反射使用不当
错误的写法:
Java代码
  1. Class beanClass = ...   
  2. if (beanClass.newInstance() instanceof TestBean) ...  
Class beanClass = ...
if (beanClass.newInstance() instanceof TestBean) ...

这里的本意是检查beanClass是否是TestBean或是其子类, 但是创建一个类实例可能没那么简单, 首先实例化一个对象会带来一定的消耗, 另外有可能类没有定义默认构造函数. 正确的做法是用Class.isAssignableFrom(Class) 方法.
icon_idea.gif 正确的写法:
Java代码
  1. Class beanClass = ...   
  2. if (TestBean.class.isAssignableFrom(beanClass)) ...  
Class beanClass = ...
if (TestBean.class.isAssignableFrom(beanClass)) ...

不必要的同步
错误的写法:
Java代码
  1. Collection l = new Vector();   
  2. for (...) {   
  3.    l.add(object);   
  4. }  
Collection l = new Vector();
for (...) {
   l.add(object);
}

Vector是ArrayList同步版本.
icon_idea.gif 正确的写法:
Java代码
  1. Collection l = new ArrayList();   
  2. for (...) {   
  3.    l.add(object);   
  4. }  
Collection l = new ArrayList();
for (...) {
   l.add(object);
}

错误的选择List类型
根据下面的表格数据来进行选择
ArrayList LinkedList
add (append) O(1) or ~O(log(n)) if growing O(1)
insert (middle)O(n) or ~O(n*log(n)) if growing O(n)
remove (middle)O(n) (always performs complete copy) O(n)
iterate O(n) O(n)
get by index O(1) O(n)

HashMap size陷阱
错误的写法:
Java代码
  1. Map map = new HashMap(collection.size());   
  2. for (Object o : collection) {   
  3.   map.put(o.key, o.value);   
  4. }  
Map map = new HashMap(collection.size());
for (Object o : collection) {
  map.put(o.key, o.value);
}

这里可以参考guava的Maps.newHashMapWithExpectedSize的实现. 用户的本意是希望给HashMap设置初始值, 避免扩容(resize)的开销. 但是没有考虑当添加的元素数量达到HashMap容量的75%时将出现resize.
icon_idea.gif 正确的写法:
Java代码
  1. Map map = new HashMap(1 + (int) (collection.size() / 0.75));  
Map map = new HashMap(1 + (int) (collection.size() / 0.75));

对Hashtable, HashMap 和 HashSet了解不够
这里主要需要了解HashMap和Hashtable的内部实现上, 它们都使用Entry包装来封装key/value, Entry内部除了要保存Key/Value的引用, 还需要保存hash桶中next Entry的应用, 因此对内存会有不小的开销, 而HashSet内部实现其实就是一个HashMap. 有时候IdentityHashMap可以作为一个不错的替代方案. 它在内存使用上更有效(没有用Entry封装, 内部采用Object[]). 不过需要小心使用. 它的实现违背了Map接口的定义. 有时候也可以用ArrayList来替换HashSet.
这一切的根源都是由于JDK内部没有提供一套高效的Map和Set实现.
对List的误用
建议下列场景用Array来替代List:
  • list长度固定, 比如一周中的每一天
  • 对list频繁的遍历, 比如超过1w次
  • 需要对数字进行包装(主要JDK没有提供基本类型的List)

比如下面的代码.
错误的写法:
Java代码
  1. List<Integer> codes = new ArrayList<Integer>();   
  2. codes.add(Integer.valueOf(10));   
  3. codes.add(Integer.valueOf(20));   
  4. codes.add(Integer.valueOf(30));   
  5. codes.add(Integer.valueOf(40));  
List<Integer> codes = new ArrayList<Integer>();
codes.add(Integer.valueOf(10));
codes.add(Integer.valueOf(20));
codes.add(Integer.valueOf(30));
codes.add(Integer.valueOf(40));

icon_idea.gif 正确的写法:
Java代码
  1. int[] codes = { 10203040 };  
