考虑这个初始化
this.cache = new LinkedHashMap<K, V>(MAX_ENTRIES+1, .75F, true) {
public boolean removeEldestEntry(Map.Entry eldest) {
}
};
有没有办法用从另一个类导入的定义替换removeEldestEntry
?
我想这样做的原因是因为我有一个具有executor
和cache
的泛型包装类,但是对于不同的可运行任务,cache
存储不同的信息,因此需要不同的行为LinkedHashMap.removeEldestEntry
编辑:
public class MyBufferService<K, V> {
private ThreadPoolExecutor executor;
private final Map cache;
public MyBufferService(String buffName) {
executor = new ThreadPoolExecutor(1, // corePoolSize
1, // maximumPoolSize
60, TimeUnit.SECONDS, // keepAlive
new LinkedBlockingQueue<>(10000), // workQueue
new ThreadFactoryBuilder().setNameFormat(buffName + "-MyBufferService-thread-%d").build(), // factory
new ThreadPoolExecutor.CallerRunsPolicy() // rejected execution handler
);
this.cache = new LinkedHashMap<K, V>(1000, .75F, true) {
public boolean removeEldestEntry(Map.Entry eldest) {
}
};
}
}
在上面的代码中,executor
接受任何实现runnable
的类,所以假设你有2个任务,每个任务runnable
,每个任务都希望在线程池执行时提供自己的removeEldestEntry
功能。
有没有办法做到这一点?
编辑 2:
private class BufferTask implements Runnable {
private final String mystring;
private final Map cache;
BufferTask(String mystring, Map cache) throws NullPointerException {
this.mystring = mystring;
this.cache = cache;
}
@Override
public void run() {
try {
synchronized (this.cache) {
this.cache.put(this.mystring, "hi");
}
} catch (Throwable t) {
}
}
public boolean removeEldestEntry(Map.Entry eldest) {
}
}
目标实际上是让每种类型的任务提供自己的removeEldestEntry
编辑3:
以下是我提交任务的方式
public class BufferService<K, V>{
public BufferService(String bufferName) {
executor = new ThreadPoolExecutor(1, // corePoolSize
1, // maximumPoolSize
keepAliveTimeSec, TimeUnit.SECONDS, // keepAlive
new LinkedBlockingQueue<>(queueSize), // workQueue
new ThreadFactoryBuilder().setNameFormat(bufferName + "-KafkaBufferService-thread-%d").build(), // factory
new ThreadPoolExecutor.CallerRunsPolicy() // rejected execution handler
);
this.cache = new LinkedHashMap<K, V>(MAX_ENTRIES+1, .75F, true) {
public boolean removeEldestEntry(Map.Entry eldest) {
}
};
}
public void putDeferBufferTask(
String myString) throws RejectedExecutionException, NullPointerException {
executor.submit(new BufferTask(myString, this.cache));
}
}
如果我正确理解您的问题,您正在寻找的可能是策略模式。通过这种方式,您可以注入任何行为。
public MyBufferService(String buffName, Predicate<Map.Entry> removeEldestEntryImplementation) {
...
this.cache = new LinkedHashMap<K, V>(1000, .75F, true) {
public boolean removeEldestEntry(Map.Entry eldest) {
return removeEldestEntryImplementation.test(eldest);
}
};
}
不要被方法名称混淆test()
,我只是使用具有合适签名的标准库提供的标准功能接口Predicate
。
在编辑 2 之后,您可以像这样加入它:
private class BufferTask implements Runnable, Predicate<Map.Entry> {
....
private boolean removeEldestEntry(Map.Entry eldest) {
// your mysterious code here
}
@Override
public boolean test(Map.Entry eldest) {
return removeEldestEntry(eldest);
}
}
然后将此类的实例传递给MyBufferService
的构造函数。