Posts

Showing posts with the label multithreading

Java: How threads communicate with each other

Threads communicate with each other with the help of 3 Object class methods 1. wait() 2. notify() 3. notifyAll() Lets look at a simple example, Consider we have 2 threads, one is mail delivery thread and another is mail-processing thread. The mail-processing thread has to keep checking to see if there's any mail to process. The mail processing thread checks for any new mail for every 2 seconds. This is truly waste of time & cpu processing power. Instead of that using wait&notify mechanism, when the mail-delivery thread puts a mail in mailbox & notifies mail-processing thread, so that it processes new mail. Key Points: 1. wait(), notify() & notifyAll() must be called from within a synchronized context. A thread cannot invoke a wait or notify method on an object unless it owns that object's lock. 2. If the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception. But a wait...

Multithreading - Why wait(), notify(), notifyAll() are defined in Object class

The methods   wait()   and   notify() , remember, are instance methods of   Object . In the same way that every object has a lock, every object can have a list of threads that are waiting for a signal (a notification) from the object. A thread gets on this waiting list by executing the   wait()   method of the target object. From that moment, it doesn’t execute any further instructions until the   notify()   method of the target object is called. If many threads are waiting on the same object, only one will be chosen (in no guaranteed order) to proceed with its execution. If there are no threads waiting, then no particular action is taken.

What is mean by Race Condition in Multithreading

Race condition is where multiple threads can access the same resource (typically an object’s instance variables) and can produce corrupted data if one thread “races in” too quickly before an operation that should be “atomic” has completed.