package net.darkmist.alib.ref;

import java.lang.ref.WeakReference;

public abstract class MemCachedRef<T> extends AbstractRef<T>
{
	private volatile WeakReference<T> valRef = null;

	/**
	 * (Re)Create the object.
	 */
	protected abstract T make();

	/**
	 * Get the cached object. If the object is not in memory, it is recreated.
	 */
	// This is not the classic race condition as valRef is volatile.
	public T get()
	{
		WeakReference<T> wref;
		T val;

		if((wref=valRef)!=null && (val = wref.get())!=null)
			return val;
		synchronized(this)
		{
			if((wref=valRef)!=null && (val = wref.get())!=null)
				return val;
			val = make();
			valRef = new WeakReference<T>(val);
		}
		return val;
	}
}

@@ -138,17 +138,8 @@
 ate 
-volatile 
 Weak
@@ -326,195 +326,48 @@
 */%0A%09
-// This is not the classic race condition as valRef is volatile.%0A%09public T get()%0A%09%7B%0A%09%09WeakReference%3CT%3E wref;%0A%09%09T val;%0A%0A%09%09if((wref=valRef)!=null && (val = wref.get())!=null)%0A%09%09%09return val;
+public synchronized T get()%0A%09%7B%0A%09%09T val;%0A
 %0A%09%09s
@@ -398,38 +398,31 @@
 %09if(
-(wref=
 valRef
-)!
+=
 =null 
-&&
+%7C%7C
  (val = 
 wref
@@ -421,10 +421,12 @@
 l = 
-wr
+valR
 ef.g
@@ -434,9 +434,9 @@
 t())
-!
+=
 =nul
@@ -441,29 +441,19 @@
 ull)%0A%09%09%09
-%09return val;%0A
+%7B%0A%09
 %09%09%09val =
@@ -461,16 +461,17 @@
 make();%0A
+%09
 %09%09%09valRe
@@ -501,16 +501,21 @@
 %3E(val);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%09re

synchronize get instead of using volitile as it's checked multiple times.