Threads and synchronization
Published by peter July 15th, 2006 in java.Yesterday we had a discussion on the way java's synchronized keyword behaves when used on method level.
I'm not shure why but somehow I expected instance variables to be automagically synchronized/locked when a thread is inside a synchronized method.
Consider the following example:
JAVA:
class MyObject{ int i = 0; public void incr(){ i++; } public synchronized void work(){ // do stuff which needs to be synchronized, which uses 'i' } }
In the example above, a thread is allowed to enter the 'incr' method, and modify 'i' while another thread is inside the 'work' method... also using 'i'. So making the method synchronized is not enough to get exclusive access to the object's instance variables. Of course there are tons of solutions for this problem, like synchronizing on 'i' or doing cunning stuff with locks.... but it certainly was a small eye-opener for me!




















0 Responses to “Threads and synchronization”
Please Wait
Leave a Reply