Java Reference
In-Depth Information
import java.lang.ref.*;
import java.io.File;
class DataHandler {
private File lastFile; // last file read
private WeakReference<byte[]>
lastData; // last data (maybe)
byte[] readFile(File file) {
byte[] data;
// check to see if we remember the data
if (file.equals(lastFile)) {
data = lastData.get();
if (data != null)
return data;
}
// don't remember it, read it in
data = readBytesFromFile(file);
lastFile = file;
lastData = new WeakReference<byte[]>(data);
return data;
}
}
When readFile is called it first checks to see if the last file read was the
same as the one being requested. If it is, readFile retrieves the refer-
ence stored in lastData , which is a weak reference to the last array of
bytes returned. If the reference returned by get is null , the data has
been garbage collected since it was last returned and so it must be re-
read. The data is then wrapped in a new WeakReference . If get returns
a non- null reference, the array has not been collected and can be re-
turned.
 
Search WWH ::




Custom Search