# JsMacrosThreadPool

`com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool`

Runs tasks on one-shot daemon workers, each of which executes one task and exits. When workers
are removed, a background task is notified and adds a free worker if the pool is below its target;  
this does not guarantee that the target is reached.  
```js
const pool = context.getCtx().runner.threadPool;  
pool.runTask(JavaWrapper.methodToJava(function() { Chat.log("task"); }));  
```

## Nested types

- [PoolThread](JsMacrosThreadPool.PoolThread.md)

## Constructors

### new JsMacrosThreadPool {#com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool_constructor-}

```js
new JsMacrosThreadPool()
```

Uses `availableProcessors() * 3` as the free-worker target and starts replenishment.

### new JsMacrosThreadPool {#com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool_constructor-int-}

```js
new JsMacrosThreadPool(int maxFreeThreads)
```

Starts the initial workers and replenishment for the supplied free-worker target.

**Parameters:**
- `maxFreeThreads`: target number of prestarted free workers, not a concurrent-task limit

## Fields

### maxFreeThreads {#com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool_maxFreeThreads}

```js
maxFreeThreads: int
```

Target number of prestarted free workers; this is not a limit on concurrently running tasks.

## Methods

### runTask {#com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool_runTask-Runnable-}

```js
runTask(Runnable task): Thread
```

Assigns a task to a free worker, or starts a new worker if none is free.

**Parameters:**
- `task`: non-null task to execute

**Returns:** the worker selected for the task; this does not wait for task completion

### runTask {#com.jsmacrosce.jsmacros.core.threads.JsMacrosThreadPool_runTask-Runnable-Consumer-}

```js
runTask(Runnable task, Consumer<Thread> beforeRunTask): Thread
```

Invokes the hook on the calling thread before assigning the task, as in `runTask(Runnable)`.  
 If the hook throws after a free worker is removed from the pool, that worker is not restored;  
 for a newly created worker, the hook throws before task assignment and the worker is not started.

**Parameters:**
- `task`: non-null task to execute
- `beforeRunTask`: non-null hook receiving the selected worker before task assignment

**Returns:** the worker selected for the task; this does not wait for task completion
