0

Lets say I have critical section code written in method A

public void A(){
  //Critical Section 
}

I can make it synchronized so as to allow exclusive access to it

synchronized public void A(){ }

Or alternatively I can also use a Semaphore class in java

How these two approaches differ in working ?

Winn
  • 413
  • 2
  • 6
  • 17
  • 2
    possible duplicate of [Synchronized Vs Semaphore](http://stackoverflow.com/questions/16907992/synchronized-vs-semaphore) – RamonBoza Nov 20 '13 at 13:40
  • Take a look at http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html –  Nov 20 '13 at 13:40

2 Answers2

1

When using semaphore, you have to remeber to acquire it before critical section and release it after, but you can give access for more threads. Therefore it is commonly used to limit access to resources such as connection pools. You can also gain access to Semaphore object and all it's methods such as tryAcquire which lets you write more flexible code - nevertheless in case of critical sections it is better to use Lock class (just due to it's purpose) - if not synchronized block.

synchronized block is simple "lower level" (than Semaphores) synchronization, it just gives access to section for one thread. You can also limit synchronized block to code which is indeed critical section by using construction:

synchronized(? extends Object) {
    // critical section
}
Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67