Preventing Multiple Instances

One of the things I needed to support in my RCP is the ability to prevent multiple copies (instances) of the application from running at the same time.

The solution is surprisingly easy … although, as with many things, not especially well documented.

In your Application class (that implements IApplication) you need to create a lock file in the application’s instance location.

[sourcecode highlight=”6-11,22-24″ language=”java”]
public Object start(IApplicationContext context) throws Exception {
Display display = PlatformUI.createDisplay();

int exitCode = IApplication.EXIT_OK;

Location instanceLocation = Platform.getInstanceLocation();

if (!instanceLocation.lock()) {
MessageDialog.openError(new Shell(display), "App Title",
"Another instance of the Application is currently running.");
} else {

int returnCode = PlatformUI.createAndRunWorkbench(display,
new PatchInstallerWorkbenchAdvisor());
switch (returnCode) {
case PlatformUI.RETURN_RESTART :
exitCode = IApplication.EXIT_RESTART;
break;
default :
exitCode = IApplication.EXIT_OK;
}
}

instanceLocation.release();

display.dispose();

return exitCode;
}
[/sourcecode]

So, before the application starts, a lock file will be created and locked.

If the lock file cannot be locked, it will display an error message and exit.

When the application does exit, the lock is released.

3 thoughts on “Preventing Multiple Instances

  1. Arpit

    On implementing this code my Application gives an IO Exception- The location is not set.
    Any solutions?

    Reply
    1. david Post author

      IO Exception- The location is not set

      Are you getting the exception when invoking the lock method or when invoking getInstanceLocation?

      Are you seeing a workspace location with the ‘-data’ parm when invoking Eclipse?

      Reply
  2. Pingback: Eclipse RCP: How to prevent multiple instances of RCP from launching? - Technology

Leave a Reply

Your email address will not be published. Required fields are marked *