2013-05-06 79 views
0

目前我有類似以下代碼:釋放BufferedReader.readLine(),而用synchronized方法鎖定

public class CtrlServer { 
    private ServerSocket ss; 
    private Map<Integer, Socket> s; 
    private Map<Integer, PrintWriter> out; 
    private Map<Integer, BufferedReader> in; 

    public CtrlServer(){ 
     ss = null; 
     s = new HashMap<Integer, Socket>(); 
     out = new HashMap<Integer, PrintWriter>(); 
     in = new HashMap<Integer, BufferedReader>(); 
    } 
    public CtrlServer(int port) throws Exception{ 
     this(); 
     if(!initialize(port)) 
      throw new Exception(); 
    } 
    public synchronized boolean initialize(int port){ 
     try{close();}catch(Exception e){} 
     try{ 
      ss = new ServerSocket(port); 
     } catch(Exception e){ 
      return false; 
     } 
     return true; 
    } 
    public boolean getClient(int id, int timeout){ 
     close(id); 
     try{ 
      ss.setSoTimeout(timeout); 
      Socket socket = ss.accept(); 
      s.put(id, socket); 
      in.put(id, new BufferedReader(new InputStreamReader(socket.getInputStream()))); 
      out.put(id, new PrintWriter(socket.getOutputStream(), true)); 
      return true; 
     }catch (Exception e){ 
      return false; 
     }finally{ 
      try{ss.setSoTimeout(0);}catch(SocketException e){} 
     } 
    } 
    public synchronized String getResponse(int id, String command){ 
     try{ 
      send(id, command); 
      String response = in.get(id).readLine(); 
      return response; 
     }catch(Exception e){ 
      close(id); 
      return null; 
     } 
    } 
    public synchronized void send(int id, String message){ 
     try{ 
      out.get(id).println(message); 
     }catch(Exception e){} 
    } 
    public void broadcast(String message){ 
     for(Entry<Integer, PrintWriter> writer: out.entrySet()) 
      send(writer.getKey(), message); 
    } 
    public synchronized boolean isAlive(int id){ 
     try{ 
      if(getResponse(id, "alive").equals("OK")) 
       return true; 
      else 
       return false; 
     }catch(Exception e){ 
      close(id); 
      return false; 
     } 
    } 
    public synchronized void close(int id){ 
     try{in.remove(id);}catch(Exception e){} 
     try{out.remove(id);}catch(Exception e){} 
     try{s.remove(id).close();}catch(Exception e){} 
    } 
    public void close(){ 
     try{ss.close();}catch (Exception e){} 
     for(Map.Entry<Integer, Socket> client : s.entrySet()){ 
      close(client.getKey()); 
     } 
    } 
} 

問題就來了要調用close()方法,並已經有另一個線程上GETRESPONSE時()在ReadLine()部分

有什麼辦法強制getResponse或bufferedReader.ReadLine()拋出一個異常或某種方式來使它停止,釋放資源什麼的?

回答

1

我會創建一個處理程序實例,它包含您的套接字,輸入,輸出併爲每個處理程序運行一個讀線程。

這將取代和簡化這裏的大部分共享代碼。