Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Cache Methods Invocations with Memoize Annotation

DZone's Guide to

Groovy Goodness: Cache Methods Invocations with Memoize Annotation

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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




How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}