int[] codes = { 10, 20, 30, 40 };

 错误的写法:
Java代码
  1. // horribly slow and a memory waster if l has a few thousand elements (try it yourself!)   
  2. List<Mergeable> l = ...;   
  3. for (int i=0; i < l.size()-1; i++) {   
  4.     Mergeable one = l.get(i);   
  5.     Iterator<Mergeable> j = l.iterator(i+1); // memory allocation!   
  6.     while (j.hasNext()) {   
  7.         Mergeable other = l.next();   
  8.         if (one.canMergeWith(other)) {   
  9.             one.merge(other);   
  10.             other.remove();   
  11.         }   
  12.     }   
  13. }  
// horribly slow and a memory waster if l has a few thousand elements (try it yourself!)
List<Mergeable> l = ...;
for (int i=0; i < l.size()-1; i++) {
    Mergeable one = l.get(i);
    Iterator<Mergeable> j = l.iterator(i+1); // memory allocation!
    while (j.hasNext()) {
        Mergeable other = l.next();
        if (one.canMergeWith(other)) {
            one.merge(other);
            other.remove();
        }
    }
}

icon_idea.gif 正确的写法:
Java代码
  1. // quite fast and no memory allocation   
  2. Mergeable[] l = ...;   
  3. for (int i=0; i < l.length-1; i++) {   
  4.     Mergeable one = l[i];   
  5.     for (int j=i+1; j < l.length; j++) {   
  6.         Mergeable other = l[j];   
  7.         if (one.canMergeWith(other)) {   
  8.             one.merge(other);   
  9.             l[j] = null;   
  10.         }   
  11.     }   
  12. }  
// quite fast and no memory allocation
Mergeable[] l = ...;
for (int i=0; i < l.length-1; i++) {
    Mergeable one = l[i];
    for (int j=i+1; j < l.length; j++) {
        Mergeable other = l[j];
        if (one.canMergeWith(other)) {
            one.merge(other);
            l[j] = null;
        }
    }
}

