Groovy @Memoize expiry based on custom event

609 views Asked by At

I am using groovy to process a batch job, I am planning to cache domain object by using groovy's @Memoize annotation, but problem is the expiry, I want to expire the cache when the job is finished. Is there any way to tell groovy to expire the cache from code?

1

There are 1 answers

0
Will On

As per the docs, @Memoized features only a max value and a protection cache size parameters.

Since the AST under the covers will create the memoize mechanism through Closure::memoize, you could emulate it with a map and memoized closures which can be disposed:

class Job {
    def log = []
    def repoBase = [
        sum: { a, b ->
            log << "sum $a and $b"
            a + b
        },
        multiply: { a, b ->
            log << "multiply $a and $b"
        }
    ]

    def repo

    def startJob() {
        repo = repoBase.collectEntries { key, value -> 
            [(key): value.memoize()] 
        } as Expando
    }

    def withJob(Closure c) {
        startJob()
        c.delegate = repo
        c.delegateStrategy = Closure.DELEGATE_FIRST
        c(this)
        repo = null
    }

}

And test:

j = new Job()

j.withJob {
    multiply 3, 4
    multiply 3, 4
    multiply 8, 8
    sum 9, 9
    sum 1, 2
    sum 9, 9
}

assert j.log == [
    "multiply 3 and 4",
    "multiply 8 and 8",
    "sum 9 and 9",
    "sum 1 and 2"
]