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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
public class ECache {
private final static Map<String, Entity> DATA_BASE = new HashMap<>();
private final static ScheduledExecutorService CLEANER = Executors.newSingleThreadScheduledExecutor();
public synchronized static void put(String key, Object value) { ECache.put(key, value, 0L); }
public synchronized static void put(final String key, final Object value, final long expire) { ECache.remove(key); if (expire > 0L) { Future future = CLEANER.schedule(new Runnable() { @Override public void run() { synchronized (ECache.class) { DATA_BASE.remove(key); } } }, expire, TimeUnit.MILLISECONDS); DATA_BASE.put(key, new Entity(value, expire, future)); } else { DATA_BASE.put(key, new Entity(value, null, null)); } }
public synchronized static <T> T get(String key) { Entity entity = DATA_BASE.get(key); if (entity != null && entity.isAlive()) { return (T) entity.value; } return null; }
public synchronized static <T> T remove(String key) { Entity entity = DATA_BASE.remove(key); if (entity == null) { return null; } if (entity.future != null) { entity.future.cancel(true); }
return entity.isAlive() ? (T) entity.value : null; }
private static class Entity { Object value; Long expirationTime; Future future;
Entity(Object value, Long expire, Future future) { this.value = value; this.expirationTime = (expire == null ? null : System.currentTimeMillis() + expire); this.future = future; }
boolean isAlive() { return this.expirationTime == null || this.expirationTime >= System.currentTimeMillis(); } } }
|