wang ming
wang ming

Reputation: 199

Can different Java applications use the same javaagent?

I hava a javaagent Jar simpleAgent.jar. I used it to redifine classes in it and I cached some classes to avoid redifine

 public class Premain {

    private static Instrumentation instrumentation;

    private static final Map<String, Class> allLoadClassesMap = new ConcurrentHashMap<>();

    public static void premain(String agentArgs, Instrumentation inst) {
        instrumentation = inst;
        cacheAllLoadedClasses("com.example");
    }

    public static void cacheAllLoadedClasses(String prfixName) {
        try {
            Class[] allLoadClasses = instrumentation.getAllLoadedClasses();
            for (Class loadedClass : allLoadClasses) {
                if (loadedClass.getName().startsWith(prfixName)) {
                    allLoadClassesMap.put(loadedClass.getName(), loadedClass);
                }
            }
            logger.warn("Loaded Class Count " + allLoadClassesMap.size());
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}

I have three different application app1.jar, app2.jar, app3.jar, so when I start the three application can I use the same agent jar? Eg.:

java -javaagent:simpleAgent.jar -jar app1.jar
java -javaagent:simpleAgent.jar -jar app2.jar
java -javaagent:simpleAgent.jar -jar app3.jar

I don't know the javaagent's implementation, so I was scared that using the same javaagent can trigger in app1 or app2 or app3 crash.

Upvotes: 1

Views: 456

Answers (2)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44032

A Javaaget is treated by the VM similarly to jar files on the class path. Those files are read only, all state is contained in the running VM such that they are safely shared among multiple processes.

Upvotes: 0

AlexR
AlexR

Reputation: 115378

Each JVM instance is separate and does not "know" about other JVMs unless you do something in application level. So, generally the answer is "yes, you can use the same jar either javaagent or not for as many JVM instances as you want."

Upvotes: 2

Related Questions