Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I identify in which Java Applet context running without passing an ID?

Tags:

java

applet

swing

I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showing) and non-shared context (specific to each applet currently showing).

However, we don't have an ID at each of the locations that call to the singleton, nor do we want to propagate the ID to all locations. What's the easiest way to identify in which applet context we're running? (I've tried messing with classloaders, thread groups, thread ids... so far I could find nothing that will enable me to ID the origin of the call).

like image 975
Ran Biron Avatar asked Aug 10 '08 18:08

Ran Biron


1 Answers

Singletons are evil, what do you expect? ;)

Perhaps the most comprehensive approach would be to load the bulk of the applet in a different class loader (use java.net.URLClassLoader.newInstance). Then use a WeakHashMap to associate class loader with an applet. If you could split most of the code into a common class loader (as a parent of each per-applet class loader) and into the normal applet codebase, that would be faster but more work.

Other hacks:

If you have access to any component, you can use Component.getParent repeatedly or SwingUtilities.getRoot.

If you are in a per-applet instance thread, then you can set up a ThreadLocal.

From the EDT, you can read the current event from the queue (java.awt.EventQueue.getCurrentEvent()), and possibly find a component from that. Alternatively push an EventQueue with a overridden dispatchEvent method.

like image 136
Tom Hawtin - tackline Avatar answered Sep 22 '22 14:09

Tom Hawtin - tackline