Skip to content
This repository has been archived by the owner on Oct 19, 2019. It is now read-only.

Commit

Permalink
Add Dispose()
Browse files Browse the repository at this point in the history
Fixes #36, #37
  • Loading branch information
vanbroup authored and ry committed Mar 3, 2016
1 parent f4ec83d commit 821be27
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
26 changes: 20 additions & 6 deletions worker.go
Expand Up @@ -45,6 +45,7 @@ type worker struct {
// This is a golang wrapper around a single V8 Isolate.
type Worker struct {
*worker
disposed bool
}

// Return the V8 version E.G. "4.3.59"
Expand Down Expand Up @@ -93,18 +94,31 @@ func New(cb ReceiveMessageCallback, sync_cb ReceiveSyncMessageCallback) *Worker

w.cWorker = C.worker_new(C.int(w.tableIndex))

externalWorker := &Worker{worker: w}
externalWorker := &Worker{
worker: w,
disposed: false,
}

runtime.SetFinalizer(externalWorker, func(final_worker *Worker) {
workerTableLock.Lock()
w := final_worker.worker
delete(workerTable, w.tableIndex)
workerTableLock.Unlock()
C.worker_dispose(w.cWorker)
final_worker.Dispose()
})
return externalWorker
}

// Forcefully frees up memory associated with worker.
// GC will also free up worker memory so calling this isn't strictly necessary.
func (w *Worker) Dispose() {
if w.disposed {
panic("worker already disposed")
}
w.disposed = true
workerTableLock.Lock()
internalWorker := w.worker
delete(workerTable, internalWorker.tableIndex)
workerTableLock.Unlock()
C.worker_dispose(internalWorker.cWorker)
}

// Load and executes a javascript file with the filename specified by
// scriptName and the contents of the file specified by the param code.
func (w *Worker) Load(scriptName string, code string) error {
Expand Down
22 changes: 22 additions & 0 deletions worker_test.go
Expand Up @@ -195,3 +195,25 @@ func TestWorkerBreaking(t *testing.T) {

worker.Load("forever.js", ` while (true) { ; } `)
}

func TestTightCreateLoop(t *testing.T) {
println("create 3000 workers in tight loop to see if we get OOM")
for i := 0; i < 3000; i++ {
runSimpleWorker(t)
}
println("success")
}

func runSimpleWorker(t *testing.T) {
w := New(nil, nil)
defer w.Dispose()

err := w.Load("mytest.js", `
// Do something
var something = "Simple JavaScript";
`)

if err != nil {
t.Fatal(err)
}
}

0 comments on commit 821be27

Please sign in to comment.