non-blocking mutual exclusion

Discussion in 'Java' started by Giambattista Bloisi, Dec 16, 2003.

  1. Hi,
    In your opinion there is a faster way to implement a non-blocking
    multual exclusion than:

    Object sem = new Object();
    int count = 0;

    void mutex_activity() {
    synchronized(sem) {
    if(count > 0)
    return;
    count++;
    }

    //... activity

    synchronized(sem) {
    count--;
    }
    }

    I tryed with the following, but it seems to not work properly.

    volatile int count = 0;

    void mutex_activity() {
    if(++count > 1) {
    --count;
    return;
    }

    //activity...

    --count;
    }

    Regards,
    Giambattista
    Giambattista Bloisi, Dec 16, 2003
    #1
    1. Advertising

  2. "Giambattista Bloisi" <> wrote in message
    news:brmt9p$l2a$...
    > Hi,
    > In your opinion there is a faster way to implement a non-blocking
    > multual exclusion than:


    The performance of locking really depends on how it is implemented in the
    underlying JVM. If your locking is correct (a big task to begin with) try
    profiling your code to see if that's where the problem is. Otherwise you'll
    be optimizing the wrong thing.

    <code snip>

    > I tryed with the following, but it seems to not work properly.
    >
    > volatile int count = 0;
    >
    > void mutex_activity() {
    > if(++count > 1) {
    > --count;
    > return;
    > }
    >
    > //activity...
    >
    > --count;
    > }
    >
    > Regards,
    > Giambattista
    >


    From p. 97 of Doug Lea's book "In particular, composite read/write
    operations such as the "++" operation on volatile variables are not
    performed atomically." Try looking up java.util.concurrent.atomic.

    Cheers,
    Matt Humphrey, Dec 16, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. ppp
    Replies:
    1
    Views:
    409
    Patricia Shanahan
    Dec 5, 2006
  2. ppp
    Replies:
    0
    Views:
    345
  3. ppp
    Replies:
    0
    Views:
    333
  4. Replies:
    4
    Views:
    1,282
    CBFalconer
    Jul 7, 2005
  5. Replies:
    5
    Views:
    1,253
    CBFalconer
    Jul 7, 2005
Loading...

Share This Page