Class ThreadPool

All Implemented Interfaces:
Proxy

@Generated("org.javagi.JavaGI") public class ThreadPool extends ProxyInstance

The GThreadPool struct represents a thread pool.

A thread pool is useful when you wish to asynchronously fork out the execution of work and continue working in your own thread. If that will happen often, the overhead of starting and destroying a thread each time might be too high. In such cases reusing already started threads seems like a good idea. And it indeed is, but implementing this can be tedious and error-prone.

Therefore GLib provides thread pools for your convenience. An added advantage is, that the threads can be shared between the different subsystems of your program, when they are using GLib.

To create a new thread pool, you use new_(Func, int, boolean). It is destroyed by free(boolean, boolean).

If you want to execute a certain task within a thread pool, use push(MemorySegment).

To get the current number of running threads you call getNumThreads(). To get the number of still unprocessed tasks you call unprocessed(). To control the maximum number of threads for a thread pool, you use getMaxThreads(). and setMaxThreads(int).

Finally you can control the number of unused threads, that are kept alive by GLib for future use. The current number can be fetched with getNumUnusedThreads(). The maximum number can be controlled by getMaxUnusedThreads() and setMaxUnusedThreads(int). All currently unused threads can be stopped by calling stopUnusedThreads().

  • Constructor Summary

    Constructors
    Constructor
    Description
    Allocate a new ThreadPool.
    Allocate a new ThreadPool.
    Create a ThreadPool proxy instance for the provided memory address.
    ThreadPool(Func func, MemorySegment userData, boolean exclusive)
    Allocate a new ThreadPool with the fields set to the provided values.
    ThreadPool(Func func, MemorySegment userData, boolean exclusive, Arena arena)
    Allocate a new ThreadPool with the fields set to the provided values.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    free(boolean immediate, boolean wait_)
    Frees all resources allocated for pool.
    static int
    This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.
    int
    Returns the maximal number of threads for pool.
    static int
    Returns the maximal allowed number of unused threads.
    The memory layout of the native struct.
    int
    Returns the number of threads currently running in pool.
    static int
    Returns the number of currently unused threads.
    boolean
    moveToFront(@Nullable MemorySegment data)
    Moves the item to the front of the queue of unprocessed items, so that it will be processed next.
    static ThreadPool
    new_(@Nullable Func func, int maxThreads, boolean exclusive)
    This function creates a new thread pool.
    static ThreadPool
    newFull(@Nullable Func func, int maxThreads, boolean exclusive)
    This function creates a new thread pool similar to g_thread_pool_new() but allowing itemFreeFunc to be specified to free the data passed to g_thread_pool_push() in the case that the GThreadPool is stopped and freed before all tasks have been executed.
    boolean
    push(@Nullable MemorySegment data)
    Inserts data into the list of tasks to be executed by pool.
    boolean
    Read the value of the field exclusive.
    @Nullable Func
    Read the value of the field func.
    Read the value of the field user_data.
    static void
    setMaxIdleTime(int interval)
    This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped.
    boolean
    setMaxThreads(int maxThreads)
    Sets the maximal allowed number of threads for pool. A value of -1 means that the maximal number of threads is unlimited.
    static void
    setMaxUnusedThreads(int maxThreads)
    Sets the maximal number of unused threads to maxThreads. If maxThreads is -1, no limit is imposed on the number of unused threads.
    void
    Sets the function used to sort the list of tasks.
    static void
    Stops all currently unused threads.
    int
    Returns the number of tasks still unprocessed in pool.
    void
    writeExclusive(boolean exclusive)
    Write a value in the field exclusive.
    void
    writeFunc(@Nullable Func func, Arena _arena)
    Write a value in the field func.
    void
    Write a value in the field user_data.

    Methods inherited from class ProxyInstance

    equals, handle, hashCode

    Methods inherited from class Object

    clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • ThreadPool

      public ThreadPool(MemorySegment address)
      Create a ThreadPool proxy instance for the provided memory address.
      Parameters:
      address - the memory address of the native object
    • ThreadPool

      public ThreadPool(Arena arena)
      Allocate a new ThreadPool.
      Parameters:
      arena - to control the memory allocation scope
    • ThreadPool

      public ThreadPool()
      Allocate a new ThreadPool. The memory is allocated with Arena.ofAuto().
    • ThreadPool

      public ThreadPool(Func func, MemorySegment userData, boolean exclusive, Arena arena)
      Allocate a new ThreadPool with the fields set to the provided values.
      Parameters:
      func - value for the field func
      userData - value for the field userData
      exclusive - value for the field exclusive
      arena - to control the memory allocation scope
    • ThreadPool

      public ThreadPool(Func func, MemorySegment userData, boolean exclusive)
      Allocate a new ThreadPool with the fields set to the provided values. The memory is allocated with Arena.ofAuto().
      Parameters:
      func - value for the field func
      userData - value for the field userData
      exclusive - value for the field exclusive
  • Method Details

    • getMemoryLayout

      public static MemoryLayout getMemoryLayout()
      The memory layout of the native struct.
      Returns:
      the memory layout
    • readFunc

      public @Nullable Func readFunc()
      Read the value of the field func.
      Returns:
      The value of the field func
    • writeFunc

      public void writeFunc(@Nullable Func func, Arena _arena)
      Write a value in the field func.
      Parameters:
      func - The new value for the field func
      _arena - to control the memory allocation scope
    • readUserData

      public MemorySegment readUserData()
      Read the value of the field user_data.
      Returns:
      The value of the field user_data
    • writeUserData

      public void writeUserData(MemorySegment userData)
      Write a value in the field user_data.
      Parameters:
      userData - The new value for the field user_data
    • readExclusive

      public boolean readExclusive()
      Read the value of the field exclusive.
      Returns:
      The value of the field exclusive
    • writeExclusive

      public void writeExclusive(boolean exclusive)
      Write a value in the field exclusive.
      Parameters:
      exclusive - The new value for the field exclusive
    • getMaxIdleTime

      public static int getMaxIdleTime()

      This function will return the maximum interval that a thread will wait in the thread pool for new tasks before being stopped.

      If this function returns 0, threads waiting in the thread pool for new work are not stopped.

      Returns:
      the maximum interval (milliseconds) to wait for new tasks in the thread pool before stopping the thread
      Since:
      2.10
    • getMaxUnusedThreads

      public static int getMaxUnusedThreads()
      Returns the maximal allowed number of unused threads.
      Returns:
      the maximal number of unused threads
    • getNumUnusedThreads

      public static int getNumUnusedThreads()
      Returns the number of currently unused threads.
      Returns:
      the number of currently unused threads
    • new_

      public static ThreadPool new_(@Nullable Func func, int maxThreads, boolean exclusive) throws GErrorException

      This function creates a new thread pool.

      Whenever you call g_thread_pool_push(), either a new thread is created or an unused one is reused. At most maxThreads threads are running concurrently for this thread pool. maxThreads = -1 allows unlimited threads to be created for this thread pool. The newly created or reused thread now executes the function func with the two arguments. The first one is the parameter to g_thread_pool_push() and the second one is userData.

      Pass g_get_num_processors() to maxThreads to create as many threads as there are logical processors on the system. This will not pin each thread to a specific processor.

      The parameter exclusive determines whether the thread pool owns all threads exclusive or shares them with other thread pools. If exclusive is true, maxThreads threads are started immediately and they will run exclusively for this thread pool until it is destroyed by g_thread_pool_free(). If exclusive is false, threads are created when needed and shared between all non-exclusive thread pools. This implies that maxThreads may not be -1 for exclusive thread pools. Besides, exclusive thread pools are not affected by g_thread_pool_set_max_idle_time() since their threads are never considered idle and returned to the global pool.

      Note that the threads used by exclusive thread pools will all inherit the scheduler settings of the current thread while the threads used by non-exclusive thread pools will inherit the scheduler settings from the first thread that created such a thread pool.

      At least one thread will be spawned when this function is called, either to create the maxThreads exclusive threads, or to preserve the scheduler settings of the current thread for future spawns.

      error can be null to ignore errors, or non-null to report errors. An error can only occur when exclusive is set to true and not all maxThreads threads could be created. See GThreadError for possible errors that may occur. Note, even in case of error a valid GThreadPool is returned.

      Parameters:
      func - a function to execute in the threads of the new thread pool
      maxThreads - the maximal number of threads to execute concurrently in the new thread pool, -1 means no limit
      exclusive - should this thread pool be exclusive?
      Returns:
      the new GThreadPool
      Throws:
      GErrorException - see GError
    • newFull

      public static ThreadPool newFull(@Nullable Func func, int maxThreads, boolean exclusive) throws GErrorException

      This function creates a new thread pool similar to g_thread_pool_new() but allowing itemFreeFunc to be specified to free the data passed to g_thread_pool_push() in the case that the GThreadPool is stopped and freed before all tasks have been executed.

      itemFreeFunc will not be called on items successfully passed to func. func is responsible for freeing the items passed to it.

      Parameters:
      func - a function to execute in the threads of the new thread pool
      maxThreads - the maximal number of threads to execute concurrently in the new thread pool, -1 means no limit
      exclusive - should this thread pool be exclusive?
      Returns:
      the new GThreadPool
      Throws:
      GErrorException - see GError
      Since:
      2.70
    • setMaxIdleTime

      public static void setMaxIdleTime(int interval)

      This function will set the maximum interval that a thread waiting in the pool for new tasks can be idle for before being stopped. This function is similar to calling g_thread_pool_stop_unused_threads() on a regular timeout, except this is done on a per thread basis.

      By setting interval to 0, idle threads will not be stopped.

      The default value is 15000 (15 seconds).

      Parameters:
      interval - the maximum interval (in milliseconds) a thread can be idle
      Since:
      2.10
    • setMaxUnusedThreads

      public static void setMaxUnusedThreads(int maxThreads)

      Sets the maximal number of unused threads to maxThreads. If maxThreads is -1, no limit is imposed on the number of unused threads.

      The default value is 8 since GLib 2.84. Previously the default value was 2.

      Parameters:
      maxThreads - maximal number of unused threads
    • stopUnusedThreads

      public static void stopUnusedThreads()
      Stops all currently unused threads. This does not change the maximal number of unused threads. This function can be used to regularly stop all unused threads e.g. from g_timeout_add().
    • free

      public void free(boolean immediate, boolean wait_)

      Frees all resources allocated for pool.

      If immediate is true, no new task is processed for pool. Otherwise this ThreadPool is not freed before the last task is processed. Note however, that no thread of this pool is interrupted while processing a task. Instead at least all still running threads can finish their tasks before the this ThreadPool is freed.

      If wait_ is true, this function does not return before all tasks to be processed (dependent on immediate, whether all or only the currently running) are ready. Otherwise this function returns immediately.

      After calling this function this ThreadPool must not be used anymore.

      Parameters:
      immediate - should this ThreadPool shut down immediately?
      wait_ - should the function wait for all tasks to be finished?
    • getMaxThreads

      public int getMaxThreads()
      Returns the maximal number of threads for pool.
      Returns:
      the maximal number of threads
    • getNumThreads

      public int getNumThreads()
      Returns the number of threads currently running in pool.
      Returns:
      the number of threads currently running
    • moveToFront

      public boolean moveToFront(@Nullable MemorySegment data)
      Moves the item to the front of the queue of unprocessed items, so that it will be processed next.
      Parameters:
      data - an unprocessed item in the pool
      Returns:
      true if the item was found and moved
      Since:
      2.46
    • push

      public boolean push(@Nullable MemorySegment data) throws GErrorException

      Inserts data into the list of tasks to be executed by pool.

      When the number of currently running threads is lower than the maximal allowed number of threads, a new thread is started (or reused) with the properties given to g_thread_pool_new(). Otherwise, data stays in the queue until a thread in this pool finishes its previous task and processes data.

      error can be null to ignore errors, or non-null to report errors. An error can only occur when a new thread couldn't be created. In that case data is simply appended to the queue of work to do.

      Before version 2.32, this function did not return a success status.

      Parameters:
      data - a new task for this ThreadPool
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
    • setMaxThreads

      public boolean setMaxThreads(int maxThreads) throws GErrorException

      Sets the maximal allowed number of threads for pool. A value of -1 means that the maximal number of threads is unlimited. If this ThreadPool is an exclusive thread pool, setting the maximal number of threads to -1 is not allowed.

      Setting maxThreads to 0 means stopping all work for pool. It is effectively frozen until maxThreads is set to a non-zero value again.

      A thread is never terminated while calling func, as supplied by g_thread_pool_new(). Instead the maximal number of threads only has effect for the allocation of new threads in g_thread_pool_push(). A new thread is allocated, whenever the number of currently running threads in this ThreadPool is smaller than the maximal number.

      error can be null to ignore errors, or non-null to report errors. An error can only occur when a new thread couldn't be created.

      Before version 2.32, this function did not return a success status.

      Parameters:
      maxThreads - a new maximal number of threads for pool, or -1 for unlimited
      Returns:
      true on success, false if an error occurred
      Throws:
      GErrorException - see GError
    • setSortFunction

      public void setSortFunction(@Nullable CompareDataFunc func)

      Sets the function used to sort the list of tasks. This allows the tasks to be processed by a priority determined by func, and not just in the order in which they were added to the pool.

      Note, if the maximum number of threads is more than 1, the order that threads are executed cannot be guaranteed 100%. Threads are scheduled by the operating system and are executed at random. It cannot be assumed that threads are executed in the order they are created.

      Parameters:
      func - the GCompareDataFunc used to sort the list of tasks. This function is passed two tasks. It should return 0 if the order in which they are handled does not matter, a negative value if the first task should be processed before the second or a positive value if the second task should be processed first.
      Since:
      2.10
    • unprocessed

      public int unprocessed()
      Returns the number of tasks still unprocessed in pool.
      Returns:
      the number of unprocessed tasks