Results 1 to 3 of 3
  1. #1
    falcon53 is offline Member
    Join Date
    Mar 2011
    Posts
    2
    Rep Power
    0

    Default synchronization doesn't seem to work

    Hi,

    I tried testing synchronization with the following code:

    public class InterferenceFix extends Thread
    {
    String name;
    static boolean isZero = true;
    static int counter = 0;
    public static void main(String arg[])
    {
    InterferenceFix one = new InterferenceFix("one");
    InterferenceFix two = new InterferenceFix("two");
    one.start();
    two.start();
    }
    InterferenceFix(String nameString)
    {
    name = nameString;
    }
    public void run() {
    for(int i=0; i<100000000; i++)
    {
    update();
    }
    System.out.println(name + ": " + counter);
    }
    synchronized void update()
    {
    if(isZero) {
    isZero = false;
    counter++;
    } else {
    isZero = true;
    counter--;
    }
    }
    }

    the counter should be be 0 or 1 in both threads. Sometimes I get this result,
    but sometimes different (plus or minus a few hundred).

    Can anyone explain to me why synchronization doesn't work here?

    thanks

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default

    The synchronized keyword for a method synchronizes on 'this', i.e. the object that executes the method; in your example the one and two objects synchronize on the objects 'one' and 'two' respectively which is not what you want. Create a separate object, make it known to your objects and make them synchronize on that shared object.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    falcon53 is offline Member
    Join Date
    Mar 2011
    Posts
    2
    Rep Power
    0

Similar Threads

  1. Thread synchronization
    By rajanis in forum Threads and Synchronization
    Replies: 0
    Last Post: 01-07-2011, 07:38 AM
  2. Synchronization Problem
    By T3X4S in forum New To Java
    Replies: 0
    Last Post: 09-17-2010, 05:35 AM
  3. Animation Synchronization
    By dreadrocksean in forum Advanced Java
    Replies: 5
    Last Post: 08-08-2008, 02:56 AM
  4. synchronization question
    By oguz in forum Threads and Synchronization
    Replies: 2
    Last Post: 07-22-2008, 08:56 AM
  5. Synchronization Doesn't seem to work
    By sherinpearl in forum Threads and Synchronization
    Replies: 1
    Last Post: 04-23-2008, 06:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •