First Look at Concurrency Support in Commons Lang 3.0

DZone 's Guide to

First Look at Concurrency Support in Commons Lang 3.0

· Java Zone ·
Free Resource

In the first part of the series I talked about some of the new and improved features in Commons Lang 3.0. In this article I will talk about concurrent utilities provided by Commons Lang 3.0. A new package 'org.apache.commons.lang3.concurrent' has been added which provides support classes for multi-threaded programming and makes use of Java 5 java.util.concurrent.* classes.

The main concurrency feature in this release is thread safe initialization of objects. Different concurrent initializer strategies are provided for the creation of managed objects e.g. lazy initailization or initialization on a background thread. All the initializers implement the ConcurrentInitializer interface. This interface has only one method called get(), through which objects can be queried. Lets take a look at different concurrent initializers :

  1. LazyInitializer

    This class provides a fully functional implementation of the double-check idiom for an instance field as suggested by Joshua Bloch in "Effective Java",2nd edition, item 71. It is required in cases where an object has to be initialized only when it is needed, because object creation is expensive or the consumption of memory or system resources is significant. In those cases lazy initialization can help in reducing the amount of resources used by a program. For example, suppose we have a user who has list of attachments. We don't want attachments to get loaded until we really need them so we should initialize user attachments lazily.
    publi class UserAttachmentInitializer extends
    LazyInitializer<UserAttachments> {

    protected UserAttachments initialize() throws ConcurrentException {
    List<File> attachments = loadAllAttachments();
    return new UserAttachments(attachments);

    * Loads all attachments
    * @return
    private List<File> loadAllAttachments() {
    return new ArrayList<File>();

    In order to apply lazy initialization we have to subclass the abstract LazyInitializer class and override its initialize method which returns UserAttachments. Access to the data object is provided through the get() method. So, code that wants to obtain the UserAttachments instance would simply look like this:
    UserAttachments userAttachments = new UserAttachmentInitializer().get();
    LazyInitializer guarantees that only a single instance of the wrapped object class is created, which is passed to all callers. Once initialized, calls to get() method are very fast because no synchroniation is required.
  2. AtomicInitializer

    This is another way to perform lazy initialization of objects using AtomicReference. This approach will be more efficient than LazyInitializer if the number of parallel threads is small as it does not need any synchronization. It has the drawback that initialization may be done multiple times if multiple threads access the initializer at the same time. However, it is guaranteed that the same object is always created by the initializer and will be returned.
    public class MyAtomicInitializer extends AtomicInitializer<MyObject> {

    protected MyObject initialize() throws ConcurrentException {
    MyObject myObject = new MyObject("shekhar");
    return myObject;

    Client will access in the same way as mentioned in LazyInitializer.
  3. BackgroundInitializer

    BackgroundInitializer initializes an object in the background task. It is a thin wrapper around a java.util.concurrent.Future object and uses an ExecutorService for starting a background task that performs initialization. The use of this initializer is typically in cases where we have to do expensive initialization like reading a configuration file, connecting to a external service or database etc,  at application start-up. BackgroundInitializer is an abstract class so we have to override its abstract initialize method.
    public static void main(String[] args) {
    ConnectionBackgroundInitializer initializer = new ConnectionBackgroundInitializer();
    ExecutorService exec = Executors.newSingleThreadExecutor();

    try {
    Connection connection = initializer.get();
    } catch (ConcurrentException e) {
    } finally {

    First of all a BackgroundInitializer object is created, and then the start method is called. Calls to the start method start the background processing and the application can continue working on 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. As shown in the example above, you can pass the ExecutorService before the start() method is called and it will be used for spawning a background task. If you don''t provide any ExecutorService then BackgroundInitializer creates a temporary ExecutorService and kills it after initialization is complete. In the example above, because we are providing our own ExecutorService, we have to kill it ourselves.
  4. CallableBackgroundInitializer

    This is a concrete specialized BackgroundInitializer implementation which takes a Callable in its constructor. Callable is similar to java.lang.Runnable but it can return a result and throw a checked exception. CallableBackgroundInitializer makes Callable work in a background task and its initialize method returns the result of the wrapped Callable. Usage of this class is similar to the way BackgroundInitializer works.
  5. MultiBackgroundInitializer

    This is a specialized BackgroundInitializer which can deal with multiple background initialization tasks. This is useful for applications that have to perform multiple initialization tasks that can run in parallel (i.e. that do not depend on each other).
    public void testMultiBackgroundInitializer() throws ConcurrentException {
    MultiBackgroundInitializer initializer = new MultiBackgroundInitializer();
    MyBackgroundInitializer firstInitializer = new MyBackgroundInitializer();
    MyBackgroundInitializer secondInitializer = new MyBackgroundInitializer();
    String first = "First Initializer";
    initializer.addInitializer(first, firstInitializer);
    String second = "Second Initializer";
    initializer.addInitializer(second, secondInitializer);
    MultiBackgroundInitializerResults multiBackgroundInitializerResults = initializer
    BackgroundInitializer<?> firstBackgroundInitializer = multiBackgroundInitializerResults
    BackgroundInitializer<?> secondBackgroundInitializer = multiBackgroundInitializerResults
    ((Integer) firstBackgroundInitializer.get()));
    ((Integer) secondBackgroundInitializer.get()));

    * A concrete implementation of {@code BackgroundInitializer} used for
    * defining background tasks for {@code MultiBackgroundInitializer}.
    private static class MyBackgroundInitializer extends
    BackgroundInitializer<Integer> {

    volatile int initializeCalls;

    protected Integer initialize() throws Exception {

    return initializeCalls;
This covers most of the functionality that is provided in the Commons Lang 3.0. concurrency package.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}