Top Description Inners Fields Constructors Methods
org.apache.commons.lang3.concurrent

public Class BackgroundInitializer<T>

extends AbstractConcurrentInitializer<T, Exception>
Class Inheritance
Known Direct Subclasses
org.apache.commons.lang3.concurrent.CallableBackgroundInitializer, org.apache.commons.lang3.concurrent.MultiBackgroundInitializer
Type Parameters
<T>
the type of the object managed by this initializer class
Imports
java.util.concurrent.Callable, .CancellationException, .ExecutionException, .ExecutorService, .Executors, .Future, org.apache.commons.lang3.function.FailableConsumer, .FailableSupplier

A class that allows complex initialization operations in a background task.

Applications often have to do some expensive initialization steps when they are started, e.g. constructing a connection to a database, reading a configuration file, etc. Doing these things in parallel can enhance performance as the CPU load can be improved. However, when access to the resources initialized in a background thread is actually required, synchronization has to be performed to ensure that their initialization is complete.

This abstract base class provides support for this use case. A concrete subclass must implement the initialize() method. Here an arbitrary initialization can be implemented, and a result object can be returned. With this method in place the basic usage of this class is as follows (where MyBackgroundInitializer is a concrete subclass):

MyBackgroundInitializer initializer = new MyBackgroundInitializer();
initializer.start();
// Now do some other things. Initialization runs in a parallel thread
...
// Wait for the end of initialization and access the result object
Object result = initializer.get();

After the construction of a BackgroundInitializer object its start() method has to be called. This starts the background processing. The application can now continue to do other things. When it needs access to the object produced by the BackgroundInitializer it calls its get() method. If initialization is already complete, get() returns the result object immediately. Otherwise it blocks until the result object is fully constructed.

BackgroundInitializer is a thin wrapper around a Future object and uses an ExecutorService for running the background initialization task. It is possible to pass in an ExecutorService at construction time or set one using setExternalExecutor() before start() was called. Then this object is used to spawn the background task. If no ExecutorService has been provided, BackgroundInitializer creates a temporary ExecutorService and destroys it when initialization is complete.

The methods provided by BackgroundInitializer provide for minimal interaction with the wrapped Future object. It is also possible to obtain the Future object directly. Then the enhanced functionality offered by Future can be used, e.g. to check whether the background operation is complete or to cancel the operation.

Since
3.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
BackgroundInitializer.Builder<
The type of the initializer managed by this builder.
I extends BackgroundInitializer<T>
,
The type of results supplied by this builder.
T
>

Builds a new instance.

private class

Field Summary

Modifier and TypeField and Description
private ExecutorService
executor

A reference to the executor service that is actually used.

private ExecutorService
externalExecutor

The external executor service for executing tasks.

private Future<T>
future

Stores the handle to the background task.

Constructor Summary

AccessConstructor and Description
protected
BackgroundInitializer()

Creates a new instance of BackgroundInitializer.

protected
BackgroundInitializer(final ExecutorService
an external ExecutorService to be used for task. execution
exec
)

Creates a new instance of BackgroundInitializer and initializes it with the given ExecutorService.

private
BackgroundInitializer(final FailableSupplier<T, ConcurrentException>
the initializer supplier called by initialize().
initializer
,
final FailableConsumer<T, ConcurrentException>
the closer consumer called by close().
closer
,
final ExecutorService
the ExecutorService to be used @see #setExternalExecutor(ExecutorService)
exec
)

Constructs a new instance.

Method Summary

Modifier and TypeMethod and Description
public static <
the type of object to build.
T
>
BackgroundInitializer.Builder<BackgroundInitializer<T>, T>

Returns:

a new builder.
builder
()

Creates a new builder.

private ExecutorService

Returns:

the ExecutorService to be used.
createExecutor
()

Creates the ExecutorService to be used.

private Callable<T>

Returns:

a task for the background initialization.
createTask
(final ExecutorService
the ExecutorService to be destroyed by the task.
execDestroy
)

Creates a task for the background initialization.

public T

Returns:

the object produced by this initializer.
get
()

Implements org.apache.commons.lang3.function.FailableSupplier.get.

Gets the result of the background initialization.

protected final synchronized ExecutorService

Returns:

the ExecutorService for executing the background task.
getActiveExecutor
()

Gets the ExecutorService that is actually used for executing the background task.

public final synchronized ExecutorService

Returns:

the ExecutorService.
getExternalExecutor
()

Gets the external ExecutorService to be used by this class.

public synchronized Future<T>

Returns:

the Future object wrapped by this initializer.
getFuture
()

Gets the Future object that was created when start() was called.

protected int

Returns:

the number of background tasks required by this initializer.
getTaskCount
()

Gets the number of background tasks to be created for this initializer.

protected Exception
getTypedException(final Exception e)

Implements abstract org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.getTypedException.

Gets an Exception with a type of E as defined by a concrete subclass of this class.

public synchronized boolean

Returns:

