關於java 泛型設計介面 導致的參數類型不符問題
我想大声告诉你
我想大声告诉你 2017-05-17 10:00:20
0
1
537

1.設計了一個介面用於包裝其它 pojo,以計算是否過期

public interface CatchWrapper<T>{
    public long getCatchedTime();
    
    public T getValue();
    
    public boolean valid();
}

某一個實作:

public class DeviceCatchWrapper implements CatchWrapper<Device> {
    private final long catchedTime;
    private final Device device;
    private static final long CATCH_TIME = 20*1000; 
    
    public DeviceCatchWrapper(Device device) {
        this.device = device;
        catchedTime = System.currentTimeMillis();
    }

    @Override
    public long getCatchedTime() {
        return catchedTime;
    }

    @Override
    public Device getValue() {
        return device;
    }

    @Override
    public boolean valid() {
        return System.currentTimeMillis() - catchedTime < CATCH_TIME;
    }

}

另有一個管理類,主要是刪除過期的快取

public class DeviceCatchWrapperManager<T> {
    private static final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    private final ConcurrentMap<String, CatchWrapper<T>> catchStore;

    private final long initialDelay;
    private final long delay;
    private TimeUnit unit;

    private volatile boolean stop = false;

    public DeviceCatchWrapperManager(ConcurrentMap<String,CatchWrapper<T>> catchStore, long initialDelay,
            long delay, TimeUnit unit) {
        this.catchStore = catchStore;
        this.initialDelay = initialDelay;
        this.delay = delay;
        this.unit = unit;
    }

    /**
     * 周期性检查过期的缓存,然后删除
     */
    public void startLoop() {
        service.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                for (Entry<String, CatchWrapper<T>> entry : catchStore.entrySet()) {
                    if (stop)
                        break;
                    String key = entry.getKey();
                    CatchWrapper<T> cw = entry.getValue();
                    if (!cw.valid()){
                        System.out.println("Device catch manager --------------->remove:"+key);
                        catchStore.remove(key, cw);
                    }
                        
                }

            }
        }, initialDelay, delay, unit);
        
    }

    /**
     * 停在对缓存进行过期检查
     */
    public void stop() {
        stop = true;
        service.shutdownNow();
    }
}

但是真正建構子 傳參數錯誤

private final ConcurrentMap<String, DeviceCatchWrapper> catchMap = new ConcurrentHashMap<>(); 

下面的报错,参数不对
private final DeviceCatchWrapperManager<Device> catchManager = new DeviceCatchWrapperManager<Device>(catchMap, 2, 2, TimeUnit.HOURS);

改怎麼解決這個錯誤 或是什麼改進呢?

我想大声告诉你
我想大声告诉你

全部回覆(1)
Peter_Zhu

ConcurrentMapDeviceCatchWrapper> catchMap = new ConcurrentHashMap(); 這句話有問題
改成ConcurrentMapCatchWrapperdr. >( );試試

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!