Class BackgroundInitializer<T>
- java.lang.Object
-
- org.apache.commons.lang3.concurrent.BackgroundInitializer<T>
-
- Type Parameters:
T- the type of the object managed by this initializer class
- All Implemented Interfaces:
ConcurrentInitializer<T>
- Direct Known Subclasses:
CallableBackgroundInitializer,MultiBackgroundInitializer
public abstract class BackgroundInitializer<T> extends java.lang.Object implements ConcurrentInitializer<T>
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 (whereMyBackgroundInitializeris 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
BackgroundInitializerobject itsstart()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 theBackgroundInitializerit calls itsget()method. If initialization is already complete,get()returns the result object immediately. Otherwise it blocks until the result object is fully constructed.BackgroundInitializeris a thin wrapper around aFutureobject and uses anExecutorServicefor running the background initialization task. It is possible to pass in anExecutorServiceat construction time or set one usingsetExternalExecutor()beforestart()was called. Then this object is used to spawn the background task. If noExecutorServicehas been provided,BackgroundInitializercreates a temporaryExecutorServiceand destroys it when initialization is complete.The methods provided by
BackgroundInitializerprovide for minimal interaction with the wrappedFutureobject. It is also possible to obtain theFutureobject directly. Then the enhanced functionality offered byFuturecan be used, e.g. to check whether the background operation is complete or to cancel the operation.- Since:
- 3.0
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedBackgroundInitializer()Creates a new instance ofBackgroundInitializer.protectedBackgroundInitializer(java.util.concurrent.ExecutorService exec)Creates a new instance ofBackgroundInitializerand initializes it with the givenExecutorService.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description Tget()Returns the result of the background initialization.protected java.util.concurrent.ExecutorServicegetActiveExecutor()Returns theExecutorServicethat is actually used for executing the background task.java.util.concurrent.ExecutorServicegetExternalExecutor()Returns the externalExecutorServiceto be used by this class.java.util.concurrent.Future<T>getFuture()Returns theFutureobject that was created whenstart()was called.protected intgetTaskCount()Returns the number of background tasks to be created for this initializer.protected abstract Tinitialize()Performs the initialization.booleanisStarted()Returns a flag whether thisBackgroundInitializerhas already been started.voidsetExternalExecutor(java.util.concurrent.ExecutorService externalExecutor)Sets anExecutorServiceto be used by this class.booleanstart()Starts the background initialization.
-
-
-
Constructor Detail
-
BackgroundInitializer
protected BackgroundInitializer()
Creates a new instance ofBackgroundInitializer. No externalExecutorServiceis used.
-
BackgroundInitializer
protected BackgroundInitializer(java.util.concurrent.ExecutorService exec)
Creates a new instance ofBackgroundInitializerand initializes it with the givenExecutorService. If theExecutorServiceis not null, the background task for initializing this object will be scheduled at this service. Otherwise a new temporaryExecutorServiceis created.- Parameters:
exec- an externalExecutorServiceto be used for task execution
-
-
Method Detail
-
getExternalExecutor
public final java.util.concurrent.ExecutorService getExternalExecutor()
Returns the externalExecutorServiceto be used by this class.- Returns:
- the
ExecutorService
-
isStarted
public boolean isStarted()
Returns a flag whether thisBackgroundInitializerhas already been started.- Returns:
- a flag whether the
start()method has already been called
-
setExternalExecutor
public final void setExternalExecutor(java.util.concurrent.ExecutorService externalExecutor)
Sets anExecutorServiceto be used by this class. TheExecutorServicepassed to this method is used for executing the background task. Thus it is possible to re-use an already existingExecutorServiceor to use a specially configured one. If noExecutorServiceis set, this instance creates a temporary one and destroys it after background initialization is complete. Note that this method must be called beforestart(); otherwise an exception is thrown.- Parameters:
externalExecutor- theExecutorServiceto be used- Throws:
java.lang.IllegalStateException- if this initializer has already been started
-
start
public boolean start()
Starts the background initialization. With this method the initializer becomes active and invokes theinitialize()method in a background task. ABackgroundInitializercan 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:
- a flag whether the initializer could be started successfully
-
get
public T get() throws ConcurrentException
Returns 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, includingInterruptedExceptionare wrapped in aConcurrentException. Calling this method beforestart()was called causes anIllegalStateExceptionexception to be thrown.- Specified by:
getin interfaceConcurrentInitializer<T>- Returns:
- the object produced by this initializer
- Throws:
ConcurrentException- if a checked exception occurred during background processingjava.lang.IllegalStateException- ifstart()has not been called
-
getFuture
public java.util.concurrent.Future<T> getFuture()
Returns theFutureobject that was created whenstart()was called. Therefore this method can only be called afterstart().- Returns:
- the
Futureobject wrapped by this initializer - Throws:
java.lang.IllegalStateException- ifstart()has not been called
-
getActiveExecutor
protected final java.util.concurrent.ExecutorService getActiveExecutor()
Returns theExecutorServicethat is actually used for executing the background task. This method can be called afterstart()(beforestart()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:
- the
ExecutorServicefor executing the background task
-
getTaskCount
protected int getTaskCount()
Returns the number of background tasks to be created for this initializer. This information is evaluated when a temporaryExecutorServiceis 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 thestart()method. Therefore overriding methods should be careful with obtaining other locks and return as fast as possible.- Returns:
- the number of background tasks required by this initializer
-
initialize
protected abstract T initialize() throws java.lang.Exception
Performs the initialization. This method is called in a background task when thisBackgroundInitializeris started. It must be implemented by a concrete subclass. An implementation is free to perform arbitrary initialization. The object returned by this method can be queried using theget()method.- Returns:
- a result object
- Throws:
java.lang.Exception- if an error occurs
-
-