Sunday, February 12, 2017

Java Threading: Synchronization II

In the previous post, we looked at how synchronized methods can be used to ensure safe access to a single object, where multiple threads try to read/write to it.

Here, we improve upon the example. In the last post, I mentioned that there were still fixes to be made, and today we will discuss one of them.

Below is the copy from the previous lesson. Take a closer look at the run() method of removeThread, line 54-57 below:

You will notice that the thread continuously checks whether there is at least 1 or more elements in the queue, and when there is, it calls dequeue() method. The question is: can we guarantee that element in the queue will remain in between the two calls? That is, what if another thread calls dequeue() in between, intercepting the element first? This is certainly possible...

Solution? I'd say we fix this issue by having dequeue() method check for the number of elements in the queue. Since dequeue() method is synchronized, it is guaranteed that if there is an element, it will be able to retrieve it for sure. What if there is no element in the queue? It will return immediately with an exception stating that there is no element to retrieve. Thus, we need to modify removeThread run() method to loop dequeue() method continuously until it does not throw an exception. Take a look at code below for implementation.

The modified code above certainly is better than the previous version, but we are not done yet. There are still a few more fixes to be made, and we will tackle one by one in the subsequent posts!

No comments:

Post a Comment