60 lines
1.7 KiB
Java
60 lines
1.7 KiB
Java
package com.alttd.custommobs.abilitymob;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
import java.util.UUID;
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
import java.util.concurrent.LinkedBlockingQueue;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.Future;
|
|
|
|
@Slf4j
|
|
public class AbilityThread {
|
|
|
|
private final ExecutorService executorService;
|
|
private final LinkedBlockingQueue<Runnable> taskQueue;
|
|
private final ConcurrentHashMap<UUID, Future<?>> tasksMap;
|
|
|
|
public AbilityThread() {
|
|
executorService = Executors.newSingleThreadExecutor();
|
|
taskQueue = new LinkedBlockingQueue<>();
|
|
tasksMap = new ConcurrentHashMap<>();
|
|
|
|
startProcessing();
|
|
}
|
|
|
|
private void startProcessing() {
|
|
executorService.execute(() -> {
|
|
while (!Thread.currentThread().isInterrupted()) {
|
|
try {
|
|
Runnable task = taskQueue.take();
|
|
task.run();
|
|
} catch (InterruptedException e) {
|
|
Thread.currentThread().interrupt();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
public synchronized void scheduleTask(UUID identifier, Runnable task) {
|
|
if (identifier == null) {
|
|
log.warn("Received task with null identifier, skipping");
|
|
return;
|
|
}
|
|
if (tasksMap.containsKey(identifier)) {
|
|
log.debug("Already scheduled task with identifier {}, skipping", identifier);
|
|
return;
|
|
}
|
|
Future<?> future = executorService.submit(() -> {
|
|
try {
|
|
task.run();
|
|
} finally {
|
|
tasksMap.remove(identifier);
|
|
}
|
|
});
|
|
|
|
tasksMap.put(identifier, future);
|
|
}
|
|
}
|