Improvements and unit tests
[poolifier.git] / lib / dynamic.js
index 53ff28fadf06c0fde0536edceb9358fef839510e..e5a9c690b95a27bf161519cd7a6840ef01242bcf 100644 (file)
@@ -1,11 +1,13 @@
 'use strict'
 const FixedThreadPool = require('./fixed')
+const { randomWorker } = require('./util')
+const EventEmitter = require('events')
+class MyEmitter extends EventEmitter {}
 
 /**
  * A thread pool with a min/max number of threads , is possible to execute tasks in sync or async mode as you prefer. <br>
  * This thread pool will create new workers when the other ones are busy, until the max number of threads,
- * when the max number of threads is reached, an exception will be thrown.
- * This pool will select the worker thread in a round robin fashion. <br>
+ * when the max number of threads is reached, an event will be emitted , if you want to listen this event use the emitter method.
  * @author Alessandro Pio Ardizio
  * @since 0.0.1
  */
@@ -19,6 +21,7 @@ class DynamicThreadPool extends FixedThreadPool {
   constructor (min, max, filename, opts) {
     super(min, filename, opts)
     this.max = max
+    this.emitter = new MyEmitter()
   }
 
   _chooseWorker () {
@@ -35,9 +38,9 @@ class DynamicThreadPool extends FixedThreadPool {
       return worker
     } else {
       if (this.workers.length === this.max) {
-        throw new Error('Max number of threads reached !!!')
+        this.emitter.emit('FullPool')
+        return randomWorker(this.tasks)
       }
-      // console.log('new thread is coming')
       // all workers are busy create a new worker
       const worker = this._newWorker()
       worker.port2.on('message', (message) => {