Top X Coffee Wait, Notify, Locking Too Synchronization Interview Questions
There has been a lot of articles too books written on how to utilization hold off too notify inward Java, how they work, when do yous demand synchronization, too how to write concurrent code inward Java, but, unfortunately, I nonetheless run across many Java programmer struggles to solve even the classic producer-consumer problem. I know, writing right concurrent code is challenging too it takes a lot of practice, mean value through powerfulness too sense to acquire it right, simply at the same time, every Java programmer should live familiar amongst basics of inter-thread communication, synchronization, locking too empathize how all the things move together. They should live able to argue the output of programme when the same code is executed yesteryear to a greater extent than than 1 thread, at the same time. They should know that compiler tin re-order their code to optimize performance too how they tin forestall it.
Since many Java programmer already has a fair thought of the wait, notify, locking, too synchronization concepts, I am non going to explicate that, simply I'll acquaint about interview questions to cheque too challenge your understanding. If yous tin reply these query right too confidently without confusing yourself, too thus yous are inward proficient safe, otherwise, it's fourth dimension to read the Effective Java too Java Concurrency inward Practice again.
When do yous demand synchronization inward Java?
First too foremost, every bit a Java Programmer, yous should know when your code needs synchronization. The reply is inward the "synchronization motto" coined yesteryear Brian Goetz, which says: "If yous write a variable which may side yesteryear side live read yesteryear about other thread, or yous are reading a variable which may have got been lastly written yesteryear about other thread, yous must utilization synchronization".
Suppose yous have got next code:
Now, this closed is a boolean field, which may live laid yesteryear 1 thread, when the user presses a push too read yesteryear about other thread which is running this loop. In this case, yous demand about kind of synchronization thus that changes made yesteryear 1 thread is visible to other.
You tin attain that synchronization yesteryear using either synchronized or volatile keyword inward Java. In fact, it is the right instance of using the volatile field, which provides low-cost synchronization.
Now, at that spot are cases, where fifty-fifty though multiple threads execute the code simply yous don't demand whatever synchronization e.g. reading from HashMap 1 time it is safely initialized. Reading value is a condom functioning too tin live done without synchronization. provided the value yous are reading is non going to alter 1 time initialized e.g. final variables.
So, don't nation inward an interview that if a code is executed yesteryear multiple threads too thus yous demand synchronization, yous also needs to consider what does the code is doing. If 1 thread is reading too other is writing too thus yous definitely demand about kind of synchronization to attain the output yous want.
When to utilization hold off too notify method inward Java?
The wait(), notify(), and notifyAll() methods are tools for inter-thread communication inward Java. Another laid of similar tools is the await(), signal() too signalAll() from Java five which move amongst Lock too Condition objects. You demand this tool when your programme has multiple threads too they demand to communicate amongst each other. The best illustration of this is 1 time again the producer-consumer problem, where ii threads demand to communicate amongst each other virtually their actions because that may impact others.
For example, if the shared queue is empty too the consumer is waiting ( yous tin utilization wait() method or condition.await() inward Java five to brand a thread hold off on a condition) for an item inward the queue, the producer tin notify consumer afterwards successful insertion. Once the consumer receives that notification he tin start his chore again. See here to acquire to a greater extent than virtually how to solve producer consumer occupation using hold off too notify inward Java.
What is the divergence betwixt notify too notifyAll inward Java?
Before I reply this question, I have got a full general advice for you, ever pay attending to the name, generally it break the purpose. As the mention suggests, the notify() method transportation notification entirely to 1 of the many threads waiting on a condition, piece notifyAll() transportation the notification to all of them.
Now, inward the instance of notify() which thread volition acquire the notification? Well, a random thread is chosen. This is also 1 of the tricky multithreading questions too yous may acquire lots of follow-ups, thus brand certain yous reply it correctly, every bit yous volition run across inward side yesteryear side question.
Why using notifyAll is a safer alternative than the notify method?
If for about reason, the random thread who receives notification from the notify() method is non able to give-up the ghost on too starts waiting again, too thus your programme volition non progress further. Your application may effect inward consummate deadlock if the thread which calls notify() goes into waiting for land afterwards sending a notification because too thus at that spot is no active thread to notify all waiting threads.
That's why notifyAll() is a safer alternative than notify() because it sends a notification to all the threads. If 1 is non able to proceed, at that spot is nonetheless about to a greater extent than threads to do the job. See here to acquire to a greater extent than virtually the divergence betwixt notify too notifyAll methods inward Java.
What is incorrect amongst this code inward multi-threading surround inward Java?
This code is inspired yesteryear depository fiscal establishment illustration given inward Core Java Volume 1 yesteryear Cay S. Horstmann, 1 of the best books to acquire Java. It's a mutual instance of a non-atomic operation which should plough over together. If multiple threads execute this code too thus it's possible that 1 thread got deactivate afterwards testing the status i.e. sufficient residue inward the account, simply when it got upwardly too start again, the province of affairs mightiness have got changed yesteryear about other thread yesteryear processing about other withdrawal functioning too right away at that spot is non plenty fund to consummate this transaction.
In social club to brand this code thread-safe too correct, yous must roll both examine too transaction within a synchronized block every bit shown below:
If yous are using Java five too knows how to utilization the java.util.concurrent.lock.Lock interface too thus yous tin also utilization a ReentrantLock to protect this code. This is also known every bit the critical section, a code segment which should entirely live executed yesteryear 1 thread at a time.
Can a thread acquire into a synchronized block without acquiring a lock inward Java?
No, it's non possible. H5N1 thread must acquire the lock required yesteryear synchronized block earlier entering. The synchronized keyword acquires the lock when a Thread enters too releases the lock Thread leaves the block. Since at that spot tin live entirely 1 lock too if it is used yesteryear about other thread than this thread needs to hold off until the lock is available.
Now at that spot tin live many gotchas, sometimes Java programmer uses unlike locks to protect the same resource, which is apparently wrong. It's similar ii doors inward your bath amongst split locks too keys. You don't desire individual to run across yous when yous are within the privy right?
So, yous must utilization same lock object or mutex to protect same resources, if yous have got to utilization multiple locks too thus utilization multi-level locks i.e. yous opened upwardly line solid door too thus yous opened upwardly privy door, thus yous demand both line solid too privy keys to utilization the toilet.
What happens to the thread afterwards calling wait() method? Does it render lock?
This is 1 of the most interesting questions on this topic. I have got seen many programmers confuse themselves when asked during interviews, how come upwardly the other thread got lock when start thread stuck afterwards calling wait()?
Well, when a thread sees that status to give-up the ghost on farther is non ok, it decides to hold off yesteryear calling the wait() method, simply it does unloose the lock. Yes, this is truly important, a thread is non proceeding farther simply the lock is released thus that other threads waiting for the lock tin proceed. This is also the primal divergence betwixt the sleep() too the wait() method, which is used to interruption a thread (see here)
What happens to the waiting thread (who have got called wait() method) 1 time about other thread calls notifyAll()?
When a thread calls the notifyAll() or signalAll() method, all thread waiting on that status (a status associated amongst lock too notifyAll() is called on an object, which holds the lock) gets a notification. Now they are costless from waiting for the land simply they nonetheless demand CPU to live allocated yesteryear thread scheduler to give-up the ghost on further. When they acquire their chances, they give-up the ghost on further. See here to acquire to a greater extent than virtually the wait, notify too notifyAll methods inward Java.
What is the divergence betwixt a thread waiting for the lock too waiting afterwards calling wait() method?
H5N1 thread waiting for lock gets activated (become eligible to run again) 1 time a lock is costless too acquired yesteryear this lock too CPU is allocated to it. H5N1 thread waiting on status may non live runnable 1 time again fifty-fifty if the lock is costless simply he hasn't received whatever notification from about other thread e.g. until individual telephone telephone notify() or notifyAll() inward the instance of wait() too signal() or signalAll() inward the instance of waiting on a Condition object.
Why wait() method should live called from synchronized method or block?
I have got already answered this query inward proficient detail, delight read this article to empathize the jeopardy too dangers of calling hold off too notify without whatever synchronized context.
Why yous should cheque waiting status on piece loop instead of if block?
One of the interesting too Practical question. You demand to cheque the waiting status inward the loop because it's possible that fifty-fifty afterwards a wake-up telephone telephone yesteryear notify() the waiting status nonetheless holds. If a thread doesn't cheque the waiting status afterwards wake up, it mightiness do impairment yesteryear proceeding further.
This could live due to many reasons e.g. to a greater extent than than 1 thread waiting on that status too until the minute thread gets a chance, start has already proceeded too nullified that wake-up call.
For example, if 3 consumers are waiting too a producer puts 1 item inward the queue too notify all three, The start consumer volition acquire the item too other ii needs to wait. This is entirely possible when yous cheque the status inward while() loop.
Btw, that's also the touchstone idiom to utilization wait() too notify() as suggested yesteryear Joshua Bloch inward Effective Java.
Why hold off too notify method are defined inward java.lang.Object cast instead of Thread?
The curt reply is because Object is also a monitor inward Java. It comes amongst an associated lock too the wait(), notify() are associated amongst waiting for the status on lock thus it makes sense to define them inward the java.lang.Object. For the long answer, run across this article.
That's all virtually about Java interview questions on wait() too notify(), locking, synchronization too inter-thread communication. I know, it's 1 of the tricky concepts to empathize too main too that's why I have got asked tricky questions. Once yous are comfortable answering this question, your agreement of wait() too notify() volition give-up the ghost solid.
Keep writing code too thinking what happens if the same code block is run yesteryear multiple threads at the same time. Remember, Thread tin halt at whatever line, too the entirely line of code may live composed of multiple instructions e.g. ++ or != are non atomic.
I also propose reading Java Concurrency inward Practice from start to cease for at to the lowest degree 1 time. It volition help yous to fill upwardly gaps inward your existing cognition of multi-threading, synchronization, too concurrency inward Java.
Other Java Multi-threading Interview Questions yous may similar to explore
Thanks for reading this article. If yous similar this post service too thus delight percentage amongst your friends too colleagues. If yous have got whatever proposition or feedback too thus delight driblet a comment. Btw, if yous mean value that Java Concurrency inward Practice is non relevant inward the era of Java 8, too thus delight read this article earlier making your judgment.
Further Learning
Multithreading too Parallel Computing inward Java
Applying Concurrency too Multi-threading to Common Java Patterns
Java Concurrency inward Practice Course yesteryear Heinz Kabutz
Since many Java programmer already has a fair thought of the wait, notify, locking, too synchronization concepts, I am non going to explicate that, simply I'll acquaint about interview questions to cheque too challenge your understanding. If yous tin reply these query right too confidently without confusing yourself, too thus yous are inward proficient safe, otherwise, it's fourth dimension to read the Effective Java too Java Concurrency inward Practice again.
10 Locking, Synchronization, too Inter-Thread Communication Questions inward Java
Here is my listing of about of the best questions on locking, synchronization, inter-thread communication too virtually the wait, notify, too notifyAll methods inward Java. These questions are truly asked inward several Java interviews too if yous have got a duo of years of Java sense too thus yous tin reply too thus without whatever difficulty.When do yous demand synchronization inward Java?
First too foremost, every bit a Java Programmer, yous should know when your code needs synchronization. The reply is inward the "synchronization motto" coined yesteryear Brian Goetz, which says: "If yous write a variable which may side yesteryear side live read yesteryear about other thread, or yous are reading a variable which may have got been lastly written yesteryear about other thread, yous must utilization synchronization".
Suppose yous have got next code:
while(!closed){ printf("Yes, losing weigth is possible"); }
Now, this closed is a boolean field, which may live laid yesteryear 1 thread, when the user presses a push too read yesteryear about other thread which is running this loop. In this case, yous demand about kind of synchronization thus that changes made yesteryear 1 thread is visible to other.
You tin attain that synchronization yesteryear using either synchronized or volatile keyword inward Java. In fact, it is the right instance of using the volatile field, which provides low-cost synchronization.
Now, at that spot are cases, where fifty-fifty though multiple threads execute the code simply yous don't demand whatever synchronization e.g. reading from HashMap 1 time it is safely initialized. Reading value is a condom functioning too tin live done without synchronization. provided the value yous are reading is non going to alter 1 time initialized e.g. final variables.
So, don't nation inward an interview that if a code is executed yesteryear multiple threads too thus yous demand synchronization, yous also needs to consider what does the code is doing. If 1 thread is reading too other is writing too thus yous definitely demand about kind of synchronization to attain the output yous want.
When to utilization hold off too notify method inward Java?
The wait(), notify(), and notifyAll() methods are tools for inter-thread communication inward Java. Another laid of similar tools is the await(), signal() too signalAll() from Java five which move amongst Lock too Condition objects. You demand this tool when your programme has multiple threads too they demand to communicate amongst each other. The best illustration of this is 1 time again the producer-consumer problem, where ii threads demand to communicate amongst each other virtually their actions because that may impact others.
For example, if the shared queue is empty too the consumer is waiting ( yous tin utilization wait() method or condition.await() inward Java five to brand a thread hold off on a condition) for an item inward the queue, the producer tin notify consumer afterwards successful insertion. Once the consumer receives that notification he tin start his chore again. See here to acquire to a greater extent than virtually how to solve producer consumer occupation using hold off too notify inward Java.
What is the divergence betwixt notify too notifyAll inward Java?
Before I reply this question, I have got a full general advice for you, ever pay attending to the name, generally it break the purpose. As the mention suggests, the notify() method transportation notification entirely to 1 of the many threads waiting on a condition, piece notifyAll() transportation the notification to all of them.
Now, inward the instance of notify() which thread volition acquire the notification? Well, a random thread is chosen. This is also 1 of the tricky multithreading questions too yous may acquire lots of follow-ups, thus brand certain yous reply it correctly, every bit yous volition run across inward side yesteryear side question.
Why using notifyAll is a safer alternative than the notify method?
If for about reason, the random thread who receives notification from the notify() method is non able to give-up the ghost on too starts waiting again, too thus your programme volition non progress further. Your application may effect inward consummate deadlock if the thread which calls notify() goes into waiting for land afterwards sending a notification because too thus at that spot is no active thread to notify all waiting threads.
That's why notifyAll() is a safer alternative than notify() because it sends a notification to all the threads. If 1 is non able to proceed, at that spot is nonetheless about to a greater extent than threads to do the job. See here to acquire to a greater extent than virtually the divergence betwixt notify too notifyAll methods inward Java.
What is incorrect amongst this code inward multi-threading surround inward Java?
if(account.getBallance() >= withdrawl ){ double ballance = account.getBallance() - withdrawl; account.setBallance(ballance); }
This code is inspired yesteryear depository fiscal establishment illustration given inward Core Java Volume 1 yesteryear Cay S. Horstmann, 1 of the best books to acquire Java. It's a mutual instance of a non-atomic operation which should plough over together. If multiple threads execute this code too thus it's possible that 1 thread got deactivate afterwards testing the status i.e. sufficient residue inward the account, simply when it got upwardly too start again, the province of affairs mightiness have got changed yesteryear about other thread yesteryear processing about other withdrawal functioning too right away at that spot is non plenty fund to consummate this transaction.
In social club to brand this code thread-safe too correct, yous must roll both examine too transaction within a synchronized block every bit shown below:
// fellow member variable inward class Object accountLock = new Object(); sychronized(accountLock){ if(account.getBallance() > withdrawl ){ double ballance = account.getBallance() - withdrawl; account.setBallance(ballance); } }
If yous are using Java five too knows how to utilization the java.util.concurrent.lock.Lock interface too thus yous tin also utilization a ReentrantLock to protect this code. This is also known every bit the critical section, a code segment which should entirely live executed yesteryear 1 thread at a time.
Can a thread acquire into a synchronized block without acquiring a lock inward Java?
No, it's non possible. H5N1 thread must acquire the lock required yesteryear synchronized block earlier entering. The synchronized keyword acquires the lock when a Thread enters too releases the lock Thread leaves the block. Since at that spot tin live entirely 1 lock too if it is used yesteryear about other thread than this thread needs to hold off until the lock is available.
Now at that spot tin live many gotchas, sometimes Java programmer uses unlike locks to protect the same resource, which is apparently wrong. It's similar ii doors inward your bath amongst split locks too keys. You don't desire individual to run across yous when yous are within the privy right?
So, yous must utilization same lock object or mutex to protect same resources, if yous have got to utilization multiple locks too thus utilization multi-level locks i.e. yous opened upwardly line solid door too thus yous opened upwardly privy door, thus yous demand both line solid too privy keys to utilization the toilet.
What happens to the thread afterwards calling wait() method? Does it render lock?
This is 1 of the most interesting questions on this topic. I have got seen many programmers confuse themselves when asked during interviews, how come upwardly the other thread got lock when start thread stuck afterwards calling wait()?
Well, when a thread sees that status to give-up the ghost on farther is non ok, it decides to hold off yesteryear calling the wait() method, simply it does unloose the lock. Yes, this is truly important, a thread is non proceeding farther simply the lock is released thus that other threads waiting for the lock tin proceed. This is also the primal divergence betwixt the sleep() too the wait() method, which is used to interruption a thread (see here)
What happens to the waiting thread (who have got called wait() method) 1 time about other thread calls notifyAll()?
When a thread calls the notifyAll() or signalAll() method, all thread waiting on that status (a status associated amongst lock too notifyAll() is called on an object, which holds the lock) gets a notification. Now they are costless from waiting for the land simply they nonetheless demand CPU to live allocated yesteryear thread scheduler to give-up the ghost on further. When they acquire their chances, they give-up the ghost on further. See here to acquire to a greater extent than virtually the wait, notify too notifyAll methods inward Java.
What is the divergence betwixt a thread waiting for the lock too waiting afterwards calling wait() method?
H5N1 thread waiting for lock gets activated (become eligible to run again) 1 time a lock is costless too acquired yesteryear this lock too CPU is allocated to it. H5N1 thread waiting on status may non live runnable 1 time again fifty-fifty if the lock is costless simply he hasn't received whatever notification from about other thread e.g. until individual telephone telephone notify() or notifyAll() inward the instance of wait() too signal() or signalAll() inward the instance of waiting on a Condition object.
Why wait() method should live called from synchronized method or block?
I have got already answered this query inward proficient detail, delight read this article to empathize the jeopardy too dangers of calling hold off too notify without whatever synchronized context.
Why yous should cheque waiting status on piece loop instead of if block?
One of the interesting too Practical question. You demand to cheque the waiting status inward the loop because it's possible that fifty-fifty afterwards a wake-up telephone telephone yesteryear notify() the waiting status nonetheless holds. If a thread doesn't cheque the waiting status afterwards wake up, it mightiness do impairment yesteryear proceeding further.
This could live due to many reasons e.g. to a greater extent than than 1 thread waiting on that status too until the minute thread gets a chance, start has already proceeded too nullified that wake-up call.
For example, if 3 consumers are waiting too a producer puts 1 item inward the queue too notify all three, The start consumer volition acquire the item too other ii needs to wait. This is entirely possible when yous cheque the status inward while() loop.
Btw, that's also the touchstone idiom to utilization wait() too notify() as suggested yesteryear Joshua Bloch inward Effective Java.
Why hold off too notify method are defined inward java.lang.Object cast instead of Thread?
The curt reply is because Object is also a monitor inward Java. It comes amongst an associated lock too the wait(), notify() are associated amongst waiting for the status on lock thus it makes sense to define them inward the java.lang.Object. For the long answer, run across this article.
That's all virtually about Java interview questions on wait() too notify(), locking, synchronization too inter-thread communication. I know, it's 1 of the tricky concepts to empathize too main too that's why I have got asked tricky questions. Once yous are comfortable answering this question, your agreement of wait() too notify() volition give-up the ghost solid.
Keep writing code too thinking what happens if the same code block is run yesteryear multiple threads at the same time. Remember, Thread tin halt at whatever line, too the entirely line of code may live composed of multiple instructions e.g. ++ or != are non atomic.
I also propose reading Java Concurrency inward Practice from start to cease for at to the lowest degree 1 time. It volition help yous to fill upwardly gaps inward your existing cognition of multi-threading, synchronization, too concurrency inward Java.
Other Java Multi-threading Interview Questions yous may similar to explore
- Top 50 Java Thread Interview Questions amongst Answers (list)
- Top 12 Java Concurrency Questions for Experienced Programmers (see here)
- Top xv Multithreading too Concurrency Questions from Investment banks (see here)
- 133 Core Java Interview Questions from lastly five years (see here)
- How volatile variable plant inward Java? (answer)
- Top 10 Java Concurrency too multi-threading best practices (article)
- Difference betwixt start() too run() method inward Java? (answer)
Thanks for reading this article. If yous similar this post service too thus delight percentage amongst your friends too colleagues. If yous have got whatever proposition or feedback too thus delight driblet a comment. Btw, if yous mean value that Java Concurrency inward Practice is non relevant inward the era of Java 8, too thus delight read this article earlier making your judgment.
Further Learning
Multithreading too Parallel Computing inward Java
Applying Concurrency too Multi-threading to Common Java Patterns
Java Concurrency inward Practice Course yesteryear Heinz Kabutz






Komentar
Posting Komentar