Updated code example and test case for mutex (#7642)

This commit is contained in:
Kamlesh Kumar
2019-08-25 21:13:47 +05:30
committed by maibin
parent 58595acd6f
commit 1888614f84
7 changed files with 45 additions and 38 deletions

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
private ReentrantLock mutex = new ReentrantLock();
@Override
public int getNextSequence() throws InterruptedException {
public int getNextSequence() {
try {
mutex.lock();
return super.getNextSequence();
@@ -15,4 +15,5 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
mutex.unlock();
}
}
}

View File

@@ -7,12 +7,15 @@ public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
private Semaphore mutex = new Semaphore(1);
@Override
public int getNextSequence() throws InterruptedException {
public int getNextSequence() {
try {
mutex.acquire();
return super.getNextSequence();
} catch (InterruptedException e) {
throw new RuntimeException("Exception in critical section.", e);
} finally {
mutex.release();
}
}
}

View File

@@ -2,9 +2,11 @@ package com.baeldung.concurrent.mutex;
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
private Object mutex = new Object();
@Override
public int getNextSequence() throws InterruptedException {
synchronized (this) {
public int getNextSequence() {
synchronized (mutex) {
return super.getNextSequence();
}
}

View File

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