В исходном коде класса SoftReference есть такое поле:
/**
* 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;
Согласно документации к методу, каждый вызов get должен приводить к обновлению поля timestamp. Но этого не происходит и я не могу понять почему. В качестве эксперемента написал такой класс:
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
public class SoftReferenceTest {
public static void main(String[] args) throws Exception {
SoftReference<StringBuilder> softReference = new SoftReference<>(new StringBuilder());
long timestamp = getTimestamp(softReference);
for (int i = 0; i < 10; i++) {
checkTimestampChange(softReference, timestamp);
}
}
private static void checkTimestampChange(SoftReference softReference, long timestampBefore) throws Exception {
softReference.get();
Thread.sleep(100);
assert timestampBefore == getTimestamp(softReference);
}
private static long getTimestamp(Object object) throws Exception {
Field timestampField = SoftReference.class.getDeclaredField("timestamp");
timestampField.setAccessible(true);
long timestamp = timestampField.getLong(object);
timestampField.setAccessible(false);
return timestamp;
}
}
Код успешно выполнился без ошибок. Не могу понять почему.
Сборка персонального компьютера от Artline: умный выбор для современных пользователей