This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I tried out the code below. I found that the topOfStack is a volatile variable. I could not really make out why is it a volatile variable. Can ayone please eloborate more on this? I just read that the topOfStack need not maintain its state. So its volatile. I really could not understand its meaning. Please eloborate.
topOfStack is volatile because it is being updated by multiple threads concurrently. Volatile makes sure that every thread gets the latest value of the variable and hence the size of the stack is strictly maintained. If the variable is not declared as volatile then the following may happen:
At a time instant when (topOfStack = size of stack -2) Thread 1 adds an element Thread 2 tries to add an element
Since, Thread 2 can have the local copy of the variable topOfStack, it still feels that the stack in *not* full and goes ahead and adds an element. This would result in replacing the element added by Thread 1 as the topOfStack value will be the same in both the threads.
Above is one of the scenarios that can arise when the variable is not volatile.
However, I'm rather unhappy about the way that StackImpl mixes synchronisation and volatile. You have some synchronised methods, then some unsynchronised methods, then a volatile variable. Even if the code actually works correctly now (which I'm not at all sure of), mixing it up like this just makes it unnecessarily complex and fragile.
If you want a thread-safe stack, wouldn't you be better off making all the methods synchronised? Synchronisation isn't slow in modern JVMs, so there is rarely any point making things complicated, to avoid it. [ October 03, 2007: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
This example was only meant for learning wait() and notify() methods [ ]. I between i noticed that if the topOfStack is not declared volatile, then you have problems [ ]... i agree this code is a bit complicated [ ]
Originally posted by Chu Tan: If the volatile instance variable is only modified by synchronized blocks, the volatile keyword is not required.
[ October 09, 2007: Message edited by: Chu Tan ]
Modification and reading both must be in a synchronized block on the same object. In this case volatile will not be required. However, as peter pointed out earlier, volatile and synchronize should not be mixed.