0

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.

Pro Poop
  • 357
  • 5
  • 14
  • 2
    As an object instance, you can provide it however best fits your application. It is common to use a dependency injection framework like Spring or [Guice](https://github.com/google/guice/wiki/GettingStarted) to configure and inject into another object's constructor. Maybe a more background is needed to answer this as I feel its overly broad. – Ben Manes Aug 04 '21 at 22:56
  • 1
    You just need to make a class that holds the cache in a field. – Louis Wasserman Aug 04 '21 at 23:46
  • 1
    You are showing 2 main methods, if they are run separately in two JVMs, there's no way to use a shared memory cache. (I mean you'd have to use another cache system) – Gaël J Aug 07 '21 at 16:24
  • @GaëlJ do you know another cache system that can do what I want? – Pro Poop Aug 07 '21 at 17:55

0 Answers0