Concurrency Package

What is Semaphore in Java

Posted on Updated on

What is Semaphores

A semaphore is a counter that controls the access to one or more shared resources. This mechanism is one of the basic tools of concurrent programming and is provided by most of the programming languages.

The concept of a semaphore was introduced by Edsger Dijkstra in 1965 and was used for the first time in the THEOS operating system

Example:-  Suppose there are three shared printer in your workspace and for each print request printer do printing. Question come here how shared resources have been access control over concurrent request, solution is “Semaphores”.

Semaphores has set of permit that access control over shared resources.  In our example there are three shared printer so we set three permit on semaphore, subsequently every access to shared resources semaphore decrement it values by one until values is greater than zero. Once it’s values is zero, Means all shared resources are busy and no more permit will be allowed until any resources is free. All requesting print commands will wait for release the resources.

Useful Methods :

Constructor:-
  • Semaphore(int permits) : Create a semaphore with the given number of permits and non-fair fairness.
  • Semaphore(int permits,boolean fair) : Create a Semaphore with given number of permits and the given fairness boolean value.
Methods :-
  • acquire() – Acquires a permit from the semaphore, blocking until one of available or thread is interrupted.
  • release() – Release a permit or increment permit by one, returning it to the semaphore.

Key Points:- 

By default Fairness properties is false; means this class make no guarantees about the order in   which thread acquire permits.

Where it is used:-

  • Movie counter :- Let suppose there are three counter to get movie ticket and usually three queue of people are waiting for their turn to get ticket. every time three ticket has been given from counter. Using this example we can say that three permits are set-up for booking Counter system and every time only three tickets are allow to book in nth number of incoming request.
  • Database Connection :- Suppose we don’t want to create more than 5 database connection at a time in our application,  no matter how may incoming request are lined up.

Snippet Code here :-

Job.java:-

package com.semaphore.example;

public class Job implements Runnable {

 private SimplePrintQueue printQueue;
 public Job(SimplePrintQueue q){
 this.printQueue = q;
 }
 
 @Override
 public void run() {

 System.out.printf("%s: Going to print a job\n",Thread. currentThread().getName()); 
 printQueue.printJob(new Object());
 System.out.printf(" %s : The document has been printed \n",Thread.currentThread().getName()); 
 }
}

SimplePrintQueue.Java


package com.semaphore.example;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SimplePrintQueue {

	private final Semaphore semaphore;
	private final int NO_OF_PRINTER = 3;

	public SimplePrintQueue() {
		semaphore = new Semaphore(NO_OF_PRINTER);
	}


	public void printJob(Object object) {
		try {
			semaphore.acquire();
			long duration = (long) (Math.random() * 10);
			System.out
					.printf("%s: PrintQueue: Printing a Job in Printer  %d during %d seconds\n",
							Thread.currentThread().getName(),
							duration);
			TimeUnit.SECONDS.sleep(duration);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			semaphore.release();
		}

	}
}


Main Program 


package com.semaphore.example;

public class Main {

public static void main(String args[]) {
SimplePrintQueue printQueue = new SimplePrintQueue ();

Thread thread[] = new Thread[50];
for (int i = 0; i < 50; i++) {
thread[i] = new Thread(new Job(printQueue), "Thread" + i);
}

for (int i = 0; i < 50; i++) {
thread[i].start();
}

}

}


What is CountDownLatch in Java

Posted on Updated on

What is CountDownLatch in Java?

CountDownLatch is part of java.util.concurrent package which allow one or more threads or main Thread will wait until set of operations get accomplished.
CountDownLatch works on latching or triggering concept over set of threads, it’s coordinate among running Thread by signaling.
A CountDownLatch is initialized with a given counter/latch and the await() method will block until counter/latch reach to zero. Every invocation of countdown() method, counter/latch value is decrement by one.

Useful Methods :

Await() : It basically block current Thread until latch value reach to zero.
countdown() : It decrement latch value by one and releasing all blocking Thread unless latch has count down to zero.

How to initialized CountDownLatch?

Using public constructor it is initialized CountDownLatch with given latch size.

Example:-

CountDownLatch countDownLatch = new CountDownLatch(10);
Here latch size is 10 which means Main Thread will be block until 10 latch has count down to zero. If latch has count down to zero then Main Thread start execution.

Where we Use CountDownLatch

  •  Server Startup : we usually see when we start Server either web/application Server a lot of services initialized in console or log file before Server start up. Here we can see Server Startup Program is block until rest or dependency services are initialized.
  •  Second, suppose as per our work/project requirement we want to do some analysis on operation data that are being fetched from different databases or source system.

Snippet Code here :-

Below here, In this example code, we describe how ApplicationStartUp class is wait for turn until all their services are completed.

AbstractService.Java : It’s a base service class which has three Child classes given below that give the implementation of  abstract method service().

  • CachingService.Java
  • InMemoryService.Java
  • UIService.Java

ApplicationStartUp.Java : It’s is main program to execute all services before Server startup.

AbstractService.Java

package com.app.service;

import java.util.concurrent.CountDownLatch;

public abstract class AbstractService {

	private CountDownLatch countDownLatch;

	public AbstractService(CountDownLatch latch) {
		this.countDownLatch = latch;
	}

	public void startup() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					serviceUp();
				} catch (Exception e) {
				} finally {
					countDownLatch.countDown();
				}
			}

		}).start();
		;
	}

	public abstract void serviceUp();

}


 

CachingService.Java


package com.app.service;

import java.util.concurrent.CountDownLatch;

public class CachingService extends AbstractService {

	public CachingService(CountDownLatch latch){
		super(latch);
	}
	
	@Override
	public void serviceUp() {
		System.out.println(" CachingServer Startup complated");
		
	}

}


 

InMemoryService.Java


package com.app.service;

import java.util.concurrent.CountDownLatch;

public class InMemoryService extends AbstractService {

	public InMemoryService(CountDownLatch latch){
		super(latch);
	}
	
	@Override
	public void serviceUp() {
		System.out.println(" InMemoryService Startup complated");
		
	}

}


 

UIService.Java


package com.app.service;

import java.util.concurrent.CountDownLatch;

public class UIService extends AbstractService {

	public UIService(CountDownLatch latch){
		super(latch);
	}
	
	@Override
	public void serviceUp() {
		System.out.println(" UIService Startup complated");
		
	}

}


 

ApplicationStartUp.Java


package com.app.startup;

import java.util.concurrent.CountDownLatch;

import com.app.service.AbstractService;
import com.app.service.CachingService;
import com.app.service.InMemoryService;
import com.app.service.UIService;

public class ApplicationStartUp {
	private final CountDownLatch latch = new CountDownLatch(3);
	private final AbstractService [] services = {new CachingService(latch),new InMemoryService(latch),new UIService(latch)};
	
	public static void main(String args[]) throws InterruptedException{
		
		ApplicationStartUp app = new ApplicationStartUp();
		app.startServer();
		
	}
	
	public void startServer() throws InterruptedException
	{
		System.out.println(" Server Starting ..........................");
		for( AbstractService service:services){
			service.startup();
		}
		latch.await();
		System.out.println(" Server Started");
	}
	
}

I hope, you would be able to understand the concept of CountLatchDown.java and usage through the example and theory.

Thanks

Ajay Kumar