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

5 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Zheng junxai5 said...

zhengjx20160721
kd 7 shoes
gucci outlet online
air jordan shoes
vans outlet
gucci outlet
coach outlet clearance
louis vuitton handbags
nike roshe run mens
concords 11
cheap jordans
nike air force 1 white
oakley sunglasses
michael kors outlet clearance
air jordan shoes
louis vuitton outlet stores
true religion jeans
louis vuitton
louis vuitton handbags
nike store
lebron 12
ralph lauren
timberlands
polo ralph lauren
louis vuitton purses
christian louboutin outlet
nike store uk
coach outlet online
mont blanc pen
nike air max 90
michael kors outlet
adidas originals store
oakley vault
tods outlet store
cheap oakleys
true religion jeans
discount jordans
true religion outlet store
michael kors outlet
kobe 10
asics shoes for men