程序不应依赖于虚拟机的finalize()方法来自动回收Socket资源,而需要手动在finally代码块中做Socket资源的释放操作。
例如:下面代码片段中,使用完之前创建的socket套接字资源后,在finally代码块中进行了释放。
public void getSocket(String host,int port){Socket socket = null;try {socket = new Socket(host,port);BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));while(reader.readLine()!=null){...}} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(socket!=null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}
