Collision of static variables for two applications in the same jvm
applet, java, jvm, singleton, static
Solution
This test case demonstrates how a static field in a single class can have different values, in the same JVM, when loading the class from two instances of a classloader:
@Test
public void test() throws Exception {
MyLoader customLoader1 = new MyLoader();
MyLoader customLoader2 = new MyLoader();
Class<?> c1 = customLoader1.loadClass(SPECIAL_CLASS_NAME);
Class<?> c2 = customLoader2.loadClass(SPECIAL_CLASS_NAME);
LoadedClass o1 = (LoadedClass) c1.newInstance();
LoadedClass o2 = (LoadedClass) c2.newInstance();
o1.setStaticPart(100d);
o2.setStaticPart(1d);
assertEquals(100d, o1.getStaticPart());
assertEquals(1d, o2.getStaticPart());
}
How to use a custom classloader in an applet I leave as an exercise for the reader. :-)
Problem
I have an applet application which uses several static objects (and we can not get rid of them). The application is launched from html page. Browser creates single jvm for any amount of tabs and thus if you open two tabs with this application, the static variables will be shared with both of them. Both won't work correctly after this. We've tried to use separate_jvm but it doesn't work in every browser. Is there any other solution?