Permalink
Browse files

Add Dispose()

Fixes #36, #37
  • Loading branch information...
1 parent f4ec83d commit 821be277b396341a217f16a08eb66457a1283419 @vanbroup vanbroup committed with Mar 3, 2016
Showing with 42 additions and 6 deletions.
  1. +20 −6 worker.go
  2. +22 −0 worker_test.go
View
@@ -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"
@@ -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 {
View
@@ -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.