多线程安全的接口

This commit is contained in:
cheney 2022-07-15 10:19:58 +08:00
parent ba3f91df54
commit a982f8b2df

View File

@ -0,0 +1,109 @@
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 <T>
*/
public class MutiThreadHander<T> {
private static class Handler<T> {
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<Thread, Handler> handers = new HashMap<Thread, Handler>();
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<Map.Entry<Thread, Handler>>it = handers.entrySet().iterator();
while ( it.hasNext() ){
Map.Entry<Thread, Handler> 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();
}
}
}