Code example: Using a Mutex Object in Java (#7587)
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.concurrent.mutex;
|
||||
|
||||
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||
|
||||
@Override
|
||||
public synchronized int getNextSequence() throws InterruptedException {
|
||||
return super.getNextSequence();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user