
com.huaweicloud.dws.client.worker.ActionWrapper Maven / Gradle / Ivy
package com.huaweicloud.dws.client.worker;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ProjectName: dws-connector
* @ClassName: ActionWrap
* @Description: 实现action 的生产消费模式
* @Date: 2023/1/14 17:31
* @Version: 1.0
*/
public class ActionWrapper {
private T value;
private final ReentrantLock lock;
private final Condition notEmpty;
public ActionWrapper() {
this.lock = new ReentrantLock(false);
notEmpty = lock.newCondition();
}
/**
* 当当前无使用 则将放置
*/
public boolean set(T value) {
lock.lock();
try {
if (this.value == null) {
this.value = value;
notEmpty.signalAll();
return true;
}
return false;
} finally {
lock.unlock();
}
}
/**
* 指定时间内尝试消费
*/
public T get(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
lock.lockInterruptibly();
try {
while (value == null) {
if (nanos <= 0) {
return null;
}
nanos = notEmpty.awaitNanos(nanos);
}
return value;
} finally {
lock.unlock();
}
}
/**
* 清除
*/
public void clear() {
lock.lock();
try {
value = null;
} finally {
lock.unlock();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy