|
24 | 24 | */ |
25 | 25 | package de.bluecolored.bluemap.core.util; |
26 | 26 |
|
| 27 | +import de.bluecolored.bluemap.core.logger.Logger; |
| 28 | +import org.jetbrains.annotations.Nullable; |
| 29 | + |
| 30 | +import java.time.Duration; |
| 31 | +import java.util.Timer; |
| 32 | +import java.util.TimerTask; |
27 | 33 | import java.util.concurrent.ConcurrentLinkedQueue; |
28 | 34 | import java.util.function.Function; |
29 | 35 | import java.util.function.Supplier; |
30 | 36 |
|
31 | 37 | public class InstancePool<T> { |
32 | 38 |
|
| 39 | + private static final class AutoClearTimer { |
| 40 | + private static final Timer INSTANCE = new Timer("BlueMap-InstancePool-RecycleTimer", true); |
| 41 | + } |
| 42 | + |
33 | 43 | private final Supplier<T> creator; |
34 | 44 | private final Function<T, T> recycler; |
35 | 45 | private final ConcurrentLinkedQueue<T> pool = new ConcurrentLinkedQueue<>(); |
| 46 | + private final @Nullable Duration autoClearTime; |
| 47 | + private @Nullable TimerTask autoClearTask = null; |
36 | 48 |
|
37 | 49 | public InstancePool(Supplier<T> creator) { |
38 | 50 | this.creator = creator; |
39 | 51 | this.recycler = t -> t; |
| 52 | + this.autoClearTime = null; |
40 | 53 | } |
41 | 54 |
|
42 | 55 | public InstancePool(Supplier<T> creator, Function<T, T> recycler) { |
43 | 56 | this.creator = creator; |
44 | 57 | this.recycler = recycler; |
| 58 | + this.autoClearTime = null; |
| 59 | + } |
| 60 | + |
| 61 | + public InstancePool(Supplier<T> creator, Function<T, T> recycler, @Nullable Duration autoClearTime) { |
| 62 | + this.creator = creator; |
| 63 | + this.recycler = recycler; |
| 64 | + this.autoClearTime = autoClearTime; |
| 65 | + updateAutoClear(); |
| 66 | + } |
| 67 | + |
| 68 | + private void updateAutoClear() { |
| 69 | + if (autoClearTask != null) autoClearTask.cancel(); |
| 70 | + if (autoClearTime != null) { |
| 71 | + autoClearTask = new TimerTask() { |
| 72 | + @Override |
| 73 | + public void run() { |
| 74 | + Logger.global.logInfo("Auto-clearing pool now!"); |
| 75 | + InstancePool.this.clear(); |
| 76 | + } |
| 77 | + }; |
| 78 | + AutoClearTimer.INSTANCE.schedule(autoClearTask, autoClearTime.toMillis()); |
| 79 | + } |
45 | 80 | } |
46 | 81 |
|
47 | 82 | public T claimInstance() { |
48 | 83 | T instance = pool.poll(); |
49 | 84 | if (instance == null) { |
50 | 85 | instance = creator.get(); |
51 | 86 | } |
| 87 | + updateAutoClear(); |
52 | 88 | return instance; |
53 | 89 | } |
54 | 90 |
|
55 | 91 | public void recycleInstance(T instance) { |
56 | 92 | instance = recycler.apply(instance); |
57 | 93 | if (instance != null) |
58 | 94 | pool.offer(instance); |
| 95 | + updateAutoClear(); |
59 | 96 | } |
60 | 97 |
|
61 | 98 | public void clear() { |
|
0 commit comments