-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBukkitMainThreadDispatcher.java
More file actions
83 lines (71 loc) · 2.49 KB
/
BukkitMainThreadDispatcher.java
File metadata and controls
83 lines (71 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.eternalcode.commons.bukkit.scheduler;
import com.eternalcode.commons.scheduler.loom.MainThreadDispatcher;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Bukkit implementation - queues tasks from VT to main thread.
*/
public final class BukkitMainThreadDispatcher implements MainThreadDispatcher {
private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
private final Plugin plugin;
private final BukkitScheduler bukkitScheduler;
private final BukkitTask tickTask;
public BukkitMainThreadDispatcher(Plugin plugin) {
this.plugin = plugin;
this.bukkitScheduler = plugin.getServer().getScheduler();
this.tickTask = this.bukkitScheduler.runTaskTimer(this.plugin, this::drainQueue, 1L, 1L);
}
private void drainQueue() {
Runnable task;
while ((task = this.queue.poll()) != null) {
try {
task.run();
} catch (Throwable t) {
this.plugin.getLogger().severe("Exception in sync task: " + t.getMessage());
t.printStackTrace();
}
}
}
@Override
public void dispatch(Runnable task) {
if (isMainThread()) {
try {
task.run();
} catch (Throwable t) {
this.plugin.getLogger().severe("Exception in sync task: " + t.getMessage());
t.printStackTrace();
}
return;
}
this.queue.offer(task);
}
@Override
public boolean isMainThread() {
return this.plugin.getServer().isPrimaryThread();
}
@Override
public void dispatchLater(Runnable task, long ticks) {
this.bukkitScheduler.runTaskLater(this.plugin, task, ticks);
}
@Override
public Cancellable dispatchTimer(Runnable task, long delay, long period) {
BukkitTask t = this.bukkitScheduler.runTaskTimer(this.plugin, task, delay, period);
return t::cancel;
}
public void shutdown() {
this.tickTask.cancel();
Runnable task;
while ((task = this.queue.poll()) != null) {
try {
task.run();
} catch (Throwable t) {
this.plugin.getLogger().severe("Exception in shutdown task: " + t.getMessage());
}
}
}
public int getPendingCount() {
return this.queue.size();
}
}