Re: servlet reference and thread safe
"gk" <srcjnu@gmail.com> writes:
if i make synchronized setter/getter methods to access those instance
variables , will that be thread safe now ?
No. Though I understand how 'yes' is tempting. Because
it would surely be easier that way.
class Subtractor {
private int subtrahend;
private int minuend;
public synchronized int getSubtrahend() {
return subtrahend;
}
public synchronized void setSubtrahend(int s) {
this.subtrahend = s;
}
public synchronized int getMinuend() {
return this.minuend;
}
public synchronized void setMinuend(int m) {
this.minuend = m;
}
public synchronized int difference() {
return minuend - subtrahend;
}
}
Let's say you have multiple threads
accessing the same Subtractor object.
Let's call them Thread 1 and Thread 2, because
I'm writing this at 3:30 AM.
This is a possible flow:
Thread 1: setMinuend(5)
Thread 1: setSubtrahend(2)
Thread 1: difference() == 3
Thread 2: setMinuend(10)
Thread 2: setSubtrahend(8)
Thread 2: difference() == 2
Hooray!
Unfortunately, this is also a possible
outcome:
Thread 1: setMinuend(5)
Thread 1: setSubtrahend(2)
Thread 2: setMinuend(10)
Thread 2: setSubtrahend(8)
Thread 1: difference() == 2
Thread 2: difference() == 2
Ooops.
Why didn't the synchronized voodoo help? It did it's job--
no two threads were allowed to access a getter or setter
at the same time. Unfortunately, that's completely pointless.
We only get the right answer if setMinuend(), setSubtrahend,
and difference() aren't all called by the same thread without
any interruption.
Go forth and sin no more.
--
Mark Jeffcoat
Austin, TX