While reading concurrency in Java, I have following doubts:
Does Java provides lower level construct then synchronized for synchronization?
In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)
While reading concurrency in Java, I have following doubts:
Does Java provides lower level construct then synchronized for synchronization?
In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)
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.
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
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.
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".)
© 2022 - 2024 — McMap. All rights reserved.