Skip to content
Advertisement

Java method should cache the results

I’m learning programming in the language java.

I need to write an application that takes a string and returns the number of unique characters in the string. It is expected that a string with the same character sequence may be passed several times to the method. Since the counting operation can be time-consuming, the method should cache the results, so that when the method is given a string previously encountered

At this stage, my application is already able to count and display characters

JavaScript

The result of the application

JavaScript

Now I need to teach my application to cache and check the input data for an already existing result.

I think LoadingCache from Guava will help me

JavaScript

Please help me pair my app with LoadingCache.

To all who will respond, thanks a lot!

Advertisement

Answer

Please help me pair my app with LoadingCache.

Merry X-Mas! There you go:

  1. LoadingCache<Key, Graph> applied to our code must be LoadingCache<String[],Map<Character, Integer>> matching the input and output types of our …
  2. createExpensiveGraph method applied to our case would be charCounter.
  3. To pair up, we would not invoke charCounter(...) directly, but through a (given) cache instance, so: graphs.get(...).

I refactored “little” (simplified String[] to String, removed “half” of your classes, made the main method interactive), this is what came out:


pom.xml:

JavaScript

Main.java

JavaScript

In- and Output:

JavaScript

(2nd calculation of “hello” is cached.)


We see: Once identifying/understanding/defining

  • “key”
  • “graph” and
  • “expensive graph operation”

, it is easy to a apply a (guava) cache to a given “operation”.

For advanced cache configuration, please refer to CacheBuilder javadoc, for advanced usage to LoadingCache javadoc.

Rather advanced and theoretical but very related to this topic/ use case: Similarity Caching.


To receive “words” from command line arguments, we can use a main() method like this:

JavaScript

To make it completely “without external libs” (i.e. guava)we would (remove/clean up that dependencies,) we would then use it, as outlined in (accepted answer of) Easy, simple to use LRU cache in java :

JavaScript

for “unlimited” cache (might be sufficient for tutor;), just:

JavaScript

(For a thread-safe version, we’d have to:)

JavaScript

LinkedHashMap javadoc 17

We could wrap our “cache loading” then like:

JavaScript

and main method like:

JavaScript

;)#

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement