3

I am using @Cacheable annotation of com.jcabi.aspects for caching mechanism in my project and I have a scenario in which I need to flush a particular data from the cache instead of flushing the whole cache. How is it possible?

For example,

import com.jcabi.aspects.Cacheable;
public class Employees {
     @Cacheable(lifetime = 1, unit = TimeUnit.HOURS)
     static int size(Organization org) {
         // calculate their amount in MySQL
     }
     @Cacheable.FlushBefore
     static void add(Employee employee, Organization org) {
         // add a new one to MySQL
     }
}

If I have a class Employees that is used by two organizations Org1 and Org2, now if a new employee is added to Org1, then only Org1's data should be flushed from the cache and Org2's data should remain in the cache.

Reference for com.jcabi.aspects.Cacheable @Cacheable : http://www.yegor256.com/2014/08/03/cacheable-java-annotation.html

Aerus
  • 4,332
  • 5
  • 43
  • 62

1 Answers1

5

It's not possible with jcabi-aspects. And I believe that your design should be improved, in order to make it possible. At the moment your class Employees is not really a proper object, but a collection of procedures (a utility class). That's why caching can't be done right. Instead, you need a new class/decorator MySqlOrganization:

class MySqlOrganization {
  private final Organization;
  @Cacheable
  public int size() {
    // count in MySQL
  }
  @Cacheable.FlushBefore
  public void add(Employee emp) {
    // save it to MySQL
  }
} 

See the benefits of a proper OOP now? :)

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • Well, thanks for the response @yegor256. But one thing more I would like to know- if I have two objects, say e1 and e2, and they are calling a cacheable method, then is it possible in any way that the method is called only for e1, and the e2 object gets the cached result? – ANKIT MITTAL Jan 27 '17 at 18:18
  • @ANKITMITTAL well, this is how it is supposed to work: cacheable method will only be executed once, all other calls to it will return previously cached value. Or I didn't understand the question? – yegor256 Jan 28 '17 at 15:04
  • suppose there are two objects e1 and e2 and both calls the cacheable method add, then the method is called twice, once for each object. Is there any way to call it only once for multiple objects also? – ANKIT MITTAL Feb 01 '17 at 11:48
  • @ANKITMITTAL I think you will have to create a third object, which will encapsulate e1 and e2. If I got your question right. – yegor256 Feb 02 '17 at 17:29