Java – synchronized vs. Semaphore

Below can be short definitions of these terms

  • synchronized – Method can be accessed by one thread at a time
  • Semaphore – Method can be accessed by n threads at a time. (n specified while initializing Semaphore)




Lets understand this with some example. Lets take example of printing. Below is a thread which takes printer & prints.

This will be tested with simple program which creates 6 threads of this with SAME printer & starts them all.

 

Now lets design our printer …

Printer with synchronized (1 print at a time)

Lets assume that

  • Our printer instance can only print one message at a time
  • It has to cool down for 300 milliseconds.

So we mark printing method as synchronized so that only one thread will print at a time & others will wait.

Output:

Notice ~300 mills gap in each print. First is at 1543804752621 & second at 1543804752925 & so on..

Printer with Semaphore (3 prints at a time)

Now lets assume that

  • We have upgraded our printer & now it can do 3 prints at a time but not more than that.
  • It still has to cool down for 300 milliseconds.

Now with synchronized we can not achieve this. We want to allow exactly 3 threads to print at the same time. Once 3 threads are in, others should keep waiting. This is where Semaphore comes to the rescue.

  • While initializing Semaphore, we can mention how many locks/permits we want to allow on particular resource. In this case 3 i.e. new Semaphore(3);
  • Unlike synchronized, in case of Semaphores, code needs to handle acquiring & releasing locks/permits. In case of synchronized this was taken care by JVM itself.

So our Printer looks like this now.

Output:

Notice that first 3 prints are almost similar time 1543805418613, 1543805418617, 1543805418613. Then there is ~300 mills wait & remaining are again almost same time 1543805418921.

This means that first 3 threads were able to get into print() method at the same time & perform print activity in parallel while other 3 threads were waiting to finish first 3 threads.



 

Leave a Reply

Your email address will not be published. Required fields are marked *