Java Example Thread Security Using WeakReference

I read about weak Java links after you sent an SO message, and realizing that I really don't know what that is.

The following code is presented on page 457, chapter 17: “Garbage collection and memory” in “Java Programming Language, fourth edition” by Arnold, Gosling and Holmes

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;
    }
}

I'm trying to understand, just to implement it, if this code is thread safe, with the code part I focus on being strings

data = lastData.get();
if (data != null)
    return data;

: "data" - , "WeDeference" lastData. , , readFile ( ?) , , , , - . , data != null, . ?

+3
3

, , , :

, , : , data. , GC , , , WeakReference ; . :

file lastData , , , readFile(..), ( "" ). , , , , readFile . , , .

+2

data, . , .

+2

Technically speaking, this is not thread safe because lastData and lastFile are unstable. The second thread can see an old copy of these links. This may not be a big deal for your application.

-1
source

All Articles