Thursday, February 26, 2009

Single Instance Application in JAVA

Hello Friends,


One of the most asking question in java world is how to make java
application as a single instance.

I google it and found many of the techniques.
I am posted here some of popular techniques.
Just go ahead and contact if you have problem......

1. By capturing port or through ServerSocket (short code) .
On this method we are creating a object of java.net.ServerSocket class.
And by passing a port number we are captured while first instance so
that if another instance occurred it is throwing a bind Exception and
you can tracked that any more instance is running on system.

Just see the link for code


2. By capturing port or through ServerSocket (Big code).
It is same as the first method but while google i got this big code with
different option just go through the code.

Just see the link for code
See the original source here get from google


3. By accessing file from local file system.
This is also another method for doing the same thing.
But it is not that much preferable because sometime when JVM
crashes or due to some IO error occured then file is not deleted
from hard disk.
note:- Dont put your file (you can use any file) in C drive or where OS exist.

Just see below for code

/*

* Program for setting single instance in JAVA

* Copyright 2009 @ yuvadeveloper

* Code By:- Prashant Chandrakar

*

*/

import java.net.ServerSocket;

import javax.swing.JOptionPane;

import javax.swing.JFrame;

import java.io.IOException;

import java.net.BindException;

class SingleInstance

{

public static ServerSocket serverSocket;

public static String errortype = "Access Error";

public static String error = "Application already running.....";

public static void main(String as[])

{

try

{

//creating object of server socket and bind to some port number

serverSocket = new ServerSocket(15486);

////do not put common port number like 80 etc.

////Because they are already used by system

JFrame jf = new JFrame();

jf.setVisible(true);

jf.setSize(200, 200);

}

catch (BindException exc)

{

JOptionPane.showMessageDialog(null, error, errortype, JOptionPane.ERROR_MESSAGE);

System.exit(0);

}

catch (IOException exc)

{

JOptionPane.showMessageDialog(null, error, errortype, JOptionPane.ERROR_MESSAGE);

System.exit(0);

}

}

}



4. By using java sun.jvmstat package from tools.jar.

Just see the link for code

5. By using Launch4j application.
It is a third party tools for creating a EXE for your application.
It is giving you a facility of creating single instance application.
Just try it. It is perfect tool.

Just see the launch4j application doc

1 comment:

  1. Thankyou so much...
    I have searched many web sites..But got the correct solution here to get single instance of my app..

    ReplyDelete