CavalliumDBEngine/src/main/java/it/cavallium/dbengine/lucene/ScheduledTaskLifecycle.java

51 lines
1.2 KiB
Java
Raw Normal View History

2021-02-03 13:48:30 +01:00
package it.cavallium.dbengine.lucene;
2021-07-01 21:19:52 +02:00
import java.nio.channels.ClosedChannelException;
2021-02-03 13:48:30 +01:00
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.StampedLock;
import org.warp.commonutils.concurrency.atomicity.Atomic;
import reactor.core.Disposable;
@Atomic
public class ScheduledTaskLifecycle {
private final StampedLock lock;
2021-07-01 21:19:52 +02:00
private volatile boolean cancelled = false;
2021-02-03 13:48:30 +01:00
public ScheduledTaskLifecycle() {
this.lock = new StampedLock();
}
/**
* Mark this task as running.
* After calling this method, please call {@method endScheduledTask} inside a finally block!
*/
public void startScheduledTask() {
2021-07-01 21:19:52 +02:00
if (cancelled) {
throw new IllegalStateException("Already closed");
}
2021-02-03 13:48:30 +01:00
this.lock.readLock();
}
/**
* Mark this task as ended. Must be called after {@method startScheduledTask}
*/
public void endScheduledTask() {
this.lock.tryUnlockRead();
}
/**
* Cancel all scheduled tasks and wait all running methods to finish
*/
public void cancelAndWait() {
2021-07-01 21:19:52 +02:00
cancelled = true;
2021-02-03 13:48:30 +01:00
// Acquire a write lock to wait all tasks to end
lock.unlockWrite(lock.writeLock());
}
2021-07-01 21:19:52 +02:00
public boolean isCancelled() {
return cancelled;
}
2021-02-03 13:48:30 +01:00
}