DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. First Look at Concurrency Support in Commons Lang 3.0

First Look at Concurrency Support in Commons Lang 3.0

Shekhar Gulati user avatar by
Shekhar Gulati
·
Aug. 17, 10 · Interview
Like (1)
Save
Tweet
Share
10.87K Views

Join the DZone community and get the full member experience.

Join For Free

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> {

    @Override
    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> {

    @Override
    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();
    initializer.setExternalExecutor(exec);
    initializer.start();

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

    }
    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);
    initializer.start();
    MultiBackgroundInitializerResults multiBackgroundInitializerResults = initializer
    .get();
    assertNotNull(multiBackgroundInitializerResults);
    BackgroundInitializer<?> firstBackgroundInitializer = multiBackgroundInitializerResults
    .getInitializer(first);
    BackgroundInitializer<?> secondBackgroundInitializer = multiBackgroundInitializerResults
    .getInitializer(second);
    assertEquals(Integer.valueOf(1),
    ((Integer) firstBackgroundInitializer.get()));
    assertEquals(Integer.valueOf(1),
    ((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;

    @Override
    protected Integer initialize() throws Exception {
    initializeCalls++;

    return initializeCalls;
    }
    }
This covers most of the functionality that is provided in the Commons Lang 3.0. concurrency package.
Object (computer science) Lazy initialization

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 19 Most Common OpenSSL Commands for 2023
  • How Chat GPT-3 Changed the Life of Young DevOps Engineers
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • Software Maintenance Models

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: