Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between various threading synchronization options in Java?

Can someone explain the various differences between various synchronization methods in Java?

  • Syncornized blocks (like monitors?)
  • Locks - Java concurrent lock.lock()/lock.unlock()
  • Semaphores..?
  • Object.wait() & Object.notify() (like Mutex?)
  • Other classes

So really I wanted to know what are the different Java sync options commonly used and how they map to "traditional"/theoretical Mutexs, Semaphores, Locks, and Monitors.

Cheers!

like image 372
NightWolf Avatar asked Oct 09 '22 02:10

NightWolf


2 Answers

I'll give a brief clarification of each:

  • synchronized blocks are your average critical section. Not much control is given. Only one thread may acquire the lock at one time and it will automatically release it when the synchronized scope ends.
  • locks are a more flexible version of the synchronized block. Depending on the implementation they may be reentrant or may support operations like tryLock which only attempts to take the lock if it's free, otherwise returns immediately. Locks need to be unlocked explicitly.
  • a semaphore is basically a lock but with the added feature that several threads may enter the critical section at one time. It operates on the more general notion of "permits", where a semaphore may have several permits available that threads want to acquire. A thread may take one or more permits and may restore one or more permits. It allows to think about synchronization more in terms of "available resources" than in terms of "code that needs to be protected".
  • wait / notify is roughly equivalent to the concept of condition variables. Similarly, they must be protected by a synchronized block and only work correctly if they are called when a lock is held on the object being used as a monitor.
like image 74
Tudor Avatar answered Oct 17 '22 16:10

Tudor


Java has native support of threading and synchronization. The native (or low-level) way to synchronize threads is using synchronized blocks and methods ( == critical section), wait() and notify().

This technique allows you to do everything you want but unfortunately the way is sometimes pretty verbose. Doug Lea developed the concurrency package initially under Apache project. Then this package was adopted by Sun Microsystems. This package provides more convenient API.

Take a look on this article for more details: http://docs.oracle.com/javase/tutorial/essential/concurrency/

like image 40
AlexR Avatar answered Oct 17 '22 16:10

AlexR