不使用finally块释放资源
public void save(File f) throws IOException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
out.write(...);
out.close();
}
public void load(File f) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(f));
in.read(...);
in.close();
}
上面的代码打开一个文件输出流, 操作系统为其分配一个文件句柄, 但是文件句柄是一种非常稀缺的资源, 必须通过调用相应的close方法来被正确的释放回收. 而为了保证在异常情况下资源依然能被正确回收, 必须将其放在finally block中. 上面的代码中使用了BufferedInputStream将file stream包装成了一个buffer stream, 这样将导致在调用close方法时才会将buffer stream写入磁盘. 如果在close的时候失败, 将导致写入数据不完全. 而对于FileInputStream在finally block的close操作这里将直接忽略.
如果BufferedOutputStream.close()方法执行顺利则万事大吉, 如果失败这里有一个潜在的bug(http://bugs.sun.com/view_bug.do?bug_id=6335274): 在close方法内部调用flush操作的时候, 如果出现异常, 将直接忽略. 因此为了尽量减少数据丢失, 在执行close之前显式的调用flush操作.
下面的代码有一个小小的瑕疵: 如果分配file stream成功, 但是分配buffer stream失败(OOM这种场景), 将导致文件句柄未被正确释放. 不过这种情况一般不用担心, 因为JVM的gc将帮助我们做清理.
// code for your cookbook
public void save() throws IOException {
File f = ...
OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
try {
out.write(...);
out.flush(); // don't lose exception by implicit flush on close
} finally {
out.close();
}
}
public void load(File f) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(f));
try {
in.read(...);
} finally {
try { in.close(); } catch (IOException e) { }
}
}
数据库访问也涉及到类似的情况:
Car getCar(DataSource ds, String plate) throws SQLException {
Car car = null;
Connection c = null;
PreparedStatement s = null;
ResultSet rs = null;
try {
c = ds.getConnection();
s = c.prepareStatement("select make, color from cars where plate=?");
s.setString(1, plate);
rs = s.executeQuery();
if (rs.next()) {
car = new Car();
car.make = rs.getString(1);
car.color = rs.getString(2);
}
} finally {
if (rs != null) try { rs.close(); } catch (SQLException e) { }
if (s != null) try { s.close(); } catch (SQLException e) { }
if (c != null) try { c.close(); } catch (SQLException e) { }
}
return car;
}
finalize方法误用
public class FileBackedCache {
private File backingStore;
...
protected void finalize() throws IOException {
if (backingStore != null) {
backingStore.close();
backingStore = null;
}
}
}
这个问题Effective Java这本书有详细的说明. 主要是finalize方法依赖于GC的调用, 其调用时机可能是立马也可能是几天以后, 所以是不可预知的. 而JDK的API文档中对这一点有误导: 建议在该方法中来释放I/O资源.
正确的做法是定义一个close方法, 然后由外部的容器来负责调用释放资源.
public class FileBackedCache {
private File backingStore;
...
public void close() throws IOException {
if (backingStore != null) {
backingStore.close();
backingStore = null;
}
}
}
在JDK 1.7 (Java 7)中已经引入了一个AutoClosable接口. 当变量(不是对象)超出了try-catch的资源使用范围, 将自动调用close方法.
try (Writer w = new FileWriter(f)) { // implements Closable
w.write("abc");
// w goes out of scope here: w.close() is called automatically in ANY case
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
Thread.interrupted方法误用
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ok
}
or
while (true) {
if (Thread.interrupted()) break;
}
这里主要是interrupted静态方法除了返回当前线程的中断状态, 还会将当前线程状态复位.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
or
while (true) {
if (Thread.currentThread().isInterrupted()) break;
}
在静态变量初始化时创建线程
class Cache {
private static final Timer evictor = new Timer();
}
Timer构造器内部会new一个thread, 而该thread会从它的父线程(即当前线程)中继承各种属性. 比如context classloader, threadlocal以及其他的安全属性(访问权限). 而加载当前类的线程可能是不确定的, 比如一个线程池中随机的一个线程. 如果你需要控制线程的属性, 最好的做法就是将其初始化操作放在一个静态方法中, 这样初始化将由它的调用者来决定.
class Cache {
private static Timer evictor;
public static setupEvictor() {
evictor = new Timer();
}
}
已取消的定时器任务依然持有状态
final MyClass callback = this;
TimerTask task = new TimerTask() {
public void run() {
callback.timeout();
}
};
timer.schedule(task, 300000L);
try {
doSomething();
} finally {
task.cancel();
}
上面的task内部包含一个对外部类实例的应用, 这将导致该引用可能不会被GC立即回收. 因为Timer将保留TimerTask在指定的时间之后才被释放. 因此task对应的外部类实例将在5分钟后被回收.
TimerTask task = new Job(this);
timer.schedule(task, 300000L);
try {
doSomething();
} finally {
task.cancel();
}
static class Job extends TimerTask {
private MyClass callback;
public Job(MyClass callback) {
this.callback = callback;
}
public boolean cancel() {
callback = null;
return super.cancel();
}
public void run() {
if (callback == null) return;
callback.timeout();
}
}