Semaphores refactor

This commit is contained in:
Grzegorz Piwowarek
2017-07-03 17:39:45 +02:00
parent 20669dc6a1
commit aecdf6d5c7
4 changed files with 36 additions and 62 deletions

View File

@@ -2,17 +2,17 @@ package com.baeldung.concurrent.semaphores;
import java.util.concurrent.Semaphore;
public class CounterUsingMutex {
class CounterUsingMutex {
private final Semaphore mutex;
private int count;
public CounterUsingMutex() {
CounterUsingMutex() {
mutex = new Semaphore(1);
count = 0;
}
public void increase() throws InterruptedException {
void increase() throws InterruptedException {
mutex.acquire();
this.count = this.count + 1;
Thread.sleep(1000);
@@ -20,11 +20,11 @@ public class CounterUsingMutex {
}
public int getCount() {
int getCount() {
return this.count;
}
public boolean hasQueuedThreads() {
boolean hasQueuedThreads() {
return mutex.hasQueuedThreads();
}

View File

@@ -4,19 +4,19 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.concurrent.TimedSemaphore;
public class DelayQueueUsingTimedSemaphore {
class DelayQueueUsingTimedSemaphore {
private final TimedSemaphore semaphore;
public DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
}
public boolean tryAdd() {
boolean tryAdd() {
return semaphore.tryAcquire();
}
public int availableSlots() {
int availableSlots() {
return semaphore.getAvailablePermits();
}

View File

@@ -2,23 +2,23 @@ package com.baeldung.concurrent.semaphores;
import java.util.concurrent.Semaphore;
public class LoginQueueUsingSemaphore {
class LoginQueueUsingSemaphore {
private final Semaphore semaphore;
public LoginQueueUsingSemaphore(int slotLimit) {
LoginQueueUsingSemaphore(int slotLimit) {
semaphore = new Semaphore(slotLimit);
}
public boolean tryLogin() {
boolean tryLogin() {
return semaphore.tryAcquire();
}
public void logout() {
void logout() {
semaphore.release();
}
public int availableSlots() {
int availableSlots() {
return semaphore.availablePermits();
}