wood burning stoves 2.0*
The moose likes Java in General and the fly likes need store object for 5 mins Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "need store object for 5 mins" Watch "need store object for 5 mins" New topic
Author

need store object for 5 mins

sudh ag
Greenhorn

Joined: Jan 12, 2011
Posts: 7
i have a requirement in which i have to store key value pair.
the value should be expire after 5 mins so that if some get access using key than null returns
how we can achieve this requirement
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14156
    
  19

Store the key-value pair and schedule a task that triggers in 5 minutes which removes it again.

There are several ways to schedule a task to be executed in 5 minutes in Java. I would use a ScheduledExecutorService for this and a ConcurrentMap to store the keys and values.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

And if you want a full Map implementation, just have FiveMinuteMap delegate other calls to the backing map as well.
You need proper synchronization, which is what the ConcurrentHashMap will do for you. If you need a TreeMap as backing mechanism you need to take care of synchronization (also while iterating) yourself.

I'd make one improvement over that class though - make the interval instance fields. That allows you to use the same class for 10 minutes, 1 hour, etc:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14156
    
  19

Rob, notice that V get(K key) is not implementing the get method from interface Map - in that interface, the key is unfortunately of type Object (because of backward compatibility reasons with pre-generics Java). If you'd want to implement the Map interface, it would have to be:
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

You're right, I missed that.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: need store object for 5 mins