当gc执行时,决定SoftReference回收有两个因素:
[list]
[*]SoftReference的timestamp
[*]有多少空闲空间
[/list]
在server模式下,会用-Xmx参数得到空闲空间大小。
在client模式下,会用当前heap最大空闲空间大小。
简单来说,server模式下会优先扩大heap大小,client模式下会优先回收垃圾。
SoftReference类中,有一个timestamp:
在新建SoftReference对象和调用SoftReference.get时都会使timestamp更新为clock的值。而clock代表的是上次gc的时间。
SoftRefLRUPolicyMSPerMB默认为1000,即1s。代表每1MB空闲空间大小SoftReference保留1s。
是否回收的条件:
clock - timestamp <= freespace * SoftRefLRUPolicyMSPerMB
举例来说,clock为1000,timestamp为300,空闲空间为1MB。
1000 - 300 <= 1000 * 1
所以不会被回收。
一个值得注意的地方是,SoftReference会至少经历1次gc而不被回收。
参考:http://jeremymanson.blogspot.com/2009/07/how-hotspot-decides-to-clear_07.html
[list]
[*]SoftReference的timestamp
[*]有多少空闲空间
[/list]
在server模式下,会用-Xmx参数得到空闲空间大小。
在client模式下,会用当前heap最大空闲空间大小。
简单来说,server模式下会优先扩大heap大小,client模式下会优先回收垃圾。
SoftReference类中,有一个timestamp:
public class SoftReference<T> extends Reference<T> {
/* Timestamp clock, updated by the garbage collector
*/
static private long clock;
/* Timestamp updated by each invocation of the get method. The VM may use
* this field when selecting soft references to be cleared, but it is not
* required to do so.
*/
private long timestamp;
......
}
在新建SoftReference对象和调用SoftReference.get时都会使timestamp更新为clock的值。而clock代表的是上次gc的时间。
SoftRefLRUPolicyMSPerMB默认为1000,即1s。代表每1MB空闲空间大小SoftReference保留1s。
是否回收的条件:
clock - timestamp <= freespace * SoftRefLRUPolicyMSPerMB
举例来说,clock为1000,timestamp为300,空闲空间为1MB。
1000 - 300 <= 1000 * 1
所以不会被回收。
一个值得注意的地方是,SoftReference会至少经历1次gc而不被回收。
参考:http://jeremymanson.blogspot.com/2009/07/how-hotspot-decides-to-clear_07.html