问题
I would like to identify the current JVM which is run. In the best case with a function described in the JVMTI Documentation, but I cannot find anything.
What I meant, is something like this: VirtualMachine.list()
delivers:
[sun.tools.attach.WindowsAttachProvider@46ae506e: 2440 de.fu.profiler.view.MainFrame...
But it displays all JVMs, not the current one being run.
回答1:
You can get a unique name from the RuntimeMXBean. on most platforms, this includes the processid of the current process.
回答2:
Use the Java system properties, for example
java.runtime.name=Java(TM) 2 Runtime Environment, Standard Edition
java.runtime.version=1.5.0_01-b08
java.specification.name=Java Platform API Specification
java.specification.vendor=Sun Microsystems Inc.
java.specification.version=1.5
java.vendor=Sun Microsystems Inc.
java.vendor.url=http://java.sun.com/
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi
java.version=1.5.0_01
java.vm.info=mixed mode, sharing
java.vm.name=Java HotSpot(TM) Client VM
java.vm.specification.name=Java Virtual Machine Specification
java.vm.specification.vendor=Sun Microsystems Inc.
java.vm.specification.version=1.0
java.vm.vendor=Sun Microsystems Inc.
java.vm.version=1.5.0_01-b08
Use java.lang.System.getProperties()
or getProperty(String name)
回答3:
jps (the command line tool bundled with the JDK) will list the currently running Java processes.
You could use JMX to find and attach to different running Java processes.
http://download.oracle.com/javase/1.5.0/docs/guide/management/agent.html
You will need to enable monitoring.
Finding your current PID is very operating system dependent. Here is a blog post with some more suggestions:
http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html
Here are links with some more info:
How can a Java program get its own process ID? http://www.google.com/search?q=find+current+java+process+id
回答4:
Will System.getProperty("java.runtime.name")
do?
回答5:
A JVM does not have a single identifying class that is linked to it's invocation, at least not one that you can easily query.
If you're using JVMTI, you can identify the threads that are running in the JVM that you have connected to. There may be one or more threads, depending on whether the JVM is running a graphical interface, or (for instance) an enterprise container. For the given threads you can examine the stack and identify the current method being called. If you iterate up through the stack you could decide if the parent class is part of the JVM (eg. java.lang.) or an application specific class (eg. com.fun.). This could allow you to uniquely identify the 'target' of the JVM being examined.
来源:https://stackoverflow.com/questions/5583975/identify-the-current-jvm-with-java-or-jvmti