Class ThreadPool
- All Implemented Interfaces:
Proxy
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_(org.gnome.glib.Func, int, boolean).
It is destroyed by free(boolean, boolean).
If you want to execute a certain task within a thread pool, use push(java.lang.foreign.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
ConstructorsConstructorDescriptionAllocate a new ThreadPool.ThreadPool(Arena arena) Allocate a new ThreadPool.ThreadPool(MemorySegment address) 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 TypeMethodDescriptionvoidfree(boolean immediate, boolean wait_) Frees all resources allocated forpool.static intThis function will return the maximumintervalthat a thread will wait in the thread pool for new tasks before being stopped.intReturns the maximal number of threads forpool.static intReturns the maximal allowed number of unused threads.static MemoryLayoutThe memory layout of the native struct.intReturns the number of threads currently running inpool.static intReturns the number of currently unused threads.booleanmoveToFront(@Nullable MemorySegment data) Moves the item to the front of the queue of unprocessed items, so that it will be processed next.static ThreadPoolThis function creates a new thread pool.static ThreadPoolThis function creates a new thread pool similar to g_thread_pool_new() but allowingitemFreeFuncto be specified to free the data passed to g_thread_pool_push() in the case that theGThreadPoolis stopped and freed before all tasks have been executed.booleanpush(@Nullable MemorySegment data) Insertsdatainto the list of tasks to be executed bypool.booleanRead the value of the fieldexclusive.@Nullable FuncreadFunc()Read the value of the fieldfunc.Read the value of the fielduser_data.static voidsetMaxIdleTime(int interval) This function will set the maximumintervalthat a thread waiting in the pool for new tasks can be idle for before being stopped.booleansetMaxThreads(int maxThreads) Sets the maximal allowed number of threads forpool.A value of -1 means that the maximal number of threads is unlimited.static voidsetMaxUnusedThreads(int maxThreads) Sets the maximal number of unused threads tomaxThreads.IfmaxThreadsis -1, no limit is imposed on the number of unused threads.voidsetSortFunction(@Nullable CompareDataFunc func) Sets the function used to sort the list of tasks.static voidStops all currently unused threads.intReturns the number of tasks still unprocessed inpool.voidwriteExclusive(boolean exclusive) Write a value in the fieldexclusive.voidWrite a value in the fieldfunc.voidwriteUserData(MemorySegment userData) Write a value in the fielduser_data.Methods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
ThreadPool
Create a ThreadPool proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
ThreadPool
Allocate a new ThreadPool.- Parameters:
arena- to control the memory allocation scope
-
ThreadPool
public ThreadPool()Allocate a new ThreadPool. The memory is allocated withArena.ofAuto(). -
ThreadPool
Allocate a new ThreadPool with the fields set to the provided values.- Parameters:
func- value for the fieldfuncuserData- value for the fielduserDataexclusive- value for the fieldexclusivearena- to control the memory allocation scope
-
ThreadPool
Allocate a new ThreadPool with the fields set to the provided values. The memory is allocated withArena.ofAuto().- Parameters:
func- value for the fieldfuncuserData- value for the fielduserDataexclusive- value for the fieldexclusive
-
-
Method Details
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
readFunc
Read the value of the fieldfunc.- Returns:
- The value of the field
func
-
writeFunc
-
readUserData
Read the value of the fielduser_data.- Returns:
- The value of the field
user_data
-
writeUserData
Write a value in the fielduser_data.- Parameters:
userData- The new value for the fielduser_data
-
readExclusive
public boolean readExclusive()Read the value of the fieldexclusive.- Returns:
- The value of the field
exclusive
-
writeExclusive
public void writeExclusive(boolean exclusive) Write a value in the fieldexclusive.- Parameters:
exclusive- The new value for the fieldexclusive
-
getMaxIdleTime
public static int getMaxIdleTime()This function will return the maximumintervalthat 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
maxThreadsthreads 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 functionfuncwith the two arguments. The first one is the parameter to g_thread_pool_push() and the second one isuserData.Pass g_get_num_processors() to
maxThreadsto create as many threads as there are logical processors on the system. This will not pin each thread to a specific processor.The parameter
exclusivedetermines whether the thread pool owns all threads exclusive or shares them with other thread pools. Ifexclusiveistrue,maxThreadsthreads are started immediately and they will run exclusively for this thread pool until it is destroyed by g_thread_pool_free(). Ifexclusiveisfalse, threads are created when needed and shared between all non-exclusive thread pools. This implies thatmaxThreadsmay 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
maxThreadsexclusive threads, or to preserve the scheduler settings of the current thread for future spawns.errorcan benullto ignore errors, or non-nullto report errors. An error can only occur whenexclusiveis set totrueand not allmaxThreadsthreads could be created. SeeGThreadErrorfor possible errors that may occur. Note, even in case of error a validGThreadPoolis returned.- Parameters:
func- a function to execute in the threads of the new thread poolmaxThreads- the maximal number of threads to execute concurrently in the new thread pool, -1 means no limitexclusive- should this thread pool be exclusive?- Returns:
- the new
GThreadPool - Throws:
GErrorException- seeGError
-
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 allowingitemFreeFuncto be specified to free the data passed to g_thread_pool_push() in the case that theGThreadPoolis stopped and freed before all tasks have been executed.itemFreeFuncwill not be called on items successfully passed tofunc.funcis responsible for freeing the items passed to it.- Parameters:
func- a function to execute in the threads of the new thread poolmaxThreads- the maximal number of threads to execute concurrently in the new thread pool,-1means no limitexclusive- should this thread pool be exclusive?- Returns:
- the new
GThreadPool - Throws:
GErrorException- seeGError- Since:
- 2.70
-
setMaxIdleTime
public static void setMaxIdleTime(int interval) This function will set the maximumintervalthat 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
intervalto 0, idle threads will not be stopped.The default value is 15000 (15 seconds).
- Parameters:
interval- the maximuminterval(in milliseconds) a thread can be idle- Since:
- 2.10
-
setMaxUnusedThreads
public static void setMaxUnusedThreads(int maxThreads) Sets the maximal number of unused threads tomaxThreads.IfmaxThreadsis -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 forpool.If
immediateistrue, no new task is processed forpool.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_istrue, this function does not return before all tasks to be processed (dependent onimmediate,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 forpool.- Returns:
- the maximal number of threads
-
getNumThreads
public int getNumThreads()Returns the number of threads currently running inpool.- Returns:
- the number of threads currently running
-
moveToFront
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:
trueif the item was found and moved- Since:
- 2.46
-
push
Insertsdatainto the list of tasks to be executed bypool.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,
datastays in the queue until a thread in this pool finishes its previous task and processesdata.errorcan benullto ignore errors, or non-nullto report errors. An error can only occur when a new thread couldn't be created. In that casedatais 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:
trueon success,falseif an error occurred- Throws:
GErrorException- seeGError
-
setMaxThreads
Sets the maximal allowed number of threads forpool.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
maxThreadsto 0 means stopping all work forpool.It is effectively frozen untilmaxThreadsis 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.errorcan benullto ignore errors, or non-nullto 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 forpool,or -1 for unlimited- Returns:
trueon success,falseif an error occurred- Throws:
GErrorException- seeGError
-
setSortFunction
Sets the function used to sort the list of tasks. This allows the tasks to be processed by a priority determined byfunc,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- theGCompareDataFuncused 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 inpool.- Returns:
- the number of unprocessed tasks
-