Is it possible to get a truly unique id for a particular JVM instance?

Uri picture Uri · May 14, 2010 · Viewed 7.5k times · Source

I need a way to uniquely and permanently identify an instance of the JVM from within Java code running in that JVM.

That is, if I have two JVMs running at the same time on the same machine, each is distinguishable. It is also distinguishable from running JVMs on other machines and from future executions on the same machine even if the process id is reused.

I figure I could implement something like this by identifying the start time, the machine MAC, and the process id, and combining them in some way. I'm wondering if there is some standard way to achieve this.

Update: I see that everyone recommended a UUID for the entire session. That seems like a good idea though possibly a little too heavyweight. Here is my problem though: I want to use the JVM id to create multiple unique identifiers in each JVM execution that somehow incorporate the JVM instance.

My understanding is that you shouldn't really mix other numbers into a UUID because uniqueness is no longer guaranteed. An alternative is to make the UUID into a string and chain it, but then it becomes too long. Any ideas on overcoming this?

Answer

Jesper picture Jesper · May 14, 2010

You could generate a UUID at the start of your program and use that during the time the program is running.

UUID id = UUID.randomUUID();

Besides the method randomUUID() there are other methods to generate UUIDs that might fit your needs better, see the API documentation of class java.util.UUID for more information.