關(guān)于java 泛型設(shè)計(jì)接口 導(dǎo)致的參數(shù)類(lèi)型不匹配問(wèn)題
問(wèn)題描述
1.設(shè)計(jì)了一個(gè)接口用于包裝其它 pojo,以計(jì)算是否過(guò)期
public interface CatchWrapper<T>{ public long getCatchedTime();public T getValue();public boolean valid();}
某一個(gè)實(shí)現(xiàn):
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; }}
另有一個(gè)管理類(lèi),主要是刪除過(guò)期的緩存
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; } /** * 周期性檢查過(guò)期的緩存,然后刪除 */ 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); } /** * 停在對(duì)緩存進(jìn)行過(guò)期檢查 */ public void stop() {stop = true;service.shutdownNow(); }}
但是真正構(gòu)造函數(shù) 傳參數(shù)報(bào)錯(cuò)
private final ConcurrentMap<String, DeviceCatchWrapper> catchMap = new ConcurrentHashMap<>(); 下面的報(bào)錯(cuò),參數(shù)不對(duì)private final DeviceCatchWrapperManager<Device> catchManager = new DeviceCatchWrapperManager<Device>(catchMap, 2, 2, TimeUnit.HOURS);
改怎么解決這個(gè)錯(cuò)誤 或者 該怎么設(shè)計(jì)接口或者改進(jìn)呢?
問(wèn)題解答
回答1:ConcurrentMap<String, DeviceCatchWrapper> catchMap = new ConcurrentHashMap<>(); 這句有問(wèn)題改成ConcurrentMap<String, CatchWrapper<Device>> catchMap = new ConcurrentHashMap<String, DeviceCatchWrapper>();試試
相關(guān)文章:
1. macOS Sierra 10.12 安裝mysql 5.7.1出現(xiàn)錯(cuò)誤2. mysql - 拖拽重排序后怎么插入數(shù)據(jù)庫(kù)?3. android - 安卓做前端,PHP做后臺(tái)服務(wù)器 有什么需要注意的?4. javascript - 微信小程序 wx.downloadFile下載文件大小有限制嗎5. mysql 獲取時(shí)間函數(shù)unix_timestamp 問(wèn)題?6. mysql - 僅僅只是把單引號(hào)與反斜杠轉(zhuǎn)義不用prepare statement能否避免sql注入?7. php - 生產(chǎn)環(huán)境下,給MySQL添加索引,修改表結(jié)構(gòu)操作,如何才能讓線上業(yè)務(wù)不受影響?8. mysql主主同步,從庫(kù)不同步應(yīng)該怎么解決?9. mysql在限制條件下篩選某列數(shù)據(jù)相同的值10. 新入手layuiadmin,部署到tp中。想用php自已寫(xiě)一個(gè)后臺(tái)管理系統(tǒng)。
