使用synchronized方法锁定时释放BufferedReader.readLine()

时间:2013-05-06 17:24:05

标签: java bufferedreader 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()方法时出现

问题,并且ReadLine()部分的getResponse()上已经存在另一个线程

有没有办法强制getResponse或bufferedReader.ReadLine()抛出异常或某种方式使其停止,释放资源或什么?

1 个答案:

答案 0 :(得分:1)

我将创建一个Handler实例,它保存您的套接字,输入,输出并为每个处理程序运行一个读取线程。

这将取代并简化大部分共享代码。