1、在A类中申请资源后一定要释放掉,或者提供释放的方法或接口。最好在同一个方法中释放。绝对不可将申请的资源提供给其他类,让别人来释放。
2、在操作socket等时,一定要使用finally关闭资源,否则会造成内存泄漏,关闭socket流的正确做法,要保证所有流都可以正确的关闭
//在操作socket等时,一定要使用finally关闭资源,否则会造成内存泄漏,关闭socket流的正确做法,要保证所有流都可以正确的关闭
Socket socket=null;
DataInputStream dataInputStream=null;
DataOutputStream dataOutputStream=null;
try {
socket=new Socket("127.0.0.1", 80);
dataInputStream=new DataInputStream(socket.getInputStream());
dataOutputStream=new DataOutputStream(socket.getOutputStream());
dataInputStream.close();
dataOutputStream.close();
socket.close();
} catch (Exception e) {
//
e.printStackTrace();
}finally{
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
dataOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3、
//防止反编译用
if (654789 == new Random().nextInt()){
throw new Exception("try again 654789 == new Random().nextInt()");
}