Preventing multiple instances of an application to start
Hello, I had the problem that I did not want multiple instances of my
application to start. I would like instead to have the command line
parameters (file paths in my case) of a second starting instance to be
forwarded to the first already running app (eg. if someone double-clicks
on an associated file type).
Here is the solution I came up with (posting it for future reference).
Any comments/corrections are welcome (this is my first try at RMI).
Phil
-- RemoteContactInterface.java --
import java.io.File;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteContactInterface extends Remote {
void loadFile(File f) throws RemoteException;
}
-- MyMainClass.java --
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class MyMainClass extends JFrame implements RemoteContactInterface {
MyMainClass(){
// start RMI server
try {
int PORT = 1099;
LocateRegistry.createRegistry(PORT);
RemoteContactInterface stub =
(RemoteContactInterface)UnicastRemoteObject.exportObject(this, PORT);
Registry registry = LocateRegistry.getRegistry();
registry.bind("myClassID", stub);
System.out.println("Server ready");
} catch (Exception e) {
System.err.println("RMI Server exception: " + e.toString());
e.printStackTrace();
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(new JLabel("Hello World"));
pack();
setVisible(true);
}
public static void main(String args[]) {
try {
Registry registry = LocateRegistry.getRegistry(null);
RemoteContactInterface stub = (RemoteContactInterface)
registry.lookup("myClassID");
for(String s: args){
File f = new File(s);
stub.loadFile(f);
}
System.out.println("App already running");
System.exit(0);
} catch (Exception e) {
// if exception is thrown, no other process already exists
// go on with normal loading
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyMainClass myClass = new MyMainClass();
}
});
}
public void loadFile(File f) throws RemoteException {
// load the file here;
}
}