我创建了一个 Cache
对象,它存储一个 String
作为键,一个序列化的对象作为值。
Cache(String--->Object)
我正在尝试运行三个 Akka 线程,它们以同步方式检索和写入同一个 Ehcache 对象。
Thread 1- synchronized (LockForEhcache){
serializedObj = cachename.get("key"); //--- this returns an Object
}
//modify the serializedObj here....
//Again store the modify Object in the Cache
synchronized (LockForEhcache){
cachename.clear();
cachename.put("key",serializedObj);
Thread 2- synchronized (LockForEhcache){
serializedObj = cachename.get("key"); //--- this returns null
}
Thread 3- synchronized (LockForEhcache){
serializedObj = cachename.get("key"); //--- this returns null
}
但只有一个线程获取存储在Cache
中的值。对于其余线程,它会抛出一个 NullPointerException
。我不明白为什么。
最佳答案
首先,缓存不是存储。所以你不能指望一个缓存一直返回最新的数据。由于不同的原因,它可能会返回 null。
现在,除非发生一些驱逐或过期,否则数据应该在那里。所以我需要一个完整的例子来告诉你发生了什么。
我的第一个问题是:为什么要清除和放置?为什么不只放?我们是否同意 clear 将清除所有条目?您的缓存中只有一个条目?
关于java - 同一个CacheManager的同一个Ehcache对象可以被多个线程使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834377/