Over a million developers have joined DZone.

Groovy Goodness: Cache Methods Invocations with Memoize Annotation

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

In Groovy we can cache closure results with memoization. In Groovy 2.2 a new @Memoize AST transformation is added, which can be used to cache plain method results. We apply the annotation to our method and the result of the method is cached if the method is invoked for the first time. If we invoke the method a second time with the same arguments then the cached result is returned.

In the following sample we want to cache the method increment(int). We use a script variable incrementChange to show when a cached method invocation takes place or a non-cached one.

import groovy.transform.*

// Script variable which is changed when increment()
// method is invoked. 
// If cached method call is invoked then the value
// of this variable will not change.
@Field boolean incrementChange = false

@Memoized 
int increment(int value) {
    incrementChange = true
    value + 1 
}

// Invoke increment with argument 10.
increment(10)

// increment is invoked so incrementChange is true.
assert incrementChange

// Set incrementChange back to false.
incrementChange = false

// Invoke increment with argument 10.
increment(10)

// Now the cached method is used and
// incrementChange is not changed.
assert !incrementChange

// Invoke increment with other argument value.
increment(11)

// increment is invoked so incrementChange is true.
assert incrementChange




Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}