How to make sure that only a single instance of a Java application is running?

前端 未结 11 1729
你的背包
你的背包 2020-12-09 20:23

I want my application to check if another version of itself is already running.

For example, demo.jar started, user clicks to run it again, but the sec

11条回答
  •  臣服心动
    2020-12-09 20:51

    If your application is running on Windows, you can call CreateMutex through JNI.

    jboolean ret = FALSE;    
    HANDLE hMutex = CreateMutex(NULL, FALSE, mutexName); 
    ret = TRUE;    
    if(WAIT_TIMEOUT == WaitForSingleObject(hMutex, 10))  
    {    
        ret = FALSE;  
    }
    else if(GetLastError() != 0)  
    {    
        ret = FALSE;  
    }
    

    This returns true if nobody else is using this mutex, false otherwise. You could provide "myApplication" as a mutex name or "Global\MyApplication" if you want your mutex to be shared by all Windows sessions.

    Edit: It's not as complicated as it looks :) and I find it clean.

提交回复
热议问题