Note that there are some explanatory texts on larger screens.

plurals
  1. POThread safety of Java example using WeakReference
    text
    copied!<p>I am reading up on weak references in Java after seing a SO post and realising I didn't really know what they were.</p> <p>The following code is from pp. 457, Chapter 17: "Garbage Collection and Memory" in "The Java Programming Language, Fourth Edition" by Arnold, Gosling and Holmes</p> <pre><code>import java.lang.ref.*; import java.io.File; class DataHandler { private File lastFile; // last file read private WeakReference&lt;byte[]&gt; 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&lt;byte[]&gt;(data); return data; } } </code></pre> <p>I am trying to understand, just for the exercise of it, if this code is thread safe, with the part of code I am focusing on being the lines</p> <pre><code>data = lastData.get(); if (data != null) return data; </code></pre> <p>My thinking is as follows: "data" is thread confined and is set to reference the referent of the "lastData" WeakReference. This creates a strong reference to the referent, hence even if after the null check, all other strong references to the referent outside readFile's scope disappears (what's the correct term ?) and even assuming the referent is not softly reachable, the garbage collector is not allowed to clear the weak reference thereby making the referent finalizable, because there still is the local strong reference to it from data. Hence if data is not null in the <code>data != null</code> line, it can not be null when returned in the following line. Correct ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload