Synchronized Vs Semaphore
Asked Answered
T

3

30

While reading concurrency in Java, I have following doubts:

  1. Does Java provides lower level construct then synchronized for synchronization?

  2. In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)

Tharpe answered 4/6, 2013 at 0:30 Comment(1)
i think for question 1 , we can use ReentrantLock and Condition objects ,, they are kind of lower level constructs..Tharpe
B
59

Synchronized allows only one thread of execution to access the resource at the same time. Semaphore allows up to n (you get to choose n) threads of execution to access the resource at the same time.

Blatt answered 4/6, 2013 at 3:34 Comment(0)
S
12
  1. There is also volatile keyword, according to http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html volatile variable access is more efficient than accessing these variables through synchronized code

  2. java.util.concurrent.Semaphore is used to restrict the number of threads that can access a resource. That is, while synchronized allows only one thread to aquire lock and execute the synchonized block / method, Semaphore gives permission up to n threads to go and blocks the others.

Swope answered 4/6, 2013 at 3:35 Comment(3)
synchronized provides solution to both Thread interference and memory consistency errors , however volatile only provides solution to memory consistency errors,, so we cannot use volatile to provide atomicity in operations,, am I missing something here ?Tharpe
volatile provides also atomic access to long / doubleSwope
With volatile you may still have dirty reads and corrupt your shared values. So it is not a alternative for synchronized.Vagrom
C
3

There is also atomics. This gives access to the basic hardware compare-and-swap command that's the basis of all synchronization. It allows you, for example, to increment a number safely. If you ++ a volatile field, another thread executing the same instruction could read the field before your thread writes to it, then write back to it after your thread. So one increment gets lost. Atomics do the read and write "atomically" and so avoid the problem.

Actually, volatiles, synchronized statements, and atomics tend to force all thread data to be refreshed from main memory and/or written to main memory as appropriate, so none of them are really that low level. (I'm simplifying here. Unlike C#, Java does not really have a concept of "main memory".)

Cygnus answered 20/11, 2013 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.