I want my BlockingQueue live for a certain time (it is stored in a singleton). That is, if no one came for the data in the queue for some time, it is deleted. Is it possible to implement it like that? Or maybe there are already ready-made life assignment tools for the queue?
- 2You can create a child class and override access methods so that they record (for example, in a special field) the access time. Then from time to time (by timer or how else) in the class that controls this queue, check the difference between the current time and the time of the last call, and if this difference exceeds a certain threshold, clear (or destroy) the queue. - m. vokhm
|
1 answer
This can be implemented using AOP or using Dynamic Proxy. Here is a demo using Dynamic Proxy:
public static void main(String[] args) throws InterruptedException { BlockingQueue queue = new LinkedBlockingDeque(); InvocationHandler handler = new InvocationHandler() { private BlockingQueue queue = new LinkedBlockingDeque(); private long callTime; private static final long TTL = 2000; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (System.currentTimeMillis() - callTime > TTL) { queue.clear(); } callTime = System.currentTimeMillis(); return method.invoke(queue, args); } }; BlockingQueue timedQueue = (BlockingQueue) Proxy.newProxyInstance(BlockingQueue.class.getClassLoader(), new Class<?>[]{BlockingQueue.class}, handler); queue.add("aaa"); queue.add("bbb"); queue.add("ccc"); timedQueue.add("aaa"); timedQueue.add("bbb"); Thread.sleep(3000); timedQueue.add("ccc"); System.out.println("Regular BlockingQueue implementation: " + queue.toString()); System.out.println("Timed BlockingQueue implementation: " + timedQueue.toString()); Thread.sleep(3000); System.out.println("Timed BlockingQueue implementation after one more timeout: " + timedQueue.toString()); } I advise you, nevertheless, to look at AspectJ (one of the implementations of AOP).
|