Programming Tutorials

Comment on Tutorial - Transient vs Volatile modifiers in Java By Reema sen



Comment Added by : Mayank

Comment Added at : 2011-01-25 15:44:21

Comment on Tutorial : Transient vs Volatile modifiers in Java By Reema sen
Real Life example of using Volatile
******************************************

class StackImpl {
private Object[] stackArray;
private volatile int topOfStack;

StackImpl (int capacity) {
stackArray = new Object[capacity];
topOfStack = -1;
}

public synchronized Object pop() {
System.out.println(Thread.currentThread() + ": popping");
while (isEmpty())
try {
System.out.println(Thread.currentThread() + ": waiting to pop");
wait(); // (1)
} catch (InterruptedException e) { }
Object obj = stackArray[topOfStack];
stackArray[topOfStack--] = null;
System.out.println(Thread.currentThread() + ": notifying after pop");
notify(); // (2)
return obj;
}

public synchronized void push(Object element) {
System.out.println(Thread.currentThread() + ": pushing");
while (isFull())
try {
System.out.println(Thread.currentThread() + ": waiting to push");
wait(); // (3)
} catch (InterruptedException e) { }
stackArray[++topOfStack] = element;
System.out.println(Thread.currentThread() + ": notifying after push");
notify(); // (4)
}

public boolean isFull() { return topOfStack >= stackArray.length -1; }
public boolean isEmpty() { return topOfStack < 0; }
}


View Tutorial