I create a class that allows me to open a single instance of my Java program. It uses a daemon thread that open a ServerSocket. if the TCP Port was already taken throws an exception at instantiation time.

The code works normally under linux and windows.

Here is the code i am using:

```
public class SingleInstaceHandler extends Thread {

    private static final Logger log = Logger.getLogger(IEPLC_Tool.class);
    private boolean finished = false;

    @SuppressWarnings("unused")
    private ServerSocket serverSocket;

    /*
     * Constructor
     * Generate the server socket.
     * If the TCP door was busy throws IOException.
     */
    public SingleInstaceHandler() throws IOException {
        @SuppressWarnings("unused")
        ServerSocket serverSocket = new ServerSocket(44331);
        this.setDaemon(true);
        this.start();
        log.info("Server socket initialized"); //if commented out it works
    }

    public void run() {
        synchronized (this) {
            while (!finished) {
                try {
                    log.debug("Server socket goes to sleep");
                    this.wait();
                    log.debug("Server socket waken up");
                } catch (InterruptedException e) {
                    log.debug("ERROR while sending SocketThread2 in wait status");
                    e.printStackTrace();
                    System.exit(-1);
                }
                log.info("Server socket end");
            }
        }
    }

    public synchronized void shutdown() {
        log.debug("SingleInstaceHandler shutdown() caled");
        finished = true;
        notifyAll();
    }
}

```

Sometimes instead the port is not kept busy... any idea?

---

UPPENDED AFTER FURTHER TESTS:

running many other tests. it seams that if the port is taken by something like another SW instance `new ServerSocket(44331);` throws an exception but sometimes even if the port is not taken for some reason it can not get this resource. in this case no exception is launched and i can open as many instance as i want of my application. maybe i should do some other operation to force the thread to lock the port...

any idea?

Thanks,

Ste