Java:与垃圾收集器竞争 [英] Java: Racing against the garbage collector

查看:136
本文介绍了Java:与垃圾收集器竞争的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了Object缓存,如下所示:

I've implemented an Object cache like so:

// Dictionary with weak keys & values
private Map<Object, WeakReference<Object>> cache = new WeakHashMap<>();

private Object checkCache(Object obj) {

    // If it's in the cache, returned the cached copy.
    if (cache.containsKey(obj)) return cache.get(obj).get();

    // Store it in, and return it.
    cache.put(obj, new WeakReference<>(obj));
    return obj;
}

生动描述以下竞赛条件场景:

Picture the following race-condition scenario:

  1. cache.containsKey(obj)返回true
  2. 垃圾收集器启动并获取缓存中的对象.
  3. null返回.
  1. cache.containsKey(obj) returns true
  2. The garbage collector kicks in and reaps the object in the cache.
  3. null is returned.

问题是:

  • 这真的可以发生吗? AFAIK GC可以在任何时间启动.
  • 可以为单个方法调用禁用Java GC吗? synchronized似乎并没有阻止GC.
  • 有没有解决方法?
  • Can this really happen? AFAIK the GC can kick in at any time.
  • Can Java GC be disabled for a single method call? synchronized doesn't seem to prevent GC.
  • Are there any work-arounds?

提前谢谢!

推荐答案

这真的可以发生吗?

Can this really happen?

是的

可以为单个方法调用禁用Java GC吗?

Can Java GC be disabled for a single method call?

否.

有没有解决方法?

Are there any work-arounds?

是:您尝试从缓存中检索对象(从而在对象仍位于缓存中时建立一个强引用),如果该引用为null,则将其添加到缓存中:

Yes: you attempt to retrieve the object from the cache (thereby establishing a strong reference if it's still in the cache), and add to the cache if that reference is null:

WeakReference<Object> ref = cache.get(obj);
Object cached = (ref != null) ? ref.get() : null;
if (cached != null) {
    return cached;
}
else {
    cache.put(obj, new WeakReference(obj));
    return obj;
}

您仍然需要同步该方法,否则您可能需要两个线程同时更新缓存(以及生成的

You still need to synchronize the method, otherwise you could have two threads updating the cache at the same time (and the resulting update race would be the least of your worries).

这篇关于Java:与垃圾收集器竞争的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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