开发者

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

开发者 https://www.devze.com 2022-12-30 02:22 出处:网络
I need a way to uniquely and permanently identify an instance of the JVM from within Java code running in that JVM.

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 t开发者_运维知识库hough 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?


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.


You could create a UUID on application startup and use that for identification.

UUID UniqueID = UUID.randomUUID();


If UUIDs are too heavy-weight, you need to review what you mean by "uniquely and permanently".

For example, if you were to limit "unique and permanent" to mean unique for machines on a given network, and permanent for the next (say) 10 years, you could use the same approach used in UUID generation but with fewer bits.

Alternatively, if you were to create a unique id generation service with a persistent store, and tie the notion of "permanent" to the lifetime of that store, then the unique ids could simply be an incrementing sequence of integers.


Why not use Singleton holding instance of java.rmi.server.UID?


I do not know of a standard library for this, but you can get far on your own with the start time (do some calculations with new java.util.Date() and System.currentMillis), the path to the installation, and the path to the JVM (consider just concatenating all System.getProperties()).

Do you have a central server these can talk to? Then a uuid can be retreived from the central server.

0

精彩评论

暂无评论...
验证码 换一张
取 消