Problem with static attributes - java

My problem is that I'm working on a project that requires me to run multiple instances of someone elses code which has many static attributes/variables, which causes all the instances to share those resources and, well, crash. I can run multiple instances of this other person's program if I create a .jar file off of it and open it multiple times by running the .jar in windows, but running calling the "main" method multiple times in my code (which is what I need to do) won't work.
I thought about creating a .jar and using Runtime.getRuntime().exec( "myprog.jar" ); to call the program multiple times, but that won't work for me since I have to pass an instance of my object to this new program and I don't think this solution would allow for that.
PS: This is also posted in the Sun forums, so I`ll post the answer I get there here or the answer I get here there naturally giving proper credit once I this is solved =P.

Remember that a static element in Java is unique only in the context of a classloader (hierarchy); a class is uniquely identified in a JVM by the tuple {classloader, classname}.
You need to instantiate isolated classloaders and load the jar using that class loader. Each loaded class (and thus statis elements) are unique in their classloader and will not interfere with one another.

I'd say you have three alternatives:
Refactor the legacy application so that it doesn't use static attributes. If you can do this, this may be the best solution in the long term.
Continue with your approach of launching the legacy application in a separate JVM. There are a number of ways that you can pass (copies of) objects to another JVM. For example, you could serialize them and pass them via the child processes input stream. Or you could stringify them and pass them as arguments. In either case, you'll need to create your own 'main' class/method that deals with the object passing before calling the legacy app.
I think you should be able to use classloader magic to dynamically load a fresh copy of the legacy application each time you run it. If you create a new classloader each time, you should get a fresh copy of the legacy application classes with a separate set of statics. But, you have to make sure that the legacy app is not on your main classpath. The problem with this approach is that it is expensive, and you are likely to create memory leaks.

The description is a little confusing.
If you are running the code multiple times, you are running multiple independent processes, each running in its own JVM. There is no way that they are actually sharing the values of their static fields. Java doesn't let you directly share memory between multiple VMs.
Can you elaborate more (ideally with examples and code) what the attributes are defined as and what kind of failures you are getting? This may be completely unrelated to them being static.
In particular, what exactly do you mean by shared resources? What resources are your programs sharing?

The proper approach was already suggested - using custom ClassLoaders. Another thing comes to my mind, which might seem ugly, but will probably do, and is a bit more object-oriented approach.
The legacy code is used for its operations, and it incorrectly uses static instead of instance variables. You can fix that using inheritance and reflection:
create (or reuse) an utility class that copies instance variables to static ones
extend the classes in question and provide the same instance variables as the static ones
override all methods. In the overriding methods use the utility to copy the state of the current object to the static variables, and then delegate to (call) the super methods.
Then start using instance of your class, instead of the legacy ones. That way you will simulate the proper behaviour.
Have in mind this is NOT thread-safe.

Related

Making a dynamic list of all classes in a package

Let's say I am making a list of possible items in the game. Every one of them is deriving from the class Item and all of them are placed in the specific package "com.name.app.items".
I want to make a list of them created dynamically, without adding any external information apart from the file containing the class.
I tried getting all files in a package and computing them accordingly but to no avail. Reflection simply refuses to cooperate. No matter what configuration I use, a scanner always returns an empty set.
My second thought was to to simply invoke a static method like ItemDatabase.add(this) but as far as I know it isn't possible without creating an instance of this object or calling a static method from outside.
Is there a go-to method for resolving this kind of issue? Or it is necessary to (apart from declaring the very class) notifying some registry of it's existence?
After many hours of research I finally found a suitable answer.
A simple Gradle task did the job for me as Reflections, ClassGraph etc. doesn't work very well on Android.
Bear in mind that if you would like to read what classes are available in a package on runtime - it will be a very difficult task so find another solution or prepare yourself for a long journey.

reflection or runtime class declaring?

well I have a simple question.
we are working on a simple application server(like), and this server accepts clients business at runtime without restarting the server.
When user implements it's business and deploy it to the server, server just try to find out the archive descriptor, and load the modules, and it works good.
some operations need to much reflection calls, and for each call they called again and again. for example there is a method which accepts any object, then search for a certain field witch has signed by a annotation and do some business with it, so if we call this method 1000 times with one same object, this is going to reflect 1000 times.
my question is, is it efficient? I mean doesn't it eat up the CPU?! the only possible solution I'm thinking is that create a class and compile it for each object(maybe wrapper) and the method will just find out the wrapper class. but I know this may make the system complex, and hard to debug.
current solution is working, but I think doing a work 1000 times is kinda not logical even it's simple and easy.
Thanks in advanced.
The use of reflection to dynamically load classes at runtime is not a bad choice per-se. Based on your description, you should provide an extensible framework that allows your client to make an implementation, and run their business logic based on that instead of some implicit run-time annotated magic.
A good real-world example for this off the top of my head is The Servlet API.
for example there is a method which accepts any object, then search
for a certain field witch has signed by a annotation and do some
business with it, so if we call this method 1000 times with one same
object, this is going to reflect 1000 times.
In this case I suggest you to use caching. After reflection is finished you'll know class name and the field name. Store them in a HashMap with Class type key and a Method as a value.
Next time you invoke "the method" check cache first.

Dynamic program updating, runtime compilation, and class loaders

I have an application that needs the ability to update parts of itself (one class at a time) without stopping and restarting. With the JavaCompiler API, it is straightforward to generate modified class source code, recompile, load, and instantiate a class. I can do this all in memory (no files read from disk or net).
The application will never instantiate more than one object of such a class. There will only be two or three references to that object. When the modified class is loaded and instantiated, all those references will be changed to the new object. I can also probably guarantee that no method in the affected class is running in another thread while loading the modified class.
My question is this: will my class loader have problems loading a modified class with the same name as a class it previously loaded?
If I do not explicitly implement a cache of loaded classes in the class loader, would that avoid problems? Or could delegation to a parent class loader still cause a problem?
I hope to use a single instance of my class loader, but if necessary, I could instantiate a new one each time I update a class.
Note: I looked at OSGI and it seems to be quite a bit more than I need.
There's a useful example on this at http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
We do quite a bit of dynamic class reloading ourselves (using Groovy for compilations). Note if you've got class dependencies then you may need recompile these dependencies on reload. In dev stacks we keep a track of these dependencies and then recompile whenever dependencies become stale. In production stacks we opted for a non-reloading ClassLoader and create a new ClassLoader when ever anything changes. So you can do it either way.
BTW - you might find the GroovyScriptEngine at http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.groovy/groovy-all/1.8.5/groovy/util/GroovyScriptEngine.java#GroovyScriptEngine very interesting if you want to dig around how they do it.
Okay, it should work: when you load the new class, it will replace the class name in the appropriate tables, and the memory should be GC'd. That said, I'd give it a strenuous test with a real short program that compiles a nontrivial class and replaces it, say 10,000 times.

Where to put business logic in Eclipse RCP program

I'm writing a small application in RCP to wrap around the business logic in another (non-RCP) simulation library. I can access and use the library fine from any of my plugins, but I don't know where I should put the instance of the Simulation library so that, say, one of the command handlers can make calls to it.
From reading the docs it sounds like I should be storing 'global' information like this in the workbench - but I still don't really understand how to do that.
Help?
First, the business layer (BL) can and should reside in its' own plugin. That will provide decent decoupling between the layers.
Second, you should carefully decide what the interface should be and which classes are exposed. Ideally, you should mostly expose interfaces and data objects.
Finally, decide how the "hand shake" works. E.g., how to obtain the initial interface to the BL. Since it is a Plugin, it could have an Activator which loads it. You could add a method in the activator which returns the BL interface.
If you are looking for something more decoupled, you could create an extension point or deploy the BL as an OSGi service, but that's a bit of an overkill for you need.
If I understand you correctly, I see two ways:
Store the instance in the model plug-in itself, using ‘SimulationFactory.getInstance(String myAppId)‘. The passed String is a constant in you app that is always used, when obtaining the reference.
Define a new class e.g. GlobalAccess in you app that is initilized with an instance of your model and has some getter (whether you use a single instance again or only provide public static methods is a matter of taste).
The seocond way is similar to some classes in eclipse like platfom or platformui, where you can obtain initial references and navigate through the workbench.
edit
i just found a tutorial that might help you:
Passing Data between Plug-ins

Unloading classes passed via RMI

I have a simple RMI 'compute' server application (similar to this) that accepts objects of some interface type from clients over RMI, executes the compute() method of the received object and returns the result over RMI to the remote client. The jobs are 'one-offs' and there is no interaction between the different jobs or between objects of different jobs.
I would like to be able to modify classes and submit instances to the compute server for execution without constantly restarting the server JVM. However when a class that has been modified is submitted again as a parameter to a remote call it's method behaviour does not change (this occurs with anonymous classes also). I have been reading up about serialization and I realise that this is to do with the ClassLoader being unable to modify existing classes.
From my reading on SO and elsewhere I realise that somehow the ClassLoader that loaded the stream class must be GC'd and replaced in order to load a new version of my class. I have an idea how to do this but the situation seems complicated by the underlying RMI runtime and it having its own RMIClassloader.
My question is: What would be the easiest way to load each new version of a class received via RMI parameters. Ideally I'm looking for a way to have each remote call get a new ClassLoader and to dispose of it upon return. Is this feasible to do without an intricate knowledge of customised ClassLoaders and the internals of RMI?
Any pointers to reading materials or examples welcome!
Edit: here is the compute server's remote interface:
public interface ComputationEngine extends Remote {
public Object execute(Task t) throws RemoteException;
}
and the 'compute job' interface, Task:
public interface Task extends java.io.Serializable {
public Object compute();
}
The only way to this is to have a new ClassLoader when you want to change a Class.
How about making use of the URLClassLoader and making the code available from a URL
I use it in one of my projects to update APIs when the jar file changes. Take a look here:
http://code.google.com/p/open-forum/source/browse/trunk/Wiki/org/one/stone/soup/wiki/jar/manager/JarManager.java
Line 184+
Check your emails :-)
This isn't really answering your question, but it might be possible to make changing part of your classes into data instead of the actual class. Use a Map instead of fields, etc. You'd have a lot fewer classes floating around, and your code would probably be simpler too.

Categories