non-blocking mutual exclusion

  • Thread starter Giambattista Bloisi
  • Start date
G

Giambattista Bloisi

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
 
M

Matt Humphrey

Giambattista Bloisi said:
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.

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,
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top