Friday, 1 January 2016

Java concurrent lock example


Java Concurrent Locks

java.util.concurrent.locks.Lock provides the mechanism to thread safe our java program like synchronized blocks, Since Lock is an interface, you need to use one of its implementations to use a Lock in your applications. ReentrantLock is one such implementation of Lock interface.The main differences between a Lock and a synchronized block are:

The synchronized block must be fully contained within a single method. A Lock can have it's calls to lock() and unlock() in separate methods.
Having a timeout trying to get access to a synchronized block is not possible. Using Lock.tryLock(long timeout, TimeUnit timeUnit), it is possible.

Here is one simple example to use the concurrent lock.


package com.vinod.thread;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentLockExample {
public static void main(String[] args) {
EmailProcessor emailProcessor = new EmailProcessor();
int n=25;
ExecutorService exec = Executors.newFixedThreadPool(n);
for (int i = 0; i < n; ++i) {
System.out.println(exec.submit(new SendEmailThread(emailProcessor)));


 * Class which sends email..sample
class EmailProcessor {
private final Lock emailLock = new ReentrantLock();
public void sendEmail() {
try {
System.out.println(Thread.currentThread().getName() + "Sending email " + new Date());
} catch (InterruptedException e) {
} finally {
System.out.println(Thread.currentThread().getName() + "Sending email completed");


 * Thread which is calling the email processor
class SendEmailThread implements Callable<Object> {
private EmailProcessor emailProcessor;
public SendEmailThread(EmailProcessor content) {
this.emailProcessor = content;
public Object call() throws Exception {
System.out.printf("Sending email", Thread.currentThread().getName());
return "Success";