Threads and synchronization

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:
  1. class MyObject{
  2.   int i = 0;
  3.   public void incr(){
  4.     i++;
  5.   }
  6.  
  7.   public synchronized void work(){
  8.     // do stuff which needs to be synchronized, which uses 'i'
  9.   }
  10. }

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”

  1. No Comments

Leave a Reply





About

Welcome to the weblog of Peter Maas. Here you'll find various posts related to stuff I like (like my kids and espresso) and stuff I do (like developing software).

JavaOne 2008 Pictures


Acme Anvile at CommunityOne Keynote sea_lion javaone2008 keynote nearby hotel javaone 2008 goodybag Rudie golden_gate_warning_sign smashmouth alcatraz Hotel room Scribbled Sun Logo Joshua Bloch at JavaOne2008 pub Cable Car line Charles Nutter & Guillaume Laforge Greenland Okke en Rudie Tim Bray introducing the (J)Ruby panel Stage being build in the nearby park Java + You on a cab
View more photos >

Categories



Meld u aan voor PayPal en begin direct met het accepteren van creditcardbetalingen.