Alex Dragoi, SCJP 1.4, OCPJP 6
1/ on line 7 in my example: dishes.isEmpty() &
2/ on line 16 in my example dishes.get(0)
James,
You are right. If there are two ice cream men accessing the same public dishes.
But in this case, there is only one ice cream man accessing its only private dishes.
Himai Minh wrote:James,
You are right. If there are two ice cream men accessing the same public dishes.
But in this case, there is only one ice cream man accessing its only private dishes.
James Boswell wrote:To illustrate my point further, try running the following class a few times:
Alex Dragoi, SCJP 1.4, OCPJP 6
Alexandru Dragoi wrote:If our dishes queue is initially empty and some child thread adds an element to it, but in the same time IceCreamMan interrogates the queue using isEmpty() method, the IceCreamMan could see a stale state for dishes object.
So what?
We are gaining some performance because we synchronize only the write but not the read. The lock contention is actually reduced.
If IceCreamMan reads a stale value now, it is not a big deal because it will catch the updated state of the dishes at the next iteration!