1

how to open the same process every time?

i have a java program ,
and i want to create a jar file (i know how to create a jar file),
that every time it opens it will be the same instance.

i used that command:

setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);  

so the user wont be able to close the jar.

now, i dont know how to open the same thread/process ,
when the user double click on the jar again.

please help.. thanks.

Sahar Millis
  • 801
  • 2
  • 13
  • 21
  • 2
    Running a program (including the JVM that runs the JAR) *always* creates a new process. The 'trick' is to have the newly launched program determine if there is already a suitable process running - and if so tell it to show itself. Then the new process terminates itself as it is no longer needed. – user2864740 Jan 26 '16 at 06:53
  • The exact implementation is where it gets hairy; and I really do hope (and suspect) there is a library out there that already takes care of the details. – user2864740 Jan 26 '16 at 06:54
  • thanks really appreciate your help. – Sahar Millis Jan 26 '16 at 06:56
  • See http://stackoverflow.com/questions/177189/how-to-implement-a-single-instance-java-application , http://stackoverflow.com/questions/11179849/run-one-instance-of-java-application?lq=1 etc. for idea starts. (It'll require some form of "IPC" to tell the existing process to show itself.) – user2864740 Jan 26 '16 at 06:57
  • besides the challenges to achieve that behavior, do you mind me asking: what is your ultimate goal? Where does this requirement come from? – reto Jan 26 '16 at 06:57
  • What you need is "single instance" say based on mutex etc. some packaging tools supports it : See http://launch4j.sourceforge.net/docs.html – Jayan Jan 26 '16 at 07:00
  • i created a program that run "behind the scenes", that allows the user some functionality. – Sahar Millis Jan 26 '16 at 07:05

1 Answers1

1

You can change your code as follow:

When starting, your application try to send a message on a dedicated port on localhost. If it is not possible, your application starts listening to this unused dedicated port on localhost.

Doing that, when you run your first instance, this instance will bind the port and listen on it ; when you run your second instance, this instance doesn't really start, it sends a message on first instance and exits.

Then, the first instance receiving the message must just do something, like passing visible and on top the window

void onMessageReceivedFromOtherInstance() {
    yourMainFrame.setVisible(true);
    yourMainFrame.toFront();
}
Prim
  • 2,880
  • 2
  • 15
  • 29