2011-09-14 88 views
1

我創建了一個允許我打開Java程序的單個實例的類。它使用一個打開ServerSocket的守護進程線程。如果TCP端口已被採用,則在實例化時拋出異常。意外套接字有時會關閉(或不打開)

該代碼通常在linux和windows下運行。

這裏是代碼我使用:

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(); 
    } 
} 

有時反而端口沒有不停地忙碌着......任何想法?


UPPENDED經過進一步檢查:

運行許多其他測試。它認爲如果端口被另一個SW實例new ServerSocket(44331);引發,則會引發異常,但有時即使端口因某些原因未被佔用,也無法獲取此資源。在這種情況下,沒有例外,我可以打開儘可能多的實例,我想要的應用程序。也許我應該做一些其他操作強制線程來鎖定端口...

任何想法?

感謝,

科技教育

+0

如何診斷的插座保持封閉狀態?爲什麼你的課堂中有一個未使用的serverSocket字段? –

+0

這段代碼對我沒有意義。你爲什麼不把'ServerSocket'存儲在一個實例變量中,你不能再次訪問它? – home

+0

我使用命令netstat -vatn | grep「44331」。我用它來保證我的應用程序的一個實例 – Stefano

回答

0

我確實感到有點笨的發佈回答我的問題...好..我的代碼有我花了很長想出了一個錯誤:

的問題是,在TE構造我做的:

ServerSocket serverSocket = new ServerSocket(44331); 

代替:

this.serverSocket = new ServerSocket(44331); 

我以前沒注意到它... basicaly的錯誤是,我宣佈在構造函數中本地套接字。當構造程序被終止時,套接字被釋放或不依賴於Garbadge收集器。行爲非常隨機。有趣的部分是,大量的時間打電話/不打電話記錄儀是爲了讓Garbadge收藏家開始或不開始。我注意到這個錯誤花了我相當長的一段時間。

而且最好是把一個:

this.serverSocket.close()等待之後。

Thans幫助反正!

乾杯,

科技教育

0

當你不守到的ServerSocket將有資格獲得GC的參考。如果您使用的是Oracle JDK,則該套接字在GCed時會關閉(java.net.PlainSocketImpl)。