实际上Sun也意识到这一点, 因此在JDK中, Collections.sort()就是将一个List拷贝到一个数组中然后调用Arrays.sort方法来执行排序.
用数组来描述一个结构
错误用法:
Java代码
  1. /**  
  2.  * @returns [1]: Location, [2]: Customer, [3]: Incident  
  3.  */  
  4. Object[] getDetails(int id) {...  
/**
 * @returns [1]: Location, [2]: Customer, [3]: Incident
 */
Object[] getDetails(int id) {...

这里用数组+文档的方式来描述一个方法的返回值. 虽然很简单, 但是很容易误用, 正确的做法应该是定义个类.
icon_idea.gif 正确的写法:
Java代码
  1. Details getDetails(int id) {...}   
  2. private class Details {   
  3.     public Location location;   
  4.     public Customer customer;   
  5.     public Incident incident;   
  6. }  
Details getDetails(int id) {...}
private class Details {
    public Location location;
    public Customer customer;
    public Incident incident;
}

对方法过度限制
错误用法:
Java代码
  1. public void notify(Person p) {   
  2.     ...   
  3.     sendMail(p.getName(), p.getFirstName(), p.getEmail());   
  4.     ...   
  5. }   
  6. class PhoneBook {   
  7.     String lookup(String employeeId) {   
  8.         Employee emp = ...   
  9.         return emp.getPhone();   
  10.     }   
  11. }  
public void notify(Person p) {
    ...
    sendMail(p.getName(), p.getFirstName(), p.getEmail());
    ...
}
class PhoneBook {
    String lookup(String employeeId) {
        Employee emp = ...
        return emp.getPhone();
    }
}

第一个例子是对方法参数做了过多的限制, 第二个例子对方法的返回值做了太多的限制.
icon_idea.gif 正确的写法:
Java代码
  1. public void notify(Person p) {   
  2.     ...   
  3.     sendMail(p);   
  4.     ...   
  5. }   
  6. class EmployeeDirectory {   
  7.     Employee lookup(String employeeId) {   
  8.         Employee emp = ...   
  9.         return emp;   
  10.     }   
  11. }  
public void notify(Person p) {
    ...
    sendMail(p);
    ...
}
class EmployeeDirectory {
    Employee lookup(String employeeId) {
        Employee emp = ...
        return emp;
    }
}

对POJO的setter方法画蛇添足
错误的写法:
Java代码
  1. private String name;   
  2. public void setName(String name) {   
  3.     this.name = name.trim();   
  4. }   
  5. public void String getName() {   
  6.     return this.name;   
  7. }  
private String name;
public void setName(String name) {
    this.name = name.trim();
}
public void String getName() {
    return this.name;
}

有时候我们很讨厌字符串首尾出现空格, 所以在setter方法中进行了trim处理, 但是这样做的结果带来的副作用会使getter方法的返回值和setter方法不一致, 如果只是将JavaBean当做一个数据容器, 那么最好不要包含任何业务逻辑. 而将业务逻辑放到专门的业务层或者控制层中处理.
正确的做法:
Java代码
  1. person.setName(textInput.getText().trim());  
person.setName(textInput.getText().trim());

日历对象(Calendar)误用
错误的写法:
Java代码
  1. Calendar cal = new GregorianCalender(TimeZone.getTimeZone("Europe/Zurich"));   
  2. cal.setTime(date);   
  3. cal.add(Calendar.HOUR_OF_DAY, 8);   
  4. date = cal.getTime();  
Calendar cal = new GregorianCalender(TimeZone.getTimeZone("Europe/Zurich"));
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 8);
date = cal.getTime();

这里主要是对date, time, calendar和time zone不了解导致. 而在一个时间上增加8小时, 跟time zone没有任何关系, 所以没有必要使用Calendar, 直接用Date对象即可, 而如果是增加天数的话, 则需要使用Calendar, 因为采用不同的时令制可能一天的小时数是不同的(比如有些DST是23或者25个小时)
icon_idea.gif 正确的写法:
Java代码
  1. date = new Date(date.getTime() + 8L * 3600L * 1000L); // add 8 hrs  
date = new Date(date.getTime() + 8L * 3600L * 1000L); // add 8 hrs

TimeZone的误用
错误的写法:
Java代码
  1. Calendar cal = new GregorianCalendar();   
  2. cal.setTime(date);   
  3. cal.set(Calendar.HOUR_OF_DAY, 0);   
  4. cal.set(Calendar.MINUTE, 0);   
  5. cal.set(Calendar.SECOND, 0);   
  6. Date startOfDay = cal.getTime();  
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date startOfDay = cal.getTime();

这里有两个错误, 一个是没有没有将毫秒归零, 不过最大的错误是没有指定TimeZone, 不过一般的桌面应用没有问题, 但是如果是服务器端应用则会有一些问题, 比如同一时刻在上海和伦敦就不一样, 因此需要指定的TimeZone.
icon_idea.gif 正确的写法:
Java代码
  1. Calendar cal = new GregorianCalendar(user.getTimeZone());   
  2. cal.setTime(date);   
  3. cal.set(Calendar.HOUR_OF_DAY, 0);   
  4. cal.set(Calendar.MINUTE, 0);   
  5. cal.set(Calendar.SECOND, 0);   
  6. cal.set(Calendar.MILLISECOND, 0);   
  7. Date startOfDay = cal.getTime();  
Calendar cal = new GregorianCalendar(user.getTimeZone());
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date startOfDay = cal.getTime();

时区(Time Zone)调整的误用
错误的写法:
Java代码
  1. public static Date convertTz(Date date, TimeZone tz) {   
  2.   Calendar cal = Calendar.getInstance();   
  3.   cal.setTimeZone(TimeZone.getTimeZone("UTC"));   
  4.   cal.setTime(date);   
  5.   cal.setTimeZone(tz);   
  6.   return cal.getTime();   
  7. }  
public static Date convertTz(Date date, TimeZone tz) {
  Calendar cal = Calendar.getInstance();
  cal.setTimeZone(TimeZone.getTimeZone("UTC"));
  cal.setTime(date);
  cal.setTimeZone(tz);
  return cal.getTime();
}

这个方法实际上没有改变时间, 输入和输出是一样的. 关于时间的问题可以参考这篇文章: http://www.odi.ch/prog/design/datetime.php 这里主要的问题是Date对象并不包含Time Zone信息. 它总是使用UTC(世界统一时间). 而调用Calendar的getTime/setTime方法会自动在当前时区和UTC之间做转换.
Calendar.getInstance()的误用
错误的写法:
Java代码
  1. Calendar c = Calendar.getInstance();   
  2. c.set(2009, Calendar.JANUARY, 15);  
Calendar c = Calendar.getInstance();
c.set(2009, Calendar.JANUARY, 15);

Calendar.getInstance()依赖local来选择一个Calendar实现, 不同实现的2009年是不同的, 比如有些Calendar实现就没有January月份.
icon_idea.gif 正确的写法:
Java代码
  1. Calendar c = new GregorianCalendar(timeZone);   
  2. c.set(2009, Calendar.JANUARY, 15);  
Calendar c = new GregorianCalendar(timeZone);
c.set(2009, Calendar.JANUARY, 15);

Date.setTime()的误用
错误的写法:
Java代码
  1. account.changePassword(oldPass, newPass);   
  2. Date lastmod = account.getLastModified();   
  3. lastmod.setTime(System.currentTimeMillis());  
account.changePassword(oldPass, newPass);
Date lastmod = account.getLastModified();
lastmod.setTime(System.currentTimeMillis());

在更新密码之后, 修改一下最后更新时间, 这里的用法没有错,但是有更好的做法: 直接传Date对象. 因为Date是Value Object, 不可变的. 如果更新了Date的值, 实际上是生成一个新的Date实例. 这样其他地方用到的实际上不在是原来的对象, 这样可能出现不可预知的异常. 当然这里又涉及到另外一个OO设计的问题, 对外暴露Date实例本身就是不好的做法(一般的做法是在setter方法中设置Date引用参数的clone对象). 另外一种比较好的做法就是直接保存long类型的毫秒数.
正确的做法:
Java代码
  1. account.changePassword(oldPass, newPass);   
  2. account.setLastModified(new Date());  
account.changePassword(oldPass, newPass);
account.setLastModified(new Date());

SimpleDateFormat非线程安全误用
错误的写法:
Java代码 复制代码
  1. public class Constants {   
  2.     public static final SimpleDateFormat date = new SimpleDateFormat("dd.MM.yyyy");   
  3. }  
public class Constants {
    public static final SimpleDateFormat date = new SimpleDateFormat("dd.MM.yyyy");
}

SimpleDateFormat不是线程安全的. 在多线程并行处理的情况下, 会得到非预期的值. 这个错误非常普遍! 如果真要在多线程环境下公用同一个SimpleDateFormat, 那么做好做好同步(cache flush, lock contention), 但是这样会搞得更复杂, 还不如直接new一个实在.
使用全局参数配置常量类/接口
Java代码
  1. public interface Constants {   
  2.     String version = "1.0";   
  3.     String dateFormat = "dd.MM.yyyy";   
  4.     String configFile = ".apprc";   
  5.     int maxNameLength = 32;   
  6.     String someQuery = "SELECT * FROM ...";   
  7. }  
public interface Constants {
    String version = "1.0";
    String dateFormat = "dd.MM.yyyy";
    String configFile = ".apprc";
    int maxNameLength = 32;
    String someQuery = "SELECT * FROM ...";
}

很多应用都会定义这样一个全局常量类或接口, 但是为什么这种做法不推荐? 因为这些常量之间基本没有任何关联, 只是因为公用才定义在一起. 但是如果其他组件需要使用这些全局变量, 则必须对该常量类产生依赖, 特别是存在server和远程client调用的场景.
比较好的做法是将这些常量定义在组件内部. 或者局限在一个类库内部.
忽略造型溢出(cast overflow)
错误的写法:
Java代码
  1. public int getFileSize(File f) {   
  2.   long l = f.length();   
  3.   return (int) l;   
  4. }  
public int getFileSize(File f) {
  long l = f.length();
  return (int) l;
}

这个方法的本意是不支持传递超过2GB的文件. 最好的做法是对长度进行检查, 溢出时抛出异常.
icon_idea.gif 正确的写法:
Java代码
  1. public int getFileSize(File f) {   
  2.   long l = f.length();   
  3.   if (l > Integer.MAX_VALUE) throw new IllegalStateException("int overflow");   
  4.   return (int) l;   
  5. }  
public int getFileSize(File f) {
  long l = f.length();
  if (l > Integer.MAX_VALUE) throw new IllegalStateException("int overflow");
  return (int) l;
}

另一个溢出bug是cast的对象不对, 比如下面第一个println. 正确的应该是下面的那个.
Java代码
  1. long a = System.currentTimeMillis();   
  2. long b = a + 100;   
  3. System.out.println((int) b-a);   
  4. System.out.println((int) (b-a));  
long a = System.currentTimeMillis();
long b = a + 100;
System.out.println((int) b-a);
System.out.println((int) (b-a));

对float和double使用==操作
错误的写法:
Java代码
  1. for (float f = 10f; f!=0; f-=0.1) {   
  2.   System.out.println(f);   
  3. }  
for (float f = 10f; f!=0; f-=0.1) {
  System.out.println(f);
}

上面的浮点数递减只会无限接近0而不会等于0, 这样会导致上面的for进入死循环. 通常绝不要对float和double使用==操作. 而采用大于和小于操作. 如果java编译器能针对这种情况给出警告. 或者在java语言规范中不支持浮点数类型的==操作就最好了.
icon_idea.gif 正确的写法:
Java代码
  1. for (float f = 10f; f>0; f-=0.1) {   
  2.   System.out.println(f);   
  3. }  
for (float f = 10f; f>0; f-=0.1) {
  System.out.println(f);
}

用浮点数来保存money
错误的写法:
Java代码
  1. float total = 0.0f;   
  2. for (OrderLine line : lines) {   
  3.   total += line.price * line.count;   
  4. }   
  5. double a = 1.14 * 75// 85.5 将表示为 85.4999...   
  6. System.out.println(Math.round(a)); // 输出值为85   
  7. BigDecimal d = new BigDecimal(1.14); //造成精度丢失  
float total = 0.0f;
for (OrderLine line : lines) {
  total += line.price * line.count;
}
double a = 1.14 * 75; // 85.5 将表示为 85.4999...
System.out.println(Math.round(a)); // 输出值为85
BigDecimal d = new BigDecimal(1.14); //造成精度丢失

这个也是一个老生常谈的错误. 比如计算100笔订单, 每笔0.3元, 最终的计算结果是29.9999971. 如果将float类型改为double类型, 得到的结果将是30.000001192092896. 出现这种情况的原因是, 人类和计算的计数方式不同. 人类采用的是十进制, 而计算机是二进制.二进制对于计算机来说非常好使, 但是对于涉及到精确计算的场景就会带来误差. 比如银行金融中的应用.
因此绝不要用浮点类型来保存money数据. 采用浮点数得到的计算结果是不精确的. 即使与int类型做乘法运算也会产生一个不精确的结果.那是因为在用二进制存储一个浮点数时已经出现了精度丢失. 最好的做法就是用一个string或者固定点数来表示. 为了精确, 这种表示方式需要指定相应的精度值.
BigDecimal就满足了上面所说的需求. 如果在计算的过程中精度的丢失超出了给定的范围, 将抛出runtime exception.
icon_idea.gif 正确的写法:
Java代码
  1. BigDecimal total = BigDecimal.ZERO;   
  2. for (OrderLine line : lines) {   
  3.   BigDecimal price = new BigDecimal(line.price);   
  4.   BigDecimal count = new BigDecimal(line.count);   
  5.   total = total.add(price.multiply(count)); // BigDecimal is immutable!   
  6. }   
  7. total = total.setScale(2, RoundingMode.HALF_UP);   
  8. BigDecimal a = (new BigDecimal("1.14")).multiply(new BigDecimal(75)); // 85.5 exact   
  9. a = a.setScale(0, RoundingMode.HALF_UP); // 86   
  10. System.out.println(a); // correct output: 86   
  11. BigDecimal a = new BigDecimal("1.14");  
BigDecimal total = BigDecimal.ZERO;
for (OrderLine line : lines) {
  BigDecimal price = new BigDecimal(line.price);
  BigDecimal count = new BigDecimal(line.count);
  total = total.add(price.multiply(count)); // BigDecimal is immutable!
}
total = total.setScale(2, RoundingMode.HALF_UP);
BigDecimal a = (new BigDecimal("1.14")).multiply(new BigDecimal(75)); // 85.5 exact
a = a.setScale(0, RoundingMode.HALF_UP); // 86
System.out.println(a); // correct output: 86
BigDecimal a = new BigDecimal("1.14");

不使用finally块释放资源
错误的写法:
Java代码
  1. public void save(File f) throws IOException {   
  2.   OutputStream out = new BufferedOutputStream(new FileOutputStream(f));   
  3.   out.write(...);   
  4.   out.close();   
  5. }   
  6. public void load(File f) throws IOException {   
  7.   InputStream in = new BufferedInputStream(new FileInputStream(f));   
  8.   in.read(...);   
  9.   in.close();   
  10. }  
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将帮助我们做清理.
Java代码
  1. // code for your cookbook   
  2. public void save() throws IOException {   
  3.   File f = ...   
  4.   OutputStream out = new BufferedOutputStream(new FileOutputStream(f));   
  5.   try {   
  6.     out.write(...);   
  7.     out.flush(); // don't lose exception by implicit flush on close   
  8.   } finally {   
  9.     out.close();   
  10.   }   
  11. }   
  12. public void load(File f) throws IOException {   
  13.   InputStream in = new BufferedInputStream(new FileInputStream(f));   
  14.   try {   
  15.     in.read(...);   
  16.   } finally {   
  17.     try { in.close(); } catch (IOException e) { }   
  18.   }   
  19. }  
// 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) { }
  }
}

