Pro Poop
Pro Poop

Reputation: 456

Use caffeine cache instance in a separate java class/file?

Is there a way to use the same instance of a cache in a different file? When I create a cache in Main.java, and write it like this:

public class Main {
   public Cache<String, String> cache = Caffeine.newBuilder()
      .expireAfterWrite(2, TimeUnit.HOURS)
      .maximumSize(250)
      .build();
  public static void main(String[] args) {

  }
}

And want to access it from another class located in a separate file, how would I go about that?

I think it would just be the following code (Second.java)

import Main;
public class Second {
  public static void main(String[] args) {
     Main main = new Main();
     main.cache.put('key', 'value');
  }
}

But the problem is that it creates a new instance of the Main class, hence creating a new cache. Because in Main.java, when the following code is executed it produces null.

public class Main {
   public Cache<String, String> cache = Caffeine.newBuilder()
      .expireAfterWrite(2, TimeUnit.HOURS)
      .maximumSize(250)
      .build();
  public static void main(String[] args) {
    //A key/value is created in Second.java
    cache.getIfPresent('key'); // => 'null'
  }
}

By the way I'm making an event-driven Minecraft plugin so the key/value should already be created via a command.

Upvotes: 0

Views: 723

Answers (0)

Related Questions