true if initialization completed successfully, otherwise false.
isInitialized
()

Implements abstract org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.isInitialized.

Tests whether this instance is initialized.

public synchronized boolean

Returns:

a flag whether the start() method has already been called.
isStarted
()

Tests whether this BackgroundInitializer has already been started.

public final synchronized void
setExternalExecutor(final ExecutorService
the ExecutorService to be used.
externalExecutor
)

Sets an ExecutorService to be used by this class.

public synchronized boolean

Returns:

a flag whether the initializer could be started successfully.
start
()

Starts the background initialization.

Inherited from org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer:
closeinitialize

Field Detail

executorback to summary
private ExecutorService executor

A reference to the executor service that is actually used.

externalExecutorback to summary
private ExecutorService externalExecutor

The external executor service for executing tasks.

futureback to summary
private Future<T> future

Stores the handle to the background task.

Constructor Detail

BackgroundInitializerback to summary
protected BackgroundInitializer()

Creates a new instance of BackgroundInitializer. No external ExecutorService is used.

BackgroundInitializerback to summary
protected BackgroundInitializer(final ExecutorService exec)

Creates a new instance of BackgroundInitializer and initializes it with the given ExecutorService. If the ExecutorService is not null, the background task for initializing this object will be scheduled at this service. Otherwise a new temporary ExecutorService is created.

Parameters
exec:ExecutorService

an external ExecutorService to be used for task. execution

BackgroundInitializerback to summary
private BackgroundInitializer(final FailableSupplier<T, ConcurrentException> initializer, final FailableConsumer<T, ConcurrentException> closer, final ExecutorService exec)

Constructs a new instance.

Parameters
initializer:FailableSupplier<T, ConcurrentException>

the initializer supplier called by initialize().

closer:FailableConsumer<T, ConcurrentException>

the closer consumer called by close().

exec:ExecutorService

the ExecutorService to be used @see #setExternalExecutor(ExecutorService)

Method Detail

builderback to summary
public static <T> BackgroundInitializer.Builder<BackgroundInitializer<T>, T> builder()

Creates a new builder.

Parameters
<T>
the type of object to build.
Returns:BackgroundInitializer.Builder<BackgroundInitializer<T>, T>

a new builder.

Since
3.14.0
createExecutorback to summary
private ExecutorService createExecutor()

Creates the ExecutorService to be used. This method is called if no ExecutorService was provided at construction time.

Returns:ExecutorService

the ExecutorService to be used.

createTaskback to summary
private Callable<T> createTask(final ExecutorService execDestroy)

Creates a task for the background initialization. The Callable object returned by this method is passed to the ExecutorService. This implementation returns a task that invokes the initialize() method. If a temporary ExecutorService is used, it is destroyed at the end of the task.

Parameters
execDestroy:ExecutorService

the ExecutorService to be destroyed by the task.

Returns:Callable<T>

a task for the background initialization.

getback to summary
public T get() throws ConcurrentException

Implements org.apache.commons.lang3.function.FailableSupplier.get.

Gets the result of the background initialization. This method blocks until initialization is complete. If the background processing caused a runtime exception, it is directly thrown by this method. Checked exceptions, including InterruptedException are wrapped in a ConcurrentException. Calling this method before start() was called causes an IllegalStateException exception to be thrown.

Returns:T

the object produced by this initializer.

Annotations
@Override
Exceptions
ConcurrentException:
if a checked exception occurred during background processing.
IllegalStateException:
if start() has not been called.
getActiveExecutorback to summary
protected final synchronized ExecutorService getActiveExecutor()

Gets the ExecutorService that is actually used for executing the background task. This method can be called after start() (before start() it returns null). If an external executor was set, this is also the active executor. Otherwise this method returns the temporary executor that was created by this object.

Returns:ExecutorService

the ExecutorService for executing the background task.

getExternalExecutorback to summary
public final synchronized ExecutorService getExternalExecutor()

Gets the external ExecutorService to be used by this class.

Returns:ExecutorService

the ExecutorService.

getFutureback to summary
public synchronized Future<T> getFuture()

Gets the Future object that was created when start() was called. Therefore this method can only be called after start().

Returns:Future<T>

the Future object wrapped by this initializer.

Exceptions
IllegalStateException:
if start() has not been called.
getTaskCountback to summary
protected int getTaskCount()

Gets the number of background tasks to be created for this initializer. This information is evaluated when a temporary ExecutorService is created. This base implementation returns 1. Derived classes that do more complex background processing can override it. This method is called from a synchronized block by the start() method. Therefore overriding methods should be careful with obtaining other locks and return as fast as possible.

Returns:int

the number of background tasks required by this initializer.

getTypedExceptionback to summary
protected Exception getTypedException(final Exception e)

Implements abstract org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.getTypedException.

Doc from org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.getTypedException.

Gets an Exception with a type of E as defined by a concrete subclass of this class.

Annotations
@Override
isInitializedback to summary
public synchronized boolean isInitialized()

