Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

need store object for 5 mins

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 21758
102
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21758
102
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right, I missed that.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!