package com.sunyard; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * 管理多线程间对象 * 类似 ThreadLocal * @param */ public class MutiThreadHander { private static class Handler { private T obj = null; private long creatAt = System.currentTimeMillis(); private long lastGetAt = System.currentTimeMillis(); public Handler(T obj) { this.obj = obj; } public T getObj() { return obj; } public long getCreatAt() { return creatAt; } public long getLastGetAt() { return lastGetAt; } } private final Map handers = new HashMap(); private ScheduledExecutorService gcThread = Executors.newScheduledThreadPool(1); private long maxLiveMillis = 8 * 3600 * 1000; private long maxIdleMillis = 3600 * 1000; private long checkEveryMillis = 5 * 60 * 1000; public MutiThreadHander() { gcThread.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { if ( handers.size() <= 0 ) { return; } long now = System.currentTimeMillis(); Iterator>it = handers.entrySet().iterator(); while ( it.hasNext() ){ Map.Entry entry = it.next(); // check maxLiveMillis if ( entry.getValue().getCreatAt() - now > maxLiveMillis ){ synchronized ( handers ){ it.remove(); } } // check maxIdleMillis if ( entry.getValue().getLastGetAt() - now > maxIdleMillis ){ synchronized ( handers ){ it.remove(); } } } } catch ( Exception e) { e.printStackTrace(); } } }, checkEveryMillis, checkEveryMillis, TimeUnit.MILLISECONDS ); } protected T initialValue() { return null; } public void clear(){ synchronized ( handers ) { handers.remove( Thread.currentThread() ); } } public void set(T obj){ synchronized ( handers ) { handers.put( Thread.currentThread() , new Handler(obj)); } } public T get(){ synchronized ( handers ) { Handler hander = handers.get( Thread.currentThread() ); if ( null == hander ) { T o = initialValue(); hander = new Handler( o ); handers.put( Thread.currentThread(), hander ); } return (T) hander.getObj(); } } }