public class DataTimeWindow<T> { private TimeUnit unit; private int lenght; private int checkCursor; private int dataCursor; private WindowBlock<T>[] blocks; private Timer timer; public DataTimeWindow(TimeUnit unit, int length) { this(unit, length, null); } public DataTimeWindow(TimeUnit unit, int length, String name) { if (length < 1) { throw new IllegalArgumentException("window length must greater than 1"); } if (null == name) { this.timer = new Timer(); } else { this.timer = new Timer(name); } this.unit = unit; this.lenght = length; this.timer.schedule(new TimerTask() { public void run() { polling(); } }, unit.toMillis(1), unit.toMillis(1)); this.checkCursor = 1; this.dataCursor = 0; this.blocks = new WindowBlock[length]; for (int i = 0; i < length; i++) { this.blocks[i] = new WindowBlock<T>(); } } private void polling() { blocks[checkCursor].clear(); checkCursor++; if (checkCursor >= this.lenght) { checkCursor = 0; } dataCursor++; if (dataCursor >= this.lenght) { dataCursor = 0; } } public void push(T data) { if (data == null) { throw new NullPointerException(); } blocks[dataCursor].push(data); System.out.println(dataCursor); } /** * 查找数据是否存在时间窗内,根据equals方法来比较的 * * @param data * @return */ public T find(T data) { if (data == null) { return null; } for (int i = 0; i < this.lenght; i++) { WindowBlock<T> windowBlock = this.blocks[i]; T exist = windowBlock.find(data); if(exist != null) { return exist; } } return null; } /** * 查找第一个匹配的数据并从时间窗内移除,根据equals方法来比较的 * * @param data * @return */ public T pick(T data) { if (data == null) { return null; } for (int i = 0; i < this.lenght; i++) { WindowBlock<T> windowBlock = this.blocks[i]; T exist = windowBlock.remove(data); if(exist != null) { return exist; } } return null; } public TimeUnit getUnit() { return unit; } public int getLenght() { return lenght; } static class WindowBlock<T> { private ConcurrentHashMap<T, T> data = new ConcurrentHashMap<T, T>(); public void push(T data) { this.data.put(data, data); } public void clear() { this.data.clear(); } public T find(T obj) { return this.data.get(obj); } public T remove(T obj) { return this.data.remove(obj); } } }
转载于:https://my.oschina.net/zhangyaxin/blog/3069963