aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 13868
    
  10

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: 19541
    
  16

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: 13868
    
  10

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: 19541
    
  16

You're right, I missed that.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: need store object for 5 mins
 
Similar Threads
Map with duplicate keys
how to serialize a java.security.key
Is insertion at a position possible in any flavour of Collection having key value?
Is it possible to insert a new key value pair at a position in a Map?
Need to restart timer with different time