数据库访问也涉及到类似的情况:
Java代码
  1. Car getCar(DataSource ds, String plate) throws SQLException {   
  2.   Car car = null;   
  3.   Connection c = null;   
  4.   PreparedStatement s = null;   
  5.   ResultSet rs = null;   
  6.   try {   
  7.     c = ds.getConnection();   
  8.     s = c.prepareStatement("select make, color from cars where plate=?");   
  9.     s.setString(1, plate);   
  10.     rs = s.executeQuery();   
  11.     if (rs.next()) {   
  12.        car = new Car();   
  13.        car.make = rs.getString(1);   
  14.        car.color = rs.getString(2);   
  15.     }   
  16.   } finally {   
  17.     if (rs != nulltry { rs.close(); } catch (SQLException e) { }   
  18.     if (s != nulltry { s.close(); } catch (SQLException e) { }   
  19.     if (c != nulltry { c.close(); } catch (SQLException e) { }   
  20.   }   
  21.   return car;   
  22. }  
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方法误用
错误的写法:
Java代码
  1. public class FileBackedCache {   
  2.    private File backingStore;   
  3.       
  4.    ...   
  5.       
  6.    protected void finalize() throws IOException {   
  7.       if (backingStore != null) {   
  8.         backingStore.close();   
  9.         backingStore = null;   
  10.       }   
  11.    }   
  12. }  
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方法, 然后由外部的容器来负责调用释放资源.
Java代码
  1. public class FileBackedCache {   
  2.    private File backingStore;   
  3.       
  4.    ...   
  5.       
  6.    public void close() throws IOException {   
  7.       if (backingStore != null) {   
  8.         backingStore.close();   
  9.         backingStore = null;   
  10.       }   
  11.    }   
  12. }  
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方法.
Java代码
  1. try (Writer w = new FileWriter(f)) { // implements Closable   
  2.   w.write("abc");   
  3.   // w goes out of scope here: w.close() is called automatically in ANY case   
  4. catch (IOException e) {   
  5.   throw new RuntimeException(e.getMessage(), e);   
  6. }  
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方法误用
错误的写法:
Java代码
  1. try {   
  2.         Thread.sleep(1000);   
  3. catch (InterruptedException e) {   
  4.         // ok   
  5. }   
  6. or    
  7. while (true) {   
  8.         if (Thread.interrupted()) break;   
  9. }  
try {
        Thread.sleep(1000);
} catch (InterruptedException e) {
        // ok
}
or 
while (true) {
        if (Thread.interrupted()) break;
}

这里主要是interrupted静态方法除了返回当前线程的中断状态, 还会将当前线程状态复位.
icon_idea.gif 正确的写法:
Java代码
  1. try {   
  2.         Thread.sleep(1000);   
  3. catch (InterruptedException e) {   
  4.         Thread.currentThread().interrupt();   
  5. }   
  6. or    
  7. while (true) {   
  8.         if (Thread.currentThread().isInterrupted()) break;   
  9. }  
try {
        Thread.sleep(1000);
} catch (InterruptedException e) {
        Thread.currentThread().interrupt();
}
or 
while (true) {
        if (Thread.currentThread().isInterrupted()) break;
}

在静态变量初始化时创建线程
错误的写法:
Java代码
  1. class Cache {   
  2.         private static final Timer evictor = new Timer();   
  3. }  
class Cache {
        private static final Timer evictor = new Timer();
}

Timer构造器内部会new一个thread, 而该thread会从它的父线程(即当前线程)中继承各种属性. 比如context classloader, threadlocal以及其他的安全属性(访问权限).  而加载当前类的线程可能是不确定的, 比如一个线程池中随机的一个线程. 如果你需要控制线程的属性, 最好的做法就是将其初始化操作放在一个静态方法中, 这样初始化将由它的调用者来决定.
正确的做法:
Java代码
  1. class Cache {   
  2.     private static Timer evictor;   
  3.         public static setupEvictor() {   
  4.                 evictor = new Timer();   
  5.         }   
  6. }  
class Cache {
    private static Timer evictor;
        public static setupEvictor() {
                evictor = new Timer();
        }
}

已取消的定时器任务依然持有状态
错误的写法:
Java代码
  1. final MyClass callback = this;   
  2. TimerTask task = new TimerTask() {   
  3.         public void run() {   
  4.                 callback.timeout();   
  5.         }   
  6. };   
  7. timer.schedule(task, 300000L);   
  8. try {   
  9.         doSomething();   
  10. finally {   
  11.         task.cancel();   
  12. }  
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分钟后被回收.
icon_idea.gif 正确的写法:
Java代码
  1. TimerTask task = new Job(this);   
  2. timer.schedule(task, 300000L);   
  3. try {   
  4.         doSomething();   
  5. finally {   
  6.         task.cancel();   
  7. }   
  8.   
  9. static class Job extends TimerTask {   
  10.         private MyClass callback;   
  11.         public Job(MyClass callback) {   
  12.                 this.callback = callback;   
  13.         }   
  14.         public boolean cancel() {   
  15.                 callback = null;   
  16.                 return super.cancel();   
  17.         }   
  18.         public void run() {   
  19.                 if (callback == nullreturn;   
  20.                 callback.timeout();   
  21.         }   
  22. }