java - Reusing an object without preventing it from being garbage collected -


i want write class instance field holds large amount of data expensive create. because object time consuming create want separate instances able reuse object if has been computed different instance. on other hand if instances of class garbage collected, want large object able garbage-collected too.

i came code following.

public class example {      private example() {}      private static volatile reference<list<integer>> ref = new weakreference<>(null);      public static list<integer> get() {         list<integer> list;         if ((list = ref.get()) != null)             return list;         synchronized (example.class) {             if ((list = ref.get()) != null)                 return list;             list = compute();             ref = new weakreference<>(list);             return list;         }     }      private static list<integer> compute() {         // expensive computation producing list millions of elements     } } 

then can make list instance field doing

public class myclass {      private final list<integer> list = example.get(); } 

this code seems work, unsure if using volatile, synchronized, weakreference , double-check idiom correctly. can see problems code, or suggest alternative/better way of achieving this?

looks me, think volatile not necessary. @ least if assigning inside synchronized block, synchronization block should prevent memory consistency errors


Comments