Java 序列化ehcache中的元素时出错
在将元素放入ehcache时,我遇到以下错误。有人知道为什么会发生这个错误吗 先谢谢你 这种方法是:Java 序列化ehcache中的元素时出错,java,serialization,replication,ehcache,Java,Serialization,Replication,Ehcache,在将元素放入ehcache时,我遇到以下错误。有人知道为什么会发生这个错误吗 先谢谢你 这种方法是: @SuppressWarnings("unchecked") @Override public void putActivity(Activity activity) { // put activity itself Serializable activityKey = KEY_PREFIX_ACTIVITY + activity.getId(); final
@SuppressWarnings("unchecked")
@Override
public void putActivity(Activity activity) {
// put activity itself
Serializable activityKey = KEY_PREFIX_ACTIVITY + activity.getId();
final Element activityElement = new Element(activityKey, activity);
getCache().put(activityElement);
// add activity to the list of user
ArrayList<Activity> activities = null;
Serializable userKey = KEY_PREFIX_USER_ACTIVITIES + activity.getExecutingUserId();
Element userActivities = getCache().get(userKey);
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = (ArrayList<Activity>) userActivities.getObjectValue();
}
activities.add(activity);
getCache().put(userActivities);
}
以下是ehcache源代码中的更多详细信息:
private MemoryEfficientByteArrayOutputStream [More ...] serializeElement(Element element) throws IOException {
// A ConcurrentModificationException can occur because Java's serialization
// mechanism is not threadsafe and POJOs are seldom implemented in a threadsafe way.
// e.g. we are serializing an ArrayList field while another thread somewhere in the application is appending to it.
try {
return MemoryEfficientByteArrayOutputStream.serialize(element);
} catch (ConcurrentModificationException e) {
throw new CacheException("Failed to serialize element due to ConcurrentModificationException. " +
"This is frequently the result of inappropriately sharing thread unsafe object " +
"(eg. ArrayList, HashMap, etc) between threads", e);
}
}
您正在更新序列化的对象,请尝试将其保存到磁盘。应该只在缓存中存储不可变对象 在您的情况下,不要尝试重用ArrayList,请创建一个新的ArrayList:
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = new ArrayList<Activity>((List) userActivities.getObjectValue());
}
您可以实例化CopyOnWriteArrayList而不是ArrayList。谢谢,您的意思是这样吗?else{activities=new ArrayList;activities.addAllArrayList userActivities.getObjectValue;}是的,我忘记了强制转换
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = new ArrayList<Activity>((List) userActivities.getObjectValue());
}