Reference API

Reference types
  1. soft: for caching
  2. weak: for fast cleanup (pre-finalizer)
  3. phantom: for safe cleanup (post-finalizer)
Reference queues: for notifications

Soft references: for quick-and-dirty caching only

Cleared when the VM runs low on memory

Hopefully in LRU fashion

Tuned with -XX:SoftRelLRUPolicyMSPerMB

how long to retain soft refs in ms per free MB of heap

Default: 1000ms

Soft refs have no notion of weight:

  • memory usage
  • computation time
  • cpu usage
volatile SoftReference<byte[]> dataReference = new SoftReference<byte[]>(null); //这个地方是可以写null的

public byte[] getData(){

byte[] data = dataReference.get();
if(data !=null) return data;
data = readData();
dataReference = new SoftReference<byte[]>(data);
return data;
}
//这些代码totally没有意思,os会自己做cache的。

Weak reference

cleared as soon as no strong and soft remains

cleared ASAP, before the finalizer runs

Not for caching. Use soft reference, as intended. check jvm spec.

 

Phantom reference

get() always returns null.// gc runs concurrently with your code

so you must use in a reference queue.

 

java.util.WeakHashMap

useful for emulating additional fields

keeps weak refs to keys, strong refs to values

not concurrent

uses equals() when it should use ==

 

Recap:

  1. start at a root
  2. trace and mark strongly-referenced objects
  3. optionally clear soft references
  4. trace and mark softly-referenced objects
  5. clear weak references
  6. enqueue finalizable objects
  7. repeast steps 1 through 5 for the queue
  8. possibly enqueue phantom references
  9. the remaining objects are dead
  10. repeat
public class GetterMethods{

final static Cache<class<?>,List<Method>> cache = CacheBuilder.newBuilder()
.weakKeys()
.softValues()
.build(new CacheLoader<Class<?>,List<Method>>(){

public List<Method> load(<Class<?> clazz){

List<Method> getters = new ArrayList<Method>();
for(Method m: clazz.getMethods())
if(m.getName().startsWith("get"))
getters.add(m);

return getters;

}

});


public static List<Method> on(Class<?> clazz){

return cache.apply(clazz);
}


//Usage:
//List<Method> l = GetterMethods.on(Foo.class);

}


To dynamically reload your web application, you need to be careful not unintentionally to retain your app classloader from being collected.



 

 

转载于:https://www.cnblogs.com/greginfo/archive/2012/02/19/2357840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值