Sunday, August 2, 2020

When to use notify() and notifyAll() in Java

As a programmer, you must not rely on any particular selection algorithm or treatment of priorities, at least if you are trying to write a Java program that is platform-independent. For example, because you don't know what order threads in the wait set will be chosen for resurrection by the notify command, you should use notify (as opposed to notify all) only when you are absolutely certain there will only be one thread suspended in the wait set. If there is a chance more than one thread will be suspended in the wait set at any one time, you should probably use notify all.

Otherwise, on some Java virtual machine implementations, a particular thread may be stuck in the wait set for a very long time. If a notify always selects the most recent arrival from the wait set and the wait set always contains multiple threads, some threads that have been waiting the longest may never be resurrected.

2 Ways to test Exception in JUnit : Annotation vs try-catch

Error handling is a core part of coding but most of the time it just went under the radar when it comes to unit testing. How do we write a JUnit test that verifies that an exception is thrown? With the try-catch construct, of course, except that this time, the code throwing an exception is a good thing—the expected behavior. The approach shown in the below code is a common pattern for testing exception-throwing behavior with JUnit.