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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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




Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}