Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core%20Java%20Interview%20Questions%20and%20Answers

Question: What synchronization constructs does Java provide? How do they work?
Answer: The two common features that are used are:
1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock.
The following have the same effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
If you synchronize a static method, then you are synchronizing across all objects of the same class, i.e. the monitor you are using for the lock is one per class, not one per object.
2. wait/notify. wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal. In Posix C, this part is equivalent to the pthread_cond_wait method, which waits for an OS signal to continue. When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point. If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object. Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook