0

I would like to implement a common cache variable storage in order to share between classes. I have many classes because I use cucumber java webdriver and it is necessary to share between steps, page objects/classes.

I have the class

public class Cache {
    private HashMap<String, String> cache = new HashMap<String, String>();

    public HashMap<String, String> getCache() {
        return cache;
    }
}

But the question, what is the most efficient way to set the key-value pairs?

My idea would be use a getter to get and use the stored variables such as cache.get("KEY") and I get the value. How to store variables in efficient way in this cache?

Any example code would be appreciated.

brobee
  • 231
  • 1
  • 5
  • 25

1 Answers1

0
  1. When using 'cache.set(key,val)', the obvious efficiency factor is the selection of key and hash function . However, in 99% percent of my projects it was efficient enough to use a straight-forward, intuitive String key (e.g. if your business requires to cache books by publisher+title, then "penguin_prideAndPrejudice" might do fine). However, the only way to know for sure is to test it on a data sample!

    1. As a side note, though it wasn't your original question, I'd suggest considering thread safely (HashMap isn't thread safe, so for concurrent environments consider synchronization or ConcurrentHashMap - just beware of bugs in some versions)
    2. There are 3rd party caches, such as Guava , that might help with advanced caching considerations, e.g. expiration.
Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11