Reputation: 23624
Disclaimer: This is probably not the best solution given the issue, but I'm curious how this implementation could be achieved.
Problem I'm trying to deal with some legacy code which has a singleton defined like bellow:
public class LegacySingleton {
private static Boolean value;
public static void setup(boolean v) {
if (value != null) {
throw new RuntimeException("Already Set up");
}
value = v;
System.out.println("Setup complete");
}
public static void teardown() {
value = null;
System.out.println("Teardown complete");
}
public static boolean getValue() {
return value;
}
}
I do not have the ability to change this design and the class is used heavily throughout the code base. The values returned by this singleton can greatly change the functionality of the code. Eg:
public class LegacyRequestHandler {
public void handleRequest() {
if (LegacySingleton.getValue()) {
System.out.println("Path A");
} else {
System.out.println("Path B");
}
}
}
Right now if I want the code to take Path A
, then I have to initialize LegacySingleton
in a particular way. If I then want to take Path B
I have to re-initialize the LegacySingleton
. There is no way of handling requests in parallel which take different paths; meaning for each different configuration of LegacySingleton
required I need to launch a separate JVM instance.
My Question Is it possible to isolate this singleton using separate class loaders? I've been playing around with the ClassLoader
API, but I cant quite figure it out.
I'm imagining it would look something along the lines of this:
public class LegacyRequestHandlerProvider extends Supplier<LegacyRequestHandler> {
private final boolean value;
public LegacyRequestHandlerProvider(boolean value) {
this.value = value;
}
@Override
public LegacyRequestHandler get() {
LegacySingleton.setup(value);
return new LegacyRequestHandler();
}
}
...
ClassLoader loader1 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier1 = loader1
.loadClass("com.project.LegacyRequestHandlerProvider")
.getConstructor(Boolean.TYPE)
.newInstance(true);
ClassLoader loader2 = new SomeFunkyClassLoaderMagic();
Supplier<LegacyRequestHandler> supplier2 = loader2
.loadClass("com.project.LegacyRequestHandlerProvider")
.getConstructor(Boolean.TYPE)
.newInstance(false);
LegacyRequestHandler handler1 = supplier1.get();
LegacyRequestHandler handler2 = supplier2.get();
Upvotes: 9
Views: 779
Reputation: 2691
In my view –and my apologies that this is a largely opinion-based answer– this is a business problem and not a technical problem, because the constraints given ("I cannot change the code") are not technical ones. But as anybody working in software development can attest, business constraints are part and parcel of our jobs.
Your issue can be abstracted as follows: "Considering constraint A, can I get result B?" And the answer is: "No, you cannot." Or perhaps you can, but with a solution that is difficult –in other words, expensive– to maintain and prone to break.
In cases like these, it would be good to know why you cannot change the software that has obvious and very serious design problems. Because that is the real problem.
Upvotes: 2
Reputation: 2328
Does plain simple reflection work at specific points in time, where you want the output of getValue
to change?
Field f = LegacySingleton.class.getDeclaredField("value");
f.setAccessible(true);
f.set(null, true|false);
If not, For the Classloader approach, you can follow a Plugin architecture. But as others have noted, this may boil down to the whole dependencies being loaded on 2 different Classloader hierarchies. Also, you may face LinkageError
issues, depending on how the dependencies work in your codebase.
Inspired by this post:
LegacyRequestHandler
class and do not include in the application/main classpath.Have a wrapper invoker that will initialise the class loader with the jar path providing LegacySingleton
class, e.g.
new ParentLastURLClassLoader(Arrays.asList(new URL[] {new URL("path/to/jar")}));
Post that, you can load the singleton in it's class loader space and obtain copies.
//2 different classloaders
ClassLoader cl1 = new ParentLastURLClassLoader(urls);
ClassLoader cl2 = new ParentLastURLClassLoader(urls);
//LegacySingleton with value = true in Classloader space of cl1
cl1.loadClass("LegacySingleton").getMethod("setup", boolean.class).invoke(null, true);
//LegacySingleton with value = false in Classloader space of cl1
cl2.loadClass("LegacySingleton").getMethod("setup", boolean.class).invoke(null, false);
cl1/2
) and trigger execution. NOTE that you shouldn't refer to the classes in the Legacy code directly in the main class, as then they will be loaded using Java primordial/application class loader.
Upvotes: 3
Reputation: 2101
/First, tell your lead that you are about spend time and make convoluted code that uses more memory and could be slower due to jit re-compilation and other class init issues, because you are somehow not allowed to fix bad obsolete code. Time and maintainability is money./
Ok, now... Your funky classloaders are just URL classloaders with the required jars given. But the trick is to NOT have the singleton nor the handlers in the main classpath, otherise the classloader will find the class in a parentclassloader (that has precedence) and it will still be a singleton. You knew that I'm sure.
Another radical solution is to re-implement the offending class your way (with properties file, or with a Threadlocal field (assuming the work is done on same thread) that a caller can set before making the call to the handler, which in turn will not see the mascarade).
You would have to deploy your overriding class with precedence in the classpath (list the jar earlier), or for a webapp, if you can, deploy in the web-inf/classes which overrides anything in the web-inf/lib. You can ultimately just delete the class from the legacy jar. The point is to have the same classname, same methods signature, but a new implementation (again, that relies on loading cfg files or using threadlocal setup before the call).
Hope this helps.
Upvotes: 3