現在、次のようなコードがあります。
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() に強制的に例外をスローさせる方法、または停止させたり、リソースを解放したりする方法はありますか?