Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: automatic memoization

I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization.

I don't want to implement that manually for every function separately. Is there some way (for example like in Python) I can just use an annotation or do something else so I get this automatically on those functions where I want it?

like image 526
Albert Avatar asked Oct 14 '10 15:10

Albert


People also ask

What is memoization in Java?

Memoization ensures that a method doesn't run for the same inputs more than once by keeping a record of the results for the given inputs (usually in a hash map).

Is caching the same as memoization?

Memoization is a specific form of caching that involves caching the return value of a function based on its parameters. Caching is a more general term; for example, HTTP caching is caching but not memoization.

Can every function be Memoized?

A function can only be memoized if it is referentially transparent; that is, only if calling the function has exactly the same effect as replacing that function call with its return value.

Why is it called memoization and not memorization?

The term "memoization" was introduced by Donald Michie in the year 1968. It's based on the Latin word memorandum, meaning "to be remembered". It's not a misspelling of the word memorization, though in a way it has something in common. Memoisation is a technique used in computing to speed up programs.


2 Answers

Spring 3.1 now provides a @Cacheable annotation, which does exactly this.

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.

like image 110
oksayt Avatar answered Oct 05 '22 23:10

oksayt


I came across a memoization library called Tek271 which appears to use annotations to memoize functions as you describe.

like image 36
Jacob Mattison Avatar answered Oct 06 '22 00:10

Jacob Mattison