How it works...

In the following screenshot, you can see a part of the output of one execution of this example:

The key to the example is in the printJob() method of the PrintQueue class. When we want to implement a critical section using locks and guarantee that only one execution thread will run a block of code, we have to create a ReentrantLock object. At the beginning of the critical section, we have to get control of the lock using the lock() method. When thread (A) calls this method, if no other thread has control of the lock, it gives thread (A) control of the lock and returns immediately to allow the thread to execute the critical section. Otherwise, if there is another, say thread (B), executing the critical section controlled by this lock, the lock() method puts thread (A) to sleep until thread (B) finishes the execution of the critical section.

At the end of the critical section, we have to use the unlock() method to free the control of the lock and allow other threads to run the critical section. If you don't call the unlock() method at the end of the critical section, other threads that are waiting for the block will wait forever, causing a deadlock situation. If you use try-catch blocks in your critical section, don't forget to put the sentence containing the unlock() method inside the finally section.

The other topic we tested in this example was fair mode. We had two critical sections in every job. In the previous screenshot, you saw how all the jobs execute the second part immediately after the first one. This is the usual case, but there are exceptions. This occurs when we have non-fair mode, that is to say, we pass a false value to the constructor of the ReentrantLock class.

On the contrary, when we establish fair mode by passing the true value to the constructor of the Lock class, the behavior is different. The first thread that requests control of the lock is Thread 0, then Thread 1, and so on. While Thread 0 is running the first block of code protected by the lock, we have nine threads waiting to execute the same block of code. When Thread 0 releases the lock, it immediately requests the lock again, so we have 10 threads trying to get the lock. As the fair mode is enabled, the Lock interface will choose Thread 1, as it's the thread that has been waiting for more time for the lock. Then, it chooses Thread 2, then Thread 3, and so on. Until all the threads have passed the first block protected by the lock, none of them will execute the second block protected by the lock. Once all the threads have executed the first block of code protected by the lock, then it will be the turn of Thread 0 again, then Thread 1, and so on. The following screenshot shows the difference:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.55.136