Monday, November 25, 2013

I am storing data in application scope. I want to clear this data after every hour. Infact using it as cache for one hour. What is the best way to implement this? Earlier we used session scope to store this data and it used to get expired after session gets expired. As this data is unique across the application we want to store it in application scope.
share|improve this question
add comment

4 Answers

For a very simple cache you can use the Google guava's MapMaker: Here is the example taken from the javadoc:
   ConcurrentMap<Key, Graph> graphs = new MapMaker()
       .concurrencyLevel(4)
       .softKeys()
       .weakValues()
       .maximumSize(10000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .makeComputingMap(
           new Function<Key, Graph>() {
             public Graph apply(Key key) {
               return createExpensiveGraph(key);
             }
           });
there are these two methods expireAfterWrite and expireAfterRead to do what yuo want. And for free you have a thread safe Map, with weakValue, softkeys and lazy evaluation if you want/need it :)
share|improve this answer
 
this is awesome. Do you know whether Guava will reap expired objects in the background? If so, how does it plug into JEE? –  Dilum Ranatunga Apr 6 '11 at 17:21 
 
@Dilum: No background task if I remember well, there is only a per access check. –  Guillaume Apr 7 '11 at 8:30 
 
This functionality has moved to guava CacheBuilder (since r10 I think). –  hawkett Sep 18 '12 at 23:29
add comment
Depending on whether you want to aggressively clear expired data (to recover memory) or you just want to recompute after expiration time, the approach would be very different.
If you simply want to recompute, I would extend SoftReference, for example:
public class ExpiringSoftReference<T> extends SoftReference<T> implements Serializable {
  private final long _expirationMoment;

  public ExpiringSoftReference(Object referent, long duration, TimeUnit unit) {
    this(referent, System.currentTimeMillis() + unit.toMillis(duration);
  }

  private ExpiringSoftReference(Object referent, long expirationMoment) {
    super(referent);
    _expirationMoment = expirationMoment;
  }

  public T get() {
    if (System.currentTimeMillis() >= _expirationMoment) {
      clear();
    }
    return super.get();
  }

  private Object writeReplace() throws ObjectStreamException {
    return new SerializedForm<T>(get(), _expirationMoment);
  }

  private static class SerializedForm<T> implements Serializable {
    private final T _referent;
    private final T _expirationMoment;

    SerializedForm(T referent, long expirationMoment) {
      _referent = referent;
      _expirationMoment = expirationMoment;
    }

    private Object readResolve() throws ObjectStreamException {
      return new ExpiringSoftReference<T>(_referent, _expirationMoment);
    }
  }
}
If you want to aggressively reclaim memory, you need to implement a sort of garbage collection. The approach to take is to first put all references in a threadsafe priority queue, then occasionally peek at the first element, to see if at least one of the references have expired:
public class ExpiringSoftReference<T> 
extends SoftReference<T> 
implements Comparable<ExpiringSoftReference>, Serializable {
  // same as above, plus
  public int compareTo(ExpiringSoftReference other) {
    if (this._expirationMoment < other._expirationMoment) {
      return -1;
    } else if (this._expirationMoment > other._expirationMoment) {
      return 1;
    } else {
      return 0;
    }
  }

  final long expiration() {
    return _expirationMoment;
  }
}

public class ExpirationEnforcer {
  private final PriorityBlockingQueue<ExpiringSoftReference> _byExpiration = new ...();

  public void add(ExpiringSoftReference reference) {
    _byExpiration.put(reference);
  }

  public synchronized void tick() {
    long now = System.currentTimeMillis();
    while (true) {
      ExpiringSoftReference candidate = _byExpiration.peek();
      if (candidate == null || candidate.expiration() > now) {
        return;
      }
      ExpirationSoftReference toClear = _byExpiration.peek();
      toClear.clear();
    }
  }
}
You will need to call tick() on the queue every couple of seconds or whatever. To do that in Java EE, you will need to use a timer service or something like that.
share|improve this answer
add comment
Where is this data coming from? If from a DB, you should consider using an ORM with support for first and second level caches like Hibernate/JPA. This way you don't need to change your code in order to be dependent from the cache (which would make it pretty hard maintainable/reusable). You just fire SQL queries the usual way and Hibernate/JPA will return objects from Java's in-memory cache whenever applicable.

See also:

share|improve this answer
add comment
We found a way to clear application scope variables using ServletContextListener and Timer.
public class SampleListener implements ServletContextListener {

public static final long _startTimerDelayMin = 10; // In minutes
public static final long _startTimerPeriodMin = 60; // In minutes

Timer timer;
ServletContext context =null;       

public void contextInitialized(ServletContextEvent contextEvent) {      
    context = contextEvent.getServletContext();     
    scheduleTimer();        
}   

public void scheduleTimer() {
    long delay = _startTimerDelayMin * 60000;   //initial delay set to _startTimerDelayMin minutes as per msecs
    long period = _startTimerPeriodMin * 60000;   //subsequent rate set to _startTimerPeriodMin minutes as per msecs
    timer = new Timer();
    timer.scheduleAtFixedRate(new RemindTask(), delay, period); 
}

public void contextDestroyed(ServletContextEvent arg0) {
    //Stopping Timer Thread once context destroyed
    timer.cancel();
}

private static String getPropertyValue(String key){
    String value = "";
    try{
        value = Util.getPropertyValueOfKey(key).trim();
    }catch(IOException e){

    }
    return value;
}

/**
 * This class is invoked at given interval to clear the application scope variable for browse call which have not been used for given time
 *
 */
class RemindTask extends TimerTask {

    public void run() {
        clearScopeVariables();
    } 

    /**
     * This funtion has logic to clear the application scope variable for browse call which have not been used for given time
     */
    public void clearScopeVariables() {
        Date dt = new Date();
        Enumeration<String> applicationScopeVarNames = (Enumeration<String>)context.getAttributeNames();
                    // TODO: clear the scope variables
    }       
}   
Add Listener in web.xml
share|improve this answer
add comment

No comments: