13

How can Java code obtain a unique identifier for the JVM in which it's running? On a Unix system, an example of what I'm looking for would be the PID of the process in which the JVM is running (assuming a one-to-one mapping between JVM's and processes).

Steve Emmerson
  • 7,702
  • 5
  • 33
  • 59
  • See http://stackoverflow.com/questions/35842/process-id-in-java for more info on getting process ID from the current Java process. [This blog entry](http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html) also has some good info. – prunge Nov 28 '11 at 22:03

3 Answers3

15

We have been using:

import java.lang.management.ManagementFactory;
String jvmName = ManagementFactory.getRuntimeMXBean().getName();

Which gives something like <pid>@<hostname>, at least in Sun/Oracle JVMs.

Erik van Oosten
  • 1,541
  • 14
  • 16
13

One simple method of creating a unique ID for each JVM is to start a static ServerSocket, set to use port 0 upon which it will grab any free port. Since no two ServerSockets (JVM or otherwise) can exist on the same port they will all be unique and you can query it for the port number. Since it is static there will be only one per JVM.

This does depend on what permissions you have but in most cases it works just fine and you can always have it bind to "127.0.0.1" to make it less likely to come up against any restrictions.

static ServerSocket myssock;
static int myid;

static {
    myssock = new ServerSocket(0);
    myid = myssock.getLocalPort();
}

If you have multiple JVMs across multiple host machines then you can combine the above with the machine's LAN IP to create a unique JVM ID across a network.

AntonyM
  • 1,602
  • 12
  • 12
0

Basically this all falls on its ass when you consider that you might have JVMs spread across multiple hosts, LANs, or could be used in docker containers you're basically down to generate a UUID from /dev/random.

If having duplicates could cost serious $$$, you might want to avoid this. However if you'd like to know how likely this is consider the math behind the birthday paradox. Since a random UUID has a key space of 2^122, and supposing you have a million JVMs, the probability of a collision is approximately 1e-22

Keynan
  • 1,338
  • 1
  • 10
  • 18