Code example: Using a Mutex Object in Java (#7587)

This commit is contained in:
Kamlesh Kumar
2019-08-16 11:28:26 +05:30
committed by maibin
parent b3547bc783
commit 4562a2fa07
7 changed files with 168 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
package com.baeldung.concurrent.mutex;
public class SequenceGenerator {
private int currentValue = 0;
public int getNextSequence() throws InterruptedException {
currentValue = currentValue + 1;
Thread.sleep(500);
return currentValue;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import com.google.common.util.concurrent.Monitor;
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
private Monitor monitor = new Monitor();
@Override
public int getNextSequence() throws InterruptedException {
monitor.enter();
try {
return super.getNextSequence();
} finally {
monitor.leave();
}
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import java.util.concurrent.locks.ReentrantLock;
public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
private ReentrantLock mutex = new ReentrantLock();
@Override
public int getNextSequence() throws InterruptedException {
try {
mutex.lock();
return super.getNextSequence();
} finally {
mutex.unlock();
}
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import java.util.concurrent.Semaphore;
public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
private Semaphore mutex = new Semaphore(1);
@Override
public int getNextSequence() throws InterruptedException {
try {
mutex.acquire();
return super.getNextSequence();
} finally {
mutex.release();
}
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.concurrent.mutex;
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
@Override
public int getNextSequence() throws InterruptedException {
synchronized (this) {
return super.getNextSequence();
}
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.concurrent.mutex;
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
@Override
public synchronized int getNextSequence() throws InterruptedException {
return super.getNextSequence();
}
}