/**
 * 
 */
package com.trendrr.oss.concurrent;

import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * An object that will be lazily initialized, and reinitialize every X millis
 * 
 * 
 * @author Dustin Norlander
 * @created Dec 6, 2010
 * 
 */
public abstract class ReinitObject<T> implements Initializer<T>{

	protected Log log = LogFactory.getLog(ReinitObject.class);
	
	PeriodicLock lock = null;
	AtomicReference<T> ref = new AtomicReference<T>();
	
	public ReinitObject(long millisBetweenInit) {
		lock = new PeriodicLock(0, millisBetweenInit);
	}
	
	public T get() {
		if (ref.get() == null) {
			//we block if the object is unitialized.  otherwise we skip while initia
			if (lock.lockOrWait()) {
				try {
					ref.set(this.init());	
				} finally {
					lock.unlock();
				}
			}
		} else {
			// else we return the old results while the new ones are being initialized
			if (lock.lockOrSkip()) {
				try {
					ref.set(this.init());	
				} finally {
					lock.unlock();
				}
			}
			
		}
		return ref.get();
	}
	
	/**
	 * passively looks to see if this object needs to be re-initialized
	 * @return
	 */
	public boolean isExpired() {
		return lock.getNextUnlock().getTime() < new Date().getTime();
	}
	
	/**
	 * clears the initialized object if it is expired.
	 */
	public void clearIfExpired() {
		if (lock.lockOrWait()) {
			try {
				ref.set(null);	
			} finally {
				lock.unlock();
			}
		}
		lock.lockUntil(new Date());
	}
}

@@ -484,16 +484,24 @@
 ss);%0A%09%0A%09
+private 
 Periodic
@@ -519,16 +519,24 @@
  null;%0A%09
+private 
 AtomicRe
@@ -578,16 +578,60 @@
 e%3CT%3E();%0A
+%09private boolean usePreviousIfNull = false;%0A
 %09%0A%09publi
@@ -725,16 +725,314 @@
 );%0A%09%7D%0A%09%0A
+%09/**%0A%09 * %0A%09 * @param millisBetweenInit%0A%09 * @param usePreviousIfNull if init returns null should we use the old result?%0A%09 */%0A%09public ReinitObject(long millisBetweenInit, boolean usePreviousIfNull) %7B%0A%09%09lock = new PeriodicLock(0, millisBetweenInit);%0A%09%09this.usePreviousIfNull = usePreviousIfNull;%0A%09%7D%0A%09%0A
 %09public 
@@ -1389,38 +1389,183 @@
  %7B%0A%09%09%09%09%09
-ref.set(
+T val = this.init();%0A%09%09%09%09%09if (val != null %7C%7C !this.usePreviousIfNull) %7B%0A%09%09%09%09%09%09ref.set(val);%09%0A%09%09%09%09%09%7D else %7B%0A//%09%09%09%09%09%09log.info(%22Skipping cause 
 this
-.
+ 
 init
-());%09
+ is null%22);%0A%09%09%09%09%09%7D
 %0A%09%09%09%09%7D f

Allow reinit object to optionally use previous value if init is null