common-utils/src/main/java/org/warp/commonutils/concurrency/executor/ScheduledTaskLifecycle.java

52 lines
1.2 KiB
Java
Raw Normal View History

2020-12-12 22:08:14 +01:00
package org.warp.commonutils.concurrency.executor;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.locks.StampedLock;
import org.warp.commonutils.concurrency.atomicity.Atomic;
@Atomic
public class ScheduledTaskLifecycle {
private final StampedLock lock;
private final ConcurrentHashMap<ScheduledFuture<?>, Object> tasks = new ConcurrentHashMap<>();
public ScheduledTaskLifecycle() {
this.lock = new StampedLock();
}
2020-12-12 22:30:40 +01:00
/**
* Register a scheduled task
*/
2020-12-12 22:08:14 +01:00
public void registerScheduledTask(ScheduledFuture<?> task) {
this.tasks.put(task, new Object());
}
2020-12-12 22:30:40 +01:00
/**
* Mark this task as running.
* After calling this method, please call {@method endScheduledTask} inside a finally block!
*/
2020-12-12 22:08:14 +01:00
public void startScheduledTask() {
this.lock.readLock();
}
2020-12-12 22:30:40 +01:00
/**
* Mark this task as ended. Must be called after {@method startScheduledTask}
*/
2020-12-12 22:08:14 +01:00
public void endScheduledTask() {
this.lock.tryUnlockRead();
}
2020-12-12 22:30:40 +01:00
/**
* Cancel all scheduled tasks and wait all running methods to finish
*/
2020-12-12 22:08:14 +01:00
public void cancelAndWait() {
tasks.forEach((task, obj) -> {
task.cancel(false);
});
2020-12-12 22:30:40 +01:00
// Acquire a write lock to wait all tasks to end
2020-12-12 22:08:14 +01:00
lock.unlockWrite(lock.writeLock());
}
}