java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.lang arrow Preventing multiple instances of an application
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 3947
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Preventing multiple instances of an application E-mail
User Rating: / 16
PoorBest 

Because each application is running in it's own JVM, there is no obvious way to detect if a particuliar application is already running.

The socket technique

One way to detect to prevent multiple application execution is to use a simple socket server. The application will try a connection to that Server, if it's a success then the application is already running (and the application is stopped), if no connection is made then the application create the Server.

In this example, the simple server is running on the same machine as the application so the machine name is "localhost", the port 80 is used, you may want to customize the port number for your machine.

[JustOneServer.java]
        
import java.io.*;
import java.net.*;

public class JustOneServer extends Thread {
    // you may need to customize this for your machine
    public static final int PORT = 80 ;
    
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    
    public void run() {
        try {
            // Create the server socket
            serverSocket = new ServerSocket(port, 1);
            while (true) {
                // Wait for a connection
                clientSocket = serverSocket.accept();
                // System.out.println("*** Got a connection! ");
                clientSocket.close();
            }
        catch (IOException ioe) {
            System.out.println("Error in JustOneServer: " + ioe);
        }
    }
}


[JustOne.java]
        
import java.io.*;
import java.net.*;

public class JustOne {
    
    SimpleDummyServer sds = null;
    
    public static void main(String args[]){
        new JustOne().doit();
    }
    
    public void doit() {
        
        try {
            Socket clientSocket = new Socket("localhost", JustOneServer.PORT);
            System.out.println("*** Already running!");
            System.exit(1);
        catch (Exception e) {
            sds = new JustOneServer();
            sds.start();
        }
        
        while(true) {
            try 
            
                System.out.print(".")
                Thread.sleep(60)
            
            catch(Exception e) { 
                e.printStackTrace()
            }
        }
    }
}

To test it out, open 2 consoles.

In console 1 , type java JustOne.

In console 2, type java JustOne and the application should response "Already running!".

The file lock technique

[JDK1.4+] You can use a flag file with a lock mechanism. The idea is to create and lock a file on user.home folder with a provided name. A concurrent execution will try to lock the same file and will failed. A special "shutdown hook" is provided to unlock the file when the JVM is shutting down.

[JustOneLock.java]
        
import java.io.*;
import java.nio.channels.*;

public class JustOneLock {

    private String appName;
    private File file;
    private FileChannel channel;
    private FileLock lock;
    
    public JustOneLock(String appName) {
        this.appName = appName;
    }
    
    public boolean isAppActive() {
        try {
            file = new File(System.getProperty("user.home"), appName + ".tmp");
            channel = new RandomAccessFile(file, "rw").getChannel();
            
            try {
                lock = channel.tryLock();
            catch (OverlappingFileLockException e) {
                // already locked
                closeLock();
                return true;
            }
            
            if (lock == null) {
                closeLock();
                return true;
            }
            
            Runtime.getRuntime().addShutdownHook(new Thread() {
                // destroy the lock when the JVM is closing
                public void run() {
                    closeLock();
                    deleteFile();
                }
            });
            return false;
        catch (Exception e) {
            closeLock();
            return true;
        }
    }
    
    private void closeLock() {
        try lock.release();  catch (Exception e) {  }
        try channel.close()catch (Exception e) {  }
    }
    
    private void deleteFile() {
        try file.delete()catch (Exception e) { }
    }
}

[JustOneTest.java]
        
public class JustOneTest {
    
    public static void main(String[] args) {
        new JustOneTest().test();
    }
    
    void test() {
        JustOneLock ua = new JustOneLock("JustOneId");
        
        if (ua.isAppActive()) {
            System.out.println("Already active.");
            System.exit(1);
        else {
            System.out.println("NOT already active.");
            try {
                while(true) {
                    try 
                        System.out.print(".")
                        Thread.sleep(60)
                    catch(Exception e) { 
                        e.printStackTrace()
                    }
                }
            catch (Exception e) {  }
        }
    }
}

 Related Tips

 
< Prev   Next >

Page 1 of 0 ( 0 comments )

You can share your information about this topic using the form below!

Please do not post your questions with this form! Thanks.


Name (required)


E-Mail (required)

Your email will not be displayed on the site - only to our administrator
Homepage(optional)



Comment Enable HTML code : Yes No



 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.