Implements abstract org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.isInitialized.

Tests whether this instance is initialized. Once initialized, always returns true. If initialization failed then the failure will be cached and this will never return true.

Returns:boolean

true if initialization completed successfully, otherwise false.

Annotations
@Override
Since
3.14.0
isStartedback to summary
public synchronized boolean isStarted()

Tests whether this BackgroundInitializer has already been started.

Returns:boolean

a flag whether the start() method has already been called.

setExternalExecutorback to summary
public final synchronized void setExternalExecutor(final ExecutorService externalExecutor)

Sets an ExecutorService to be used by this class. The ExecutorService passed to this method is used for executing the background task. Thus it is possible to re-use an already existing ExecutorService or to use a specially configured one. If no ExecutorService is set, this instance creates a temporary one and destroys it after background initialization is complete. Note that this method must be called before start(); otherwise an exception is thrown.

Parameters
externalExecutor:ExecutorService

the ExecutorService to be used.

Exceptions
IllegalStateException:
if this initializer has already been started.
startback to summary
public synchronized boolean start()

Starts the background initialization. With this method the initializer becomes active and invokes the initialize() method in a background task. A BackgroundInitializer can be started exactly once. The return value of this method determines whether the start was successful: only the first invocation of this method returns true, following invocations will return false.

Returns:boolean

a flag whether the initializer could be started successfully.

org.apache.commons.lang3.concurrent back to summary

public Class BackgroundInitializer.Builder<I extends BackgroundInitializer<T>, T>

extends AbstractConcurrentInitializer.AbstractBuilder<I extends BackgroundInitializer<T>, T, BackgroundInitializer.Builder<I extends BackgroundInitializer<T>, T>, Exception>
Class Inheritance
Type Parameters
<I>
The type of the initializer managed by this builder.
<T>
The type of results supplied by this builder.

Builds a new instance.
Since
3.14.0

Field Summary

Modifier and TypeField and Description
private ExecutorService
externalExecutor

The external executor service for executing tasks.

Constructor Summary

AccessConstructor and Description
public
Builder()

Constructs a new instance.

Method Summary

Modifier and TypeMethod and Description
public I
public BackgroundInitializer.Builder<I, T>

Returns:

this instance.
setExternalExecutor
(final ExecutorService
the ExecutorService to be used.
externalExecutor
)

Sets the external executor service for executing tasks.

Inherited from org.apache.commons.lang3.concurrent.AbstractConcurrentInitializer.AbstractBuilder:
getClosergetInitializersetClosersetInitializer

Field Detail

externalExecutorback to summary
private ExecutorService externalExecutor

The external executor service for executing tasks. null is a permitted value.

Constructor Detail

Builderback to summary
public Builder()

Constructs a new instance.

Method Detail

getback to summary
public I get()

Implements org.apache.commons.lang3.function.FailableSupplier.get.

Doc from org.apache.commons.lang3.function.FailableSupplier.get.

Supplies an object

Annotations
@SuppressWarnings:unchecked
@Override
setExternalExecutorback to summary
public BackgroundInitializer.Builder<I, T> setExternalExecutor(final ExecutorService externalExecutor)

Sets the external executor service for executing tasks. null is a permitted value.

Parameters
externalExecutor:ExecutorService

the ExecutorService to be used.

Returns:BackgroundInitializer.Builder<I, T>

this instance.

See Also
org.apache.commons.lang3.concurrent.BackgroundInitializer#setExternalExecutor(ExecutorService)
org.apache.commons.lang3.concurrent back to summary

private final Class BackgroundInitializer.InitializationTask

extends Object
implements Callable<T>
Class Inheritance
  • java.lang.Object
  • org.apache.commons.lang3.concurrent.BackgroundInitializer.InitializationTask
All Implemented Interfaces
java.util.concurrent.Callable

Field Summary

Modifier and TypeField and Description
private final ExecutorService
execFinally

Stores the executor service to be destroyed at the end.

Constructor Summary

AccessConstructor and Description
pack-priv
InitializationTask(final ExecutorService exec)

Creates a new instance of InitializationTask and initializes it with the ExecutorService to be destroyed at the end.

Method Summary

Modifier and TypeMethod and Description
public T

Returns:

the result object
call
()

Implements java.util.concurrent.Callable.call.

Initiates initialization and returns the result.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

execFinallyback to summary
private final ExecutorService execFinally

Stores the executor service to be destroyed at the end.

Constructor Detail

InitializationTaskback to summary
pack-priv InitializationTask(final ExecutorService exec)

Creates a new instance of InitializationTask and initializes it with the ExecutorService to be destroyed at the end.

Parameters
exec:ExecutorService

the ExecutorService

Method Detail

callback to summary
public T call() throws Exception

Implements java.util.concurrent.Callable.call.

Initiates initialization and returns the result.

Returns:T

the result object

Annotations
@Override
Exceptions
Exception:
if an error occurs