NIOThreadPool

public final class NIOThreadPool

A thread pool that should be used if some (kernel thread) blocking work needs to be performed for which no non-blocking API exists.

When using NIO it is crucial not to block any of the EventLoops as that leads to slow downs or stalls of arbitrary other work. Unfortunately though there are tasks that applications need to achieve for which no non-blocking APIs exist. In those cases NIOThreadPool can be used but should be treated as a last resort.

Note

The prime example for missing non-blocking APIs is file IO on UNIX. The OS does not provide a usable and truly non-blocking API but with NonBlockingFileIO NIO provides a high-level API for file IO that should be preferred to running blocking file IO system calls directly on NIOThreadPool. Under the covers NonBlockingFileIO will use NIOThreadPool on all currently supported platforms though.
  • The state of the WorkItem.

    See more

    Declaration

    Swift

    public enum WorkItemState
  • The work that should be done by the NIOThreadPool.

    Declaration

    Swift

    public typealias WorkItem = (WorkItemState) -> Void
  • Gracefully shutdown this NIOThreadPool. All tasks will be run before shutdown will take place.

    Declaration

    Swift

    public func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void)

    Parameters

    queue

    The DispatchQueue used to executed the callback

    callback

    The function to be executed once the shutdown is complete.

  • Submit a WorkItem to process.

    Note

    This is a low-level method, in most cases the runIfActive method should be used.

    Declaration

    Swift

    public func submit(_ body: @escaping WorkItem)

    Parameters

    body

    The WorkItem to process by the NIOThreadPool.

  • Initialize a NIOThreadPool thread pool with numberOfThreads threads.

    Declaration

    Swift

    public init(numberOfThreads: Int)

    Parameters

    numberOfThreads

    The number of threads to use for the thread pool.

  • Start the NIOThreadPool if not already started.

    Declaration

    Swift

    public func start()
  • Runs the submitted closure if the thread pool is still active, otherwise fails the promise. The closure will be run on the thread pool so can do blocking work.

    Declaration

    Swift

    public func runIfActive<T>(eventLoop: EventLoop, _ body: @escaping () throws -> T) -> EventLoopFuture<T>

    Parameters

    eventLoop

    The EventLoop the returned EventLoopFuture will fire on.

    body

    The closure which performs some blocking work to be done on the thread pool.

    Return Value

    The EventLoopFuture of promise fulfilled with the result (or error) of the passed closure.