多个线程可以使用同一CacheManager的同一Ehcache对象吗? [英] Can same Ehcache object of same CacheManager be used by multiple threads?

查看:442
本文介绍了多个线程可以使用同一CacheManager的同一Ehcache对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Cache对象,该对象存储String作为键,并存储序列化的对象作为值.

I have created a Cache object which stores a String as the key and a serialized object as the value.

Cache(String--->Object) 

我正在尝试运行三个Akka线程,这些线程以同步方式检索和写入同一Ehcache对象.

I am trying to run three Akka threads which retrieve and write into the same Ehcache object in a synchronized way.

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.我不知道为什么.

But only one thread gets the value stored in the Cache. For the rest of the threads, it throws a NullPointerException. I can't figure out why.

推荐答案

首先,缓存不是存储区.因此,您不能指望缓存会一直返回最新数据.由于不同的原因,它可能返回null.

First of all, a cache is not a store. So you can't expect a cache to return the latest data all the time. For different reasons, it might return null.

现在,除非有一些逐出或到期,否则数据应该在那里.因此,我需要一个完整的例子来告诉您发生了什么事.

Right now, unless some eviction or expiration occurs, the data should be there. So I will need a full example to tell you what's going on.

我的第一个问题是:为什么要清理并放置?为什么不只放?我们是否同意清除将清除所有条目?您的缓存中只有一个条目?

My first question would be: Why do you clear and put? Why not only put? And do we agree that clear will clear all entries? You only have one entry in your cache?

这篇关于多个线程可以使用同一CacheManager的同一Ehcache对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