如何获取唯一的JVM标识符? [英] How to obtain unique JVM identifier?

查看:242
本文介绍了如何获取唯一的JVM标识符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java代码如何为运行它的JVM获取唯一标识符?在Unix系统上,我正在寻找的一个例子是运行JVM的进程的PID(假设JVM和进程之间的一对一映射)。

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).

推荐答案

为每个JVM创建唯一ID的一种简单方法是启动一个静态ServerSocket,设置为使用端口0,它将获取任何空闲端口。由于在同一端口上不能存在两个ServerSockets(JVM或其他),因此它们都是唯一的,您可以查询它的端口号。由于它是静态的,每个JVM只有一个。

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.

这取决于你拥有的权限,但在大多数情况下它可以正常工作,你可以随时使用它到127.0.0.1使其不太可能遇到任何限制。

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();
}

如果您在多台主机上有多个JVM,那么您可以将上述内容与机器的LAN IP通过网络创建唯一的JVM ID。

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.

这篇关于如何获取唯一的JVM标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