Search code examples
javacachingcollectionslockslru

ExpiringMap or TTL based Cache


http://www.java2s.com/Code/Java/Collections-Data-Structure/ExpiringMap.htm

Q1) I was looking at the above Caching code. I am confused why we need a lock when getLastAccessTime is called. That method is only being called by the Expirer thread.

Q2) Let say, if the Map is being called by only thread, then do we ever need a reentrant lock in the ExpiringObject. Because the setLastAccessTime is called by only thread when calling Map's put method and getLastAccessTime method will be called by Expirer thread. The reason why I am asking is, I tested inserting 1M objects, Reentrant Lock is taking more than 100MB


Solution

  • The lock is needed, since the long value cannot be updated atomically on 32 bit systems.

    Alternatives:

    • Replace the long by a Long. The reference update is atomically.

    • Use AtomicLong

    • Keep using the Lock object but use a static array of locks with size of about the double number of available CPUs and index it with locks[hashCode() % locks.length]

    And the last option: Use a cache, which is doing this in an optimized way already, like EHCache, Google Guava or cache2k.