LoadingCache

Discussion in 'Plugin Development' started by JanTuck, Jan 16, 2017.

Thread Status:
Not open for further replies.
  1. Offline

    JanTuck

    I'm new to this cache thingy.

    Code:java
    1. private LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
    2. .expireAfterAccess(15, TimeUnit.MINUTES)
    3. .build(
    4. new CacheLoader<String, Object>() {
    5. public Object load(String key) { // no checked exception
    6. return getData(key);
    7. }
    8. });
    9.  
    10.  
    11.  
    12. private Object getData(String key) {
    13. return cache.getIfPresent(key);
    14. }
    15.  
    16. private boolean cache(String key, Object data) {
    17. if (data != null) {
    18. cache.put(key, data);
    19. } else {
    20. cache.invalidate(key);
    21. }
    22. return true;
    23. }
    24.  
    25. private boolean hasCached(String key, Object data) {
    26. if (getData(key) != null && getData(key) == data)
    27. return true;
    28. return false;
    29. }
    30.  
     
  2. Offline

    DoggyCode™

    That's not how it works.
    PHP:
    LoadingCache<KeyObjectcache CacheBuilder.newBuilder()
      .
    maximumSize(1000)
      .
    removalListener(new MyRemovalListener())
      .
    expireAfterWrite(10TimeUnit.MINUTES)
      .
    build(new MyCacheLoader());
    MyRemovalListener implements RemovalListener<Key, Value> and overrides a method called onRemoval(
    RemovalNotification rn). This method represents what will happen when the object is removed from cache (there can be multiple causes: the cache reached its maximum size, the object hasn't been accessed for the expire after write time, or removed on purpose). rn.getKey() returns the key of the cache map, and rn.getValue() returns the value. You can use these getters to save the data directly to a file.

    MyCacheLoader extends CacheLoader<Key, Value> and overrides a method called load(Key k). This method represents what how to load the object into memory (cache), it requires that you return an instance of Value. Here you could return a new instance of Value with its variables/data collected from the config/a file.

    Calling get(Key k) on the LoadingCache, will load (if it hasn't already been loaded) and return the value. You don't have to worry about anything, this will run for itself now.
     
  3. Offline

    JanTuck

    @DoggyCode™
    Ohh no, it works fine just wanted to know if there was some better ways so thx.
     
Thread Status:
Not open for further replies.

Share This Page