I have a singleton object that implements some basic functionality in a common library. It's much more complicated than this, but for documenting the issue, below is the Singleton implementation, with all but one inner properties/objects removed:
package mystuff.lib.common
public class CommonSingleton {
public final static CommonSingleton INSTANCE = new CommonSingleton();
private Cache<String, Object> cache = null;
private CommonSingleton() {
// Exists only to defeat instantiation.
Initialize();
}
private void Initialize() {
cache = null;
}
public Cache<String, Object> getCache() {
if (cache == null) {
cache = new Cache<String, Object>();
}
return cache;
}
public void Reload() {
Initialize();
}
}
I have included that library in two SEPARATE projects. The library isn't installed on the machine where the code runs. The contents of the common library is included within each JAR when the artifacts are created in IntelliJ IDEA.
Both projects (JAR files) load and run (as plugins) inside a parent application, so they're both loaded inside the same JVM. I expected each JAR to have its own copy of this common singleton, since they are, after all, separate JAR files. It is only included in a common library because many of my projects require the same functionality and I would rather include the library in my project than have multiple copies of the code floating around.
Project/Module #1: TestPluginOne.JAR
package mystuff.plugins.TestPluginOne;
import mystuff.lib.common.CommonSingleton;
import mystuff.lib.common.Objects.Cache;
public class TestClassOne {
public TestClassOne() {
}
public Boolean SaveItemInCache(String key, String content) {
return CommonSingleton.INSTANCE.getCache().add(key, content, 30);
}
public void Reload() {
CommonSingleton.INSTANCE.Reload();
}
}
Project/Module #2: TestPluginTwo.JAR
package mystuff.plugins.TestPluginTwo;
import mystuff.lib.common.CommonSingleton;
import mystuff.lib.common.Objects.Cache;
public class TestClassTwo {
public TestClassTwo() {
}
public String GetItemFromCache(String key) {
return CommonSingleton.INSTANCE.getCache().get(key);
}
public void Reload() {
CommonSingleton.INSTANCE.Reload();
}
}
I am finding, however, that when I use this object in both of my modules (separate JAR files, mind you), that they are both accessing the same singleton. While this particular example with a Cache object, might not indicate any issue with this, there are many reasons why I need these treated as separate objects. There are many internal/private member variables that need to contain different values, depending on the project/module/plugin that is consuming this Singleton.
I'm confused. When I do this in .NET (for example) in separate DLLs, each DLL maintains it's own internal instance of that common object.
How can I have this common Singleton functionality included in separate projects, from a common library, without them sharing instances of the Singleton object?
Thanks!