Java编程常见问题汇总
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java编程常见问题汇总相关的知识,希望对你有一定的参考价值。
学习Java的同学注意了!!!
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群:618528494 我们一起学Java!
每天在写Java程序,其实里面有一些细节大家可能没怎么注意,这不,有人总结了一个我们编程中常见的问题。虽然一般没有什么大问题,但是最好别这样做。另外这里提到的很多问题其实可以通过Findbugs( http://findbugs.sourceforge.net/ )来帮我们进行检查出来。
字符串连接误用
错误的写法:
<span class = "hljs-built_in" >String s = <span class = "hljs-string" > "" ; <span class = "hljs-keyword" > for (Person p : persons) { s += <span class = "hljs-string" > ", " + p.getName(); } s = s.substring(<span class = "hljs-number" > 2 ); <span class = "hljs-comment" > //remove first comma</span></span></span></span></span></span> |
正确的写法:
StringBuilder sb = new StringBuilder(persons.size() * 16); // well estimated buffer for (Person p : persons) { if (sb.length() > 0) sb.append(", "); sb.append(p.getName); }
错误的使用StringBuffer
错误的写法:
StringBuffer sb = <span class = "hljs-keyword" > new StringBuffer(); sb.append(<span class = "hljs-string" > "Name: " ); sb.append(name + <span class = "hljs-string" > ‘\n‘ ); sb.append(<span class = "hljs-string" > "!" ); ... String s = sb.toString();</span></span></span></span> |
问题在第三行,append char比String性能要好,另外就是初始化StringBuffer没有指定size,导致中间append时可能重新调整内部数组大小。如果是JDK1.5最好用StringBuilder取代StringBuffer,除非有线程安全的要求。还有一种方式就是可以直接连接字符串。缺点就是无法初始化时指定长度。
正确的写法:
StringBuilder sb = <span class = "hljs-keyword" > new StringBuilder(<span class = "hljs-number" > 100 ); sb.append(<span class = "hljs-string" > "Name: " ); sb.append(name); sb.append(<span class = "hljs-string" > "\n!" ); <span class = "hljs-built_in" >String s = sb.toString();</span></span></span></span></span> |
或者这样写:
<span class = "hljs-built_in" >String s = <span class = "hljs-string" > "Name: " + name + <span class = "hljs-string" > "\n!" ;</span></span></span> |
测试字符串相等性
错误的写法:
<span class = "hljs-keyword" > if (name.compareTo(<span class = "hljs-string" > "John" ) == <span class = "hljs-number" > 0 ) ... <span class = "hljs-keyword" > if (name == <span class = "hljs-string" > "John" ) ... <span class = "hljs-keyword" > if (name.equals(<span class = "hljs-string" > "John" )) ... <span class = "hljs-keyword" > if (<span class = "hljs-string" > "" .equals(name)) ...</span></span></span></span></span></span></span></span></span> |
上面的代码没有错,但是不够好。compareTo不够简洁,==原义是比较两个对象是否一样。另外比较字符是否为空,最好判断它的长度。
正确的写法:
<span class = "hljs-keyword" > if (<span class = "hljs-string" > "John" .equals(name)) ... <span class = "hljs-keyword" > if (name.length() == <span class = "hljs-number" > 0 ) ... <span class = "hljs-keyword" > if (name.isEmpty()) ...</span></span></span></span></span> |
数字转换成字符串
错误的写法:
<span class = "hljs-string" > "" + <span class = "hljs-keyword" >set.size() new <span class = "hljs-type" >Integer(<span class = "hljs-keyword" >set.size()).<span class = "hljs-built_in" >toString()</span></span></span></span></span> |
正确的写法:
<span class = "hljs-selector-tag" >String<span class = "hljs-selector-class" >.valueOf(<span class = "hljs-selector-tag" >set<span class = "hljs-selector-class" >.size())</span></span></span></span> |
利用不可变对象(Immutable)
错误的写法:
zero = <span class = "hljs-keyword" > new Integer(<span class = "hljs-number" > 0 ); <span class = "hljs-keyword" > return <span class = "hljs-built_in" >Boolean.valueOf(<span class = "hljs-string" > "true" );</span></span></span></span></span> |
正确的写法:
zero = Integer.valueOf(<span class = "hljs-number" > 0 ); <span class = "hljs-keyword" > return Boolean.<span class = "hljs-keyword" >TRUE;</span></span></span> |
请使用XML解析器
错误的写法:
int <span class = "hljs-keyword" >start = xml.indexOf(<span class = "hljs-string" > "<name>" ) + <span class = "hljs-string" > "<name>" .length(); int <span class = "hljs-keyword" >end = xml.indexOf(<span class = "hljs-string" > "</name>" ); String name = xml.substring(<span class = "hljs-keyword" >start, <span class = "hljs-keyword" >end);</span></span></span></span></span></span></span> |
正确的写法:
SAXBuilder builder = <span class = "hljs-keyword" > new SAXBuilder(<span class = "hljs-literal" > false ); Document doc = doc = builder.build(<span class = "hljs-keyword" > new StringReader(xml)); <span class = "hljs-built_in" >String name = doc.getRootElement().getChild(<span class = "hljs-string" > "name" ).getText();</span></span></span></span></span> |
请使用JDom组装XML
错误的写法:
<span class = "hljs-built_in" >String name = ... String attribute = ... String xml = <span class = "hljs-string" > "<root>" +<span class = "hljs-string" > "<name att=\"" + attribute +<span class = "hljs-string" > "\">" + name +<span class = "hljs-string" > "</name>" +<span class = "hljs-string" > "</root>" ;</span></span></span></span></span></span> |
正确的写法:
Element root = <span class = "hljs-keyword" > new Element(<span class = "hljs-string" > "root" ); root.setAttribute(<span class = "hljs-string" > "att" , attribute); root.setText(name); Document doc = <span class = "hljs-keyword" > new Documet(); doc.setRootElement(root); XmlOutputter <span class = "hljs-keyword" >out = <span class = "hljs-keyword" > new XmlOutputter(Format.getPrettyFormat()); String xml = <span class = "hljs-keyword" >out.outputString(root);</span></span></span></span></span></span></span> |
XML编码陷阱
错误的写法:
<span class = "hljs-built_in" >String xml = FileUtils.readTextFile(<span class = "hljs-string" > "my.xml" );</span></span> |
因为xml的编码在文件中指定的,而在读文件的时候必须指定编码。另外一个问题不能一次就将一个xml文件用String保存,这样对内存会造成不必要的浪费,正确的做法用InputStream来边读取边处理。为了解决编码的问题, 最好使用XML解析器来处理。
未指定字符编码
错误的写法:
Reader r = <span class = "hljs-keyword" > new FileReader(file); Writer w = <span class = "hljs-keyword" > new FileWriter(file); Reader r = <span class = "hljs-keyword" > new InputStreamReader(inputStream); Writer w = <span class = "hljs-keyword" > new OutputStreamWriter(outputStream); <span class = "hljs-built_in" >String s = <span class = "hljs-keyword" > new <span class = "hljs-built_in" >String(byteArray); <span class = "hljs-comment" > // byteArray is a byte[] byte [] a = string.getBytes();</span></span></span></span></span></span></span></span> |
这样的代码主要不具有跨平台可移植性。因为不同的平台可能使用的是不同的默认字符编码。
正确的写法:
Reader r = <span class = "hljs-keyword" > new InputStreamReader(<span class = "hljs-keyword" > new FileInputStream(file), <span class = "hljs-string" > "ISO-8859-1" ); Writer w = <span class = "hljs-keyword" > new OutputStreamWriter(<span class = "hljs-keyword" > new FileOutputStream(file), <span class = "hljs-string" > "ISO-8859-1" ); Reader r = <span class = "hljs-keyword" > new InputStreamReader(inputStream, <span class = "hljs-string" > "UTF-8" ); Writer w = <span class = "hljs-keyword" > new OutputStreamWriter(outputStream, <span class = "hljs-string" > "UTF-8" ); <span class = "hljs-built_in" >String s = <span class = "hljs-keyword" > new <span class = "hljs-built_in" >String(byteArray, <span class = "hljs-string" > "ASCII" ); byte [] a = string.getBytes(<span class = "hljs-string" > "ASCII" );</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
未对数据流进行缓存
错误的写法:
InputStream <span class = "hljs-keyword" >in = <span class = "hljs-keyword" > new FileInputStream(file); <span class = "hljs-keyword" > int b; <span class = "hljs-keyword" > while ((b = <span class = "hljs-keyword" >in.read()) != <span class = "hljs-number" >- 1 ) { ... }</span></span></span></span></span></span> |
上面的代码是一个byte一个byte的读取,导致频繁的本地JNI文件系统访问,非常低效,因为调用本地方法是非常耗时的。最好用BufferedInputStream包装一下。曾经做过一个测试,从/dev/zero下读取1MB,大概花了1s,而用BufferedInputStream包装之后只需要60ms,性能提高了94%! 这个也适用于output stream操作以及socket操作。
正确的写法:
InputStream <span class = "hljs-keyword" >in = <span class = "hljs-keyword" > new BufferedInputStream(<span class = "hljs-keyword" > new FileInputStream(file));</span></span></span> |
无限使用heap内存
错误的写法:
<span class = "hljs-keyword" > byte [] pdf = toPdf(file);</span> |
这里有一个前提,就是文件大小不能讲JVM的heap撑爆。否则就等着OOM吧,尤其是在高并发的服务器端代码。最好的做法是采用Stream的方式边读取边存储(本地文件或database)。
正确的写法:
<span class = "hljs-attribute" >File pdf = toPdf(file);</span> |
另外,对于服务器端代码来说,为了系统的安全,至少需要对文件的大小进行限制。
不指定超时时间
错误的代码:
Socket socket = ... socket.connect(remote); InputStream <span class = "hljs-keyword" >in = socket.getInputStream(); <span class = "hljs-keyword" > int i = <span class = "hljs-keyword" >in.read();</span></span></span> |
这种情况在工作中已经碰到不止一次了。个人经验一般超时不要超过20s。这里有一个问题,connect可以指定超时时间,但是read无法指定超时时间。但是可以设置阻塞(block)时间。
正确的写法:
Socket socket = ... socket.connect(remote, <span class = "hljs-number" > 20000 ); <span class = "hljs-comment" > // fail after 20s InputStream <span class = "hljs-keyword" >in = socket.getInputStream(); socket.setSoTimeout(<span class = "hljs-number" > 15000 ); <span class = "hljs-keyword" > int i = <span class = "hljs-keyword" >in.read();</span></span></span></span></span></span> |
另外,文件的读取(FileInputStream, FileChannel, FileDescriptor, File)没法指定超时时间, 而且IO操作均涉及到本地方法调用, 这个更操作了JVM的控制范围,在分布式文件系统中,对IO的操作内部实际上是网络调用。一般情况下操作60s的操作都可以认为已经超时了。为了解决这些问题,一般采用缓存和异步/消息队列处理。
频繁使用计时器
错误代码:
<span class = "hljs-keyword" > for (...) { <span class = "hljs-keyword" > long t = System.currentTimeMillis(); <span class = "hljs-keyword" > long t = System.nanoTime(); Date d = <span class = "hljs-keyword" > new Date(); Calendar c = <span class = "hljs-keyword" > new GregorianCalendar(); }</span></span></span></span></span> |
每次new一个Date或Calendar都会涉及一次本地调用来获取当前时间(尽管这个本地调用相对其他本地方法调用要快)。
如果对时间不是特别敏感,这里使用了clone方法来新建一个Date实例。这样相对直接new要高效一些。
正确的写法:
<span class = "hljs-built_in" >Date d = <span class = "hljs-keyword" > new <span class = "hljs-built_in" >Date(); <span class = "hljs-keyword" > for (E entity : entities) { entity.doSomething(); entity.setUpdated((<span class = "hljs-built_in" >Date) d.clone()); }</span></span></span></span></span> |
如果循环操作耗时较长(超过几ms),那么可以采用下面的方法,立即创建一个Timer,然后定期根据当前时间更新时间戳,在我的系统上比直接new一个时间对象快200倍:
<span class = "hljs-keyword" > private <span class = "hljs-keyword" > volatile <span class = "hljs-keyword" > long time; Timer timer = <span class = "hljs-keyword" > new Timer(<span class = "hljs-keyword" > true ); <span class = "hljs-keyword" > try { time = System.currentTimeMillis(); timer.scheduleAtFixedRate(<span class = "hljs-keyword" > new TimerTask() { <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >run<span class = "hljs-params" >() { time = System.currentTimeMillis(); } }, <span class = "hljs-number" >0L, <span class = "hljs-number" >10L); <span class = "hljs-comment" > // granularity 10ms <span class = "hljs-keyword" > for (E entity : entities) { entity.doSomething(); entity.setUpdated(<span class = "hljs-keyword" > new Date(time)); } } <span class = "hljs-keyword" > finally { timer.cancel(); }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
捕获所有的异常
错误的写法:
Query q = ... Person p; <span class = "hljs-keyword" > try { p = (Person) q.getSingleResult(); } <span class = "hljs-keyword" > catch (<span class = "hljs-keyword" >Exception e) { p = <span class = "hljs-keyword" > null ; }</span></span></span></span> |
这是EJB3的一个查询操作,可能出现异常的原因是:结果不唯一;没有结果;数据库无法访问,而捕获所有的异常,设置为null将掩盖各种异常情况。
正确的写法:
Query q = ... Person p; <span class = "hljs-keyword" > try { p = (Person) q.getSingleResult(); } <span class = "hljs-keyword" > catch (NoResultException e) { p = <span class = "hljs-keyword" > null ; }</span></span></span> |
忽略所有异常
错误的写法:
<span class = "hljs-keyword" > try { doStuff(); } <span class = "hljs-keyword" > catch (<span class = "hljs-keyword" >Exception e) { log.fatal(<span class = "hljs-string" > "Could not do stuff" ); } doMoreStuff();</span></span></span></span> |
这个代码有两个问题, 一个是没有告诉调用者, 系统调用出错了. 第二个是日志没有出错原因, 很难跟踪定位问题。
正确的写法:
<span class = "hljs-keyword" > try { doStuff(); } <span class = "hljs-keyword" > catch (<span class = "hljs-keyword" >Exception e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new MyRuntimeException(<span class = "hljs-string" > "Could not do stuff because: " + e.getMessage, e); }</span></span></span></span></span></span> |
重复包装RuntimeException
错误的写法:
<span class = "hljs-keyword" > try { doStuff(); } <span class = "hljs-keyword" > catch (<span class = "hljs-keyword" >Exception e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e); }</span></span></span></span></span> |
正确的写法:
<span class = "hljs-keyword" > try { doStuff(); } <span class = "hljs-keyword" > catch (RuntimeException e) { <span class = "hljs-keyword" > throw e; } <span class = "hljs-keyword" > catch (<span class = "hljs-keyword" >Exception e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage(), e); } <span class = "hljs-keyword" > try { doStuff(); } <span class = "hljs-keyword" > catch (IOException e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage(), e); } <span class = "hljs-keyword" > catch (NamingException e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage(), e); }</span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
不正确的传播异常
错误的写法:
<span class = "hljs-keyword" > try { } <span class = "hljs-keyword" > catch (ParseException e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(); <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.toString()); <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage()); <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e); }</span></span></span></span></span></span></span></span></span></span> |
主要是没有正确的将内部的错误信息传递给调用者. 第一个完全丢掉了内部错误信息, 第二个错误信息依赖toString方法, 如果没有包含最终的嵌套错误信息, 也会出现丢失, 而且可读性差. 第三个稍微好一些, 第四个跟第二个一样。
正确的写法:
<span class = "hljs-keyword" > try { } <span class = "hljs-keyword" > catch (ParseException e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage(), e); }</span></span></span></span> |
用日志记录异常
错误的写法:
<span class = "hljs-keyword" > try { ... } <span class = "hljs-keyword" > catch (ExceptionA e) { <span class = "hljs-built_in" >log.error(e.getMessage(), e); <span class = "hljs-keyword" > throw e; } <span class = "hljs-keyword" > catch (ExceptionB e) { <span class = "hljs-built_in" >log.error(e.getMessage(), e); <span class = "hljs-keyword" > throw e; }</span></span></span></span></span></span></span> |
一般情况下在日志中记录异常是不必要的, 除非调用方没有记录日志。
异常处理不彻底
错误的写法:
<span class = "hljs-keyword" > try { <span class = "hljs-keyword" >is = <span class = "hljs-keyword" > new FileInputStream(inFile); os = <span class = "hljs-keyword" > new FileOutputStream(outFile); } <span class = "hljs-keyword" > finally { <span class = "hljs-keyword" > try { <span class = "hljs-keyword" >is.close(); os.close(); } <span class = "hljs-keyword" > catch (IOException e) { <span class = "hljs-comment" > /* we can‘t do anything */ } }</span></span></span></span></span></span></span></span></span> |
is可能close失败, 导致os没有close
正确的写法:
<span class = "hljs-keyword" > try { <span class = "hljs-keyword" >is = <span class = "hljs-keyword" > new FileInputStream(inFile); os = <span class = "hljs-keyword" > new FileOutputStream(outFile); } <span class = "hljs-keyword" > finally { <span class = "hljs-keyword" > try { <span class = "hljs-keyword" > if (<span class = "hljs-keyword" >is != <span class = "hljs-literal" > null ) <span class = "hljs-keyword" >is.close(); } <span class = "hljs-keyword" > catch (IOException e) {<span class = "hljs-comment" > /* we can‘t do anything */ } <span class = "hljs-keyword" > try { <span class = "hljs-keyword" > if (os != <span class = "hljs-literal" > null ) os.close(); } <span class = "hljs-keyword" > catch (IOException e) {<span class = "hljs-comment" > /* we can‘t do anything */ } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
捕获不可能出现的异常
错误的写法:
<span class = "hljs-keyword" > try { ... <span class = "hljs-keyword" > do risky stuff ... } <span class = "hljs-keyword" > catch (<span class = "hljs-type" >SomeException e) { <span class = "hljs-comment" > // never happens } ... <span class = "hljs-keyword" > do some more ...</span></span></span></span></span></span> |
正确的写法:
<span class = "hljs-keyword" > try { ... <span class = "hljs-keyword" > do risky stuff ... } <span class = "hljs-keyword" > catch (SomeException e) { <span class = "hljs-comment" > // never happens hopefully <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new IllegalStateException(e.getMessage(), e); <span class = "hljs-comment" > // crash early, passing all information } ... <span class = "hljs-keyword" > do some more ...</span></span></span></span></span></span></span></span> |
transient的误用
错误的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >A <span class = "hljs-keyword" > implements <span class = "hljs-title" >Serializable { <span class = "hljs-keyword" > private String someState; <span class = "hljs-keyword" > private <span class = "hljs-keyword" > transient Log log = LogFactory.getLog(getClass()); <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >f<span class = "hljs-params" >() { log.debug(<span class = "hljs-string" > "enter f" ); ... } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
这里的本意是不希望Log对象被序列化. 不过这里在反序列化时, 会因为log未初始化, 导致f()方法抛空指针, 正确的做法是将log定义为静态变量或者定位为具备变量。
正确的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >A <span class = "hljs-keyword" > implements <span class = "hljs-title" >Serializable { <span class = "hljs-keyword" > private String someState; <span class = "hljs-keyword" > private <span class = "hljs-keyword" > static <span class = "hljs-keyword" > final Log log = LogFactory.getLog(A. class ); <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >f<span class = "hljs-params" >() { log.debug(<span class = "hljs-string" > "enter f" ); ... } } <span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >A <span class = "hljs-keyword" > implements <span class = "hljs-title" >Serializable { <span class = "hljs-keyword" > private String someState; <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >f<span class = "hljs-params" >() { Log log = LogFactory.getLog(getClass()); log.debug(<span class = "hljs-string" > "enter f" ); ... } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
不必要的初始化
错误的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >B { <span class = "hljs-keyword" > private <span class = "hljs-keyword" > int count = <span class = "hljs-number" > 0 ; <span class = "hljs-keyword" > private String name = <span class = "hljs-keyword" > null ; <span class = "hljs-keyword" > private <span class = "hljs-keyword" > boolean important = <span class = "hljs-keyword" > false ; }</span></span></span></span></span></span></span></span></span></span></span></span> |
这里的变量会在初始化时使用默认值:0, null, false, 因此上面的写法有些多此一举。
正确的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >B { <span class = "hljs-keyword" > private <span class = "hljs-keyword" > int count; <span class = "hljs-keyword" > private String name; <span class = "hljs-keyword" > private <span class = "hljs-keyword" > boolean important; }</span></span></span></span></span></span></span></span></span> |
最好用静态final定义Log变量
<span class = "hljs-keyword" > private <span class = "hljs-keyword" > static <span class = "hljs-keyword" > final <span class = "hljs-type" >Log log = <span class = "hljs-type" >LogFactory.getLog(<span class = "hljs-type" >MyClass.<span class = "hljs-keyword" > class );</span></span></span></span></span></span></span> |
这样做的好处有三:
- 可以保证线程安全
- 静态或非静态代码都可用
- 不会影响对象序列化
选择错误的类加载器
错误的代码:
<span class = "hljs-attribute" >Class clazz = Class.forName(name); <span class = "hljs-attribute" >Class clazz = getClass().getClassLoader().loadClass(name);</span></span> |
这里本意是希望用当前类来加载希望的对象, 但是这里的getClass()可能抛出异常, 特别在一些受管理的环境中, 比如应用服务器, web容器, Java WebStart环境中, 最好的做法是使用当前应用上下文的类加载器来加载。
正确的写法:
<span class = "hljs-type" >ClassLoader cl = <span class = "hljs-type" >Thread.currentThread().getContextClassLoader(); <span class = "hljs-keyword" > if (cl == null ) cl = <span class = "hljs-type" >MyClass.<span class = "hljs-keyword" > class .getClassLoader(); <span class = "hljs-comment" > // fallback <span class = "hljs-type" >Class clazz = cl.loadClass(name);</span></span></span></span></span></span></span> |
反射使用不当
错误的写法:
Class beanClass = ... <span class = "hljs-keyword" > if (beanClass.newInstance() <span class = "hljs-keyword" > instanceof TestBean) ...</span></span> |
这里的本意是检查beanClass是否是TestBean或是其子类, 但是创建一个类实例可能没那么简单, 首先实例化一个对象会带来一定的消耗, 另外有可能类没有定义默认构造函数. 正确的做法是用Class.isAssignableFrom(Class) 方法。
正确的写法:
<span class = "hljs-type" >Class beanClass = ... <span class = "hljs-keyword" > if (<span class = "hljs-type" >TestBean.<span class = "hljs-keyword" > class .isAssignableFrom(beanClass)) ...</span></span></span></span> |
不必要的同步
错误的写法:
Collection l = <span class = "hljs-keyword" > new Vector(); <span class = "hljs-keyword" > for (...) { l.add(<span class = "hljs-keyword" >object); }</span></span></span> |
Vector是ArrayList同步版本。
正确的写法:
Collection l = <span class = "hljs-keyword" > new ArrayList(); <span class = "hljs-keyword" > for (...) { l.add(<span class = "hljs-keyword" >object); }</span></span></span> |
错误的选择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陷阱
错误的写法:
<span class = "hljs-built_in" >Map map = <span class = "hljs-keyword" > new HashMap(collection.size()); <span class = "hljs-keyword" > for (<span class = "hljs-built_in" >Object o : collection) { map.put(o.key, o.value); }</span></span></span></span> |
这里可以参考guava的Maps.newHashMapWithExpectedSize的实现. 用户的本意是希望给HashMap设置初始值, 避免扩容(resize)的开销. 但是没有考虑当添加的元素数量达到HashMap容量的75%时将出现resize。
正确的写法:
Map <span class = "hljs-built_in" >map = <span class = "hljs-keyword" > new HashMap(<span class = "hljs-number" > 1 + (<span class = "hljs-keyword" > int ) (collection.size() / <span class = "hljs-number" > 0.75 ));</span></span></span></span></span> |
对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)
比如下面的代码。
错误的写法:
<span class = "hljs-keyword" >List<Integer> codes = <span class = "hljs-keyword" > new ArrayList<Integer>(); codes.add(Integer.valueOf(<span class = "hljs-number" > 10 )); codes.add(Integer.valueOf(<span class = "hljs-number" > 20 )); codes.add(Integer.valueOf(<span class = "hljs-number" > 30 )); codes.add(Integer.valueOf(<span class = "hljs-number" > 40 ));</span></span></span></span></span></span> |
正确的写法:
<span class = "hljs-keyword" > int [] codes = { <span class = "hljs-number" > 10 , <span class = "hljs-number" > 20 , <span class = "hljs-number" > 30 , <span class = "hljs-number" > 40 };</span></span></span></span></span> |
错误的写法:
<span class = "hljs-comment" > // horribly slow and a memory waster if l has a few thousand elements (try it yourself!) List<Mergeable> l = ...; <span class = "hljs-keyword" > for (<span class = "hljs-keyword" > int i=<span class = "hljs-number" > 0 ; i < l.size()<span class = "hljs-number" >- 1 ; i++) { Mergeable one = l.<span class = "hljs-keyword" >get(i); Iterator<Mergeable> j = l.iterator(i+<span class = "hljs-number" > 1 ); <span class = "hljs-comment" > // memory allocation! <span class = "hljs-keyword" > while (j.hasNext()) { Mergeable other = l.next(); <span class = "hljs-keyword" > if (one.canMergeWith(other)) { one.merge(other); other.remove(); } } }</span></span></span></span></span></span></span></span></span></span> |
正确的写法:
<span class = "hljs-comment" > // quite fast and no memory allocation Mergeable[] l = ...; <span class = "hljs-keyword" > for (<span class = "hljs-keyword" > int i=<span class = "hljs-number" > 0 ; i < l.length-<span class = "hljs-number" > 1 ; i++) { Mergeable one = l[i]; <span class = "hljs-keyword" > for (<span class = "hljs-keyword" > int j=i+<span class = "hljs-number" > 1 ; j < l.length; j++) { Mergeable other = l[j]; <span class = "hljs-keyword" > if (one.canMergeWith(other)) { one.merge(other); l[j] = <span class = "hljs-keyword" > null ; } } }</span></span></span></span></span></span></span></span></span></span> |
实际上Sun也意识到这一点, 因此在JDK中, Collections.sort()就是将一个List拷贝到一个数组中然后调用Arrays.sort方法来执行排序。
用数组来描述一个结构
错误用法:
<span class = "hljs-comment" > /** * @returns [1]: Location, [2]: Customer, [3]: Incident */ Object[] getDetails(<span class = "hljs-keyword" > int <span class = "hljs-keyword" >id) {...</span></span></span> |
这里用数组+文档的方式来描述一个方法的返回值. 虽然很简单, 但是很容易误用, 正确的做法应该是定义个类。
正确的写法:
<span class = "hljs-function" >Details <span class = "hljs-title" >getDetails<span class = "hljs-params" >(<span class = "hljs-keyword" > int id) {...} <span class = "hljs-keyword" > private <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >Details { <span class = "hljs-keyword" > public Location location; <span class = "hljs-keyword" > public Customer customer; <span class = "hljs-keyword" > public Incident incident; }</span></span></span></span></span></span></span></span></span></span></span> |
对方法过度限制
错误用法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >notify<span class = "hljs-params" >(Person p) { ... sendMail(p.getName(), p.getFirstName(), p.getEmail()); ... } <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >PhoneBook { <span class = "hljs-function" >String <span class = "hljs-title" >lookup<span class = "hljs-params" >(String employeeId) { Employee emp = ... <span class = "hljs-keyword" > return emp.getPhone(); } }</span></span></span></span></span></span></span></span></span></span></span></span> |
第一个例子是对方法参数做了过多的限制, 第二个例子对方法的返回值做了太多的限制。
正确的写法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >notify<span class = "hljs-params" >(Person p) { ... sendMail(p); ... } <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >EmployeeDirectory { <span class = "hljs-function" >Employee <span class = "hljs-title" >lookup<span class = "hljs-params" >(String employeeId) { Employee emp = ... <span class = "hljs-keyword" > return emp; } }</span></span></span></span></span></span></span></span></span></span></span></span> |
对POJO的setter方法画蛇添足
错误的写法:
<span class = "hljs-keyword" > private String name; <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >setName<span class = "hljs-params" >(String name) { <span class = "hljs-keyword" > this .name = name.trim(); } <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void String <span class = "hljs-title" >getName<span class = "hljs-params" >() { <span class = "hljs-keyword" > return <span class = "hljs-keyword" > this .name; }</span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
有时候我们很讨厌字符串首尾出现空格, 所以在setter方法中进行了trim处理, 但是这样做的结果带来的副作用会使getter方法的返回值和setter方法不一致, 如果只是将JavaBean当做一个数据容器, 那么最好不要包含任何业务逻辑. 而将业务逻辑放到专门的业务层或者控制层中处理。
正确的做法:
<span class = "hljs-selector-tag" >person<span class = "hljs-selector-class" >.setName(<span class = "hljs-selector-tag" >textInput<span class = "hljs-selector-class" >.getText()<span class = "hljs-selector-class" >.trim());</span></span></span></span></span> |
日历对象(Calendar)误用
错误的写法:
Calendar cal = <span class = "hljs-keyword" > new GregorianCalender(TimeZone.getTimeZone(<span class = "hljs-string" > "Europe/Zurich" )); cal.setTime(date); cal.add(Calendar.HOUR_OF_DAY, <span class = "hljs-number" > 8 ); date = cal.getTime();</span></span></span> |
这里主要是对date, time, calendar和time zone不了解导致. 而在一个时间上增加8小时, 跟time zone没有任何关系, 所以没有必要使用Calendar, 直接用Date对象即可, 而如果是增加天数的话, 则需要使用Calendar, 因为采用不同的时令制可能一天的小时数是不同的(比如有些DST是23或者25个小时)
正确的写法:
date = <span class = "hljs-keyword" > new <span class = "hljs-built_in" >Date(date.getTime() + <span class = "hljs-number" >8L * <span class = "hljs-number" >3600L * <span class = "hljs-number" >1000L); <span class = "hljs-comment" > // add 8 hrs</span></span></span></span></span></span> |
TimeZone的误用
错误的写法:
Calendar cal = <span class = "hljs-keyword" > new GregorianCalendar(); cal.setTime(date); cal.<span class = "hljs-built_in" >set(Calendar.HOUR_OF_DAY, <span class = "hljs-number" > 0 ); cal.<span class = "hljs-built_in" >set(Calendar.MINUTE, <span class = "hljs-number" > 0 ); cal.<span class = "hljs-built_in" >set(Calendar.SECOND, <span class = "hljs-number" > 0 ); Date startOfDay = cal.getTime();</span></span></span></span></span></span></span> |
这里有两个错误, 一个是没有没有将毫秒归零, 不过最大的错误是没有指定TimeZone, 不过一般的桌面应用没有问题, 但是如果是服务器端应用则会有一些问题, 比如同一时刻在上海和伦敦就不一样, 因此需要指定的TimeZone.
正确的写法:
Calendar cal = <span class = "hljs-keyword" > new GregorianCalendar(user.getTimeZone()); cal.setTime(date); cal.<span class = "hljs-built_in" >set(Calendar.HOUR_OF_DAY, <span class = "hljs-number" > 0 ); cal.<span class = "hljs-built_in" >set(Calendar.MINUTE, <span class = "hljs-number" > 0 ); cal.<span class = "hljs-built_in" >set(Calendar.SECOND, <span class = "hljs-number" > 0 ); cal.<span class = "hljs-built_in" >set(Calendar.MILLISECOND, <span class = "hljs-number" > 0 ); Date startOfDay = cal.getTime();</span></span></span></span></span></span></span></span></span> |
时区(Time Zone)调整的误用
错误的写法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > static Date <span class = "hljs-title" >convertTz<span class = "hljs-params" >(Date date, TimeZone tz) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone(<span class = "hljs-string" > "UTC" )); cal.setTime(date); cal.setTimeZone(tz); <span class = "hljs-keyword" > return cal.getTime(); }</span></span></span></span></span></span></span> |
这个方法实际上没有改变时间, 输入和输出是一样的. 关于时间的问题可以参考这篇文章: http://www.odi.ch/prog/design/datetime.php 这里主要的问题是Date对象并不包含Time Zone信息. 它总是使用UTC(世界统一时间). 而调用Calendar的getTime/setTime方法会自动在当前时区和UTC之间做转换。
Calendar.getInstance()的误用
错误的写法:
<span class = "hljs-type" >Calendar <span class = "hljs-built_in" >c = <span class = "hljs-type" >Calendar.getInstance(); <span class = "hljs-built_in" >c.<span class = "hljs-keyword" >set(<span class = "hljs-number" > 2009 , <span class = "hljs-type" >Calendar.<span class = "hljs-type" >JANUARY, <span class = "hljs-number" > 15 );</span></span></span></span></span></span></span></span></span> |
Calendar.getInstance()依赖local来选择一个Calendar实现, 不同实现的2009年是不同的, 比如有些Calendar实现就没有January月份。
正确的写法:
<span class = "hljs-type" >Calendar <span class = "hljs-built_in" >c = new <span class = "hljs-type" >GregorianCalendar(timeZone); <span class = "hljs-built_in" >c.<span class = "hljs-keyword" >set(<span class = "hljs-number" > 2009 , <span class = "hljs-type" >Calendar.<span class = "hljs-type" >JANUARY, <span class = "hljs-number" > 15 );</span></span></span></span></span></span></span></span></span> |
Date.setTime()的误用
错误的写法:
account.changePassword(oldPass, newPass); <span class = "hljs-built_in" >Date lastmod = account.getLastModified(); lastmod.setTime(System.currentTimeMillis());</span> |
在更新密码之后, 修改一下最后更新时间, 这里的用法没有错,但是有更好的做法: 直接传Date对象. 因为Date是Value Object, 不可变的. 如果更新了Date的值, 实际上是生成一个新的Date实例. 这样其他地方用到的实际上不在是原来的对象, 这样可能出现不可预知的异常. 当然这里又涉及到另外一个OO设计的问题, 对外暴露Date实例本身就是不好的做法(一般的做法是在setter方法中设置Date引用参数的clone对象). 另外一种比较好的做法就是直接保存long类型的毫秒数。
正确的做法:
<span class = "hljs-selector-tag" >account<span class = "hljs-selector-class" >.changePassword(<span class = "hljs-selector-tag" >oldPass, <span class = "hljs-selector-tag" >newPass); <span class = "hljs-selector-tag" >account<span class = "hljs-selector-class" >.setLastModified(<span class = "hljs-selector-tag" > new <span class = "hljs-selector-tag" >Date());</span></span></span></span></span></span></span></span> |
SimpleDateFormat非线程安全误用
错误的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >Constants { <span class = "hljs-keyword" > public <span class = "hljs-keyword" > static <span class = "hljs-keyword" > final SimpleDateFormat date = <span class = "hljs-keyword" > new SimpleDateFormat(<span class = "hljs-string" > "dd.MM.yyyy" ); }</span></span></span></span></span></span></span></span></span> |
SimpleDateFormat不是线程安全的. 在多线程并行处理的情况下, 会得到非预期的值. 这个错误非常普遍! 如果真要在多线程环境下公用同一个SimpleDateFormat, 那么做好做好同步(cache flush, lock contention), 但是这样会搞得更复杂, 还不如直接new一个实在。
使用全局参数配置常量类/接口
<span class = "hljs-attribute" > public interface Constants { <span class = "hljs-attribute" >String version = <span class = "hljs-string" > "1.0" ; <span class = "hljs-attribute" >String dateFormat = <span class = "hljs-string" > "dd.MM.yyyy" ; <span class = "hljs-attribute" >String configFile = <span class = "hljs-string" > ".apprc" ; <span class = "hljs-attribute" > int maxNameLength = <span class = "hljs-number" > 32 ; <span class = "hljs-attribute" >String someQuery = <span class = "hljs-string" > "SELECT * FROM ..." ; }</span></span></span></span></span></span></span></span></span></span></span> |
很多应用都会定义这样一个全局常量类或接口, 但是为什么这种做法不推荐? 因为这些常量之间基本没有任何关联, 只是因为公用才定义在一起. 但是如果其他组件需要使用这些全局变量, 则必须对该常量类产生依赖, 特别是存在server和远程client调用的场景。
比较好的做法是将这些常量定义在组件内部. 或者局限在一个类库内部。
忽略造型溢出(cast overflow)
错误的写法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > int <span class = "hljs-title" >getFileSize<span class = "hljs-params" >(File f) { <span class = "hljs-keyword" > long l = f.length(); <span class = "hljs-keyword" > return (<span class = "hljs-keyword" > int ) l; }</span></span></span></span></span></span></span></span> |
这个方法的本意是不支持传递超过2GB的文件. 最好的做法是对长度进行检查, 溢出时抛出异常。
正确的写法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > int <span class = "hljs-title" >getFileSize<span class = "hljs-params" >(File f) { <span class = "hljs-keyword" > long l = f.length(); <span class = "hljs-keyword" > if (l > Integer.MAX_VALUE) <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new IllegalStateException(<span class = "hljs-string" > "int overflow" ); <span class = "hljs-keyword" > return (<span class = "hljs-keyword" > int ) l; }</span></span></span></span></span></span></span></span></span></span></span></span> |
另一个溢出bug是cast的对象不对, 比如下面第一个println. 正确的应该是下面的那个。
<span class = "hljs-keyword" > long a = System.currentTimeMillis(); <span class = "hljs-keyword" > long b = a + <span class = "hljs-number" > 100 ; System.<span class = "hljs-keyword" >out.println((<span class = "hljs-keyword" > int ) b-a); System.<span class = "hljs-keyword" >out.println((<span class = "hljs-keyword" > int ) (b-a));</span></span></span></span></span></span></span> |
对float和double使用==操作
错误的写法:
<span class = "hljs-keyword" > for (<span class = "hljs-keyword" > float f = <span class = "hljs-number" >10f; f!=<span class = "hljs-number" > 0 ; f-=<span class = "hljs-number" > 0.1 ) { System.<span class = "hljs-keyword" >out.println(f); }</span></span></span></span></span></span> |
上面的浮点数递减只会无限接近0而不会等于0, 这样会导致上面的for进入死循环. 通常绝不要对float和double使用==操作. 而采用大于和小于操作. 如果java编译器能针对这种情况给出警告. 或者在java语言规范中不支持浮点数类型的==操作就最好了。
正确的写法:
<span class = "hljs-keyword" > for (<span class = "hljs-keyword" > float f = <span class = "hljs-number" >10f; f><span class = "hljs-number" > 0 ; f-=<span class = "hljs-number" > 0.1 ) { System.<span class = "hljs-keyword" >out.println(f); }</span></span></span></span></span></span> |
用浮点数来保存money
错误的写法:
<span class = "hljs-keyword" > float total = <span class = "hljs-number" > 0 .0f; <span class = "hljs-keyword" > for (OrderLine line : lines) { total += line.price * line.count; } <span class = "hljs-keyword" > double a = <span class = "hljs-number" > 1.14 * <span class = "hljs-number" > 75 ; <span class = "hljs-comment" > // 85.5 将表示为 85.4999... System.<span class = "hljs-keyword" >out.println(Math.round(a)); <span class = "hljs-comment" > // 输出值为85 BigDecimal d = <span class = "hljs-keyword" > new BigDecimal(<span class = "hljs-number" > 1.14 ); <span class = "hljs-comment" > //造成精度丢失</span></span></span></span></span></span></span></span></span></span></span></span> |
这个也是一个老生常谈的错误. 比如计算100笔订单, 每笔0.3元, 最终的计算结果是29.9999971. 如果将float类型改为double类型, 得到的结果将是30.000001192092896. 出现这种情况的原因是, 人类和计算的计数方式不同. 人类采用的是十进制, 而计算机是二进制.二进制对于计算机来说非常好使, 但是对于涉及到精确计算的场景就会带来误差. 比如银行金融中的应用。
因此绝不要用浮点类型来保存money数据. 采用浮点数得到的计算结果是不精确的. 即使与int类型做乘法运算也会产生一个不精确的结果.那是因为在用二进制存储一个浮点数时已经出现了精度丢失. 最好的做法就是用一个string或者固定点数来表示. 为了精确, 这种表示方式需要指定相应的精度值.
BigDecimal就满足了上面所说的需求. 如果在计算的过程中精度的丢失超出了给定的范围, 将抛出runtime exception.
正确的写法:
BigDecimal total = BigDecimal.ZERO; <span class = "hljs-keyword" > for (OrderLine line : lines) { BigDecimal price = <span class = "hljs-keyword" > new BigDecimal(line.price); BigDecimal count = <span class = "hljs-keyword" > new BigDecimal(line.count); total = total.add(price.multiply(count)); <span class = "hljs-comment" > // BigDecimal is immutable! } total = total.setScale(<span class = "hljs-number" > 2 , RoundingMode.HALF_UP); BigDecimal a = (<span class = "hljs-keyword" > new BigDecimal(<span class = "hljs-string" > "1.14" )).multiply(<span class = "hljs-keyword" > new BigDecimal(<span class = "hljs-number" > 75 )); <span class = "hljs-comment" > // 85.5 exact a = a.setScale(<span class = "hljs-number" > 0 , RoundingMode.HALF_UP); <span class = "hljs-comment" > // 86 System.<span class = "hljs-keyword" >out.println(a); <span class = "hljs-comment" > // correct output: 86 BigDecimal a = <span class = "hljs-keyword" > new BigDecimal(<span class = "hljs-string" > "1.14" );</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
不使用finally块释放资源
错误的写法:
<span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >save(<span class = "hljs-params" >File f) throws IOException { OutputStream <span class = "hljs-keyword" >out = <span class = "hljs-keyword" > new BufferedOutputStream(<span class = "hljs-keyword" > new FileOutputStream(f)); <span class = "hljs-keyword" >out.write(...); <span class = "hljs-keyword" >out.close(); } <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >load(<span class = "hljs-params" >File f) throws IOException { InputStream <span class = "hljs-keyword" >in = <span class = "hljs-keyword" > new BufferedInputStream(<span class = "hljs-keyword" > new FileInputStream(f)); <span class = "hljs-keyword" >in.read(...); <span class = "hljs-keyword" >in.close(); }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
上面的代码打开一个文件输出流, 操作系统为其分配一个文件句柄, 但是文件句柄是一种非常稀缺的资源, 必须通过调用相应的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将帮助我们做清理。
<span class = "hljs-comment" > // code for your cookbook <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >save(<span class = "hljs-params" >) throws IOException { File f = ... OutputStream <span class = "hljs-keyword" >out = <span class = "hljs-keyword" > new BufferedOutputStream(<span class = "hljs-keyword" > new FileOutputStream(f)); <span class = "hljs-keyword" > try { <span class = "hljs-keyword" >out.write(...); <span class = "hljs-keyword" >out.flush(); <span class = "hljs-comment" > // don‘t lose exception by implicit flush on close } <span class = "hljs-keyword" > finally { <span class = "hljs-keyword" >out.close(); } } <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >load(<span class = "hljs-params" >File f) throws IOException { InputStream <span class = "hljs-keyword" >in = <span class = "hljs-keyword" > new BufferedInputStream(<span class = "hljs-keyword" > new FileInputStream(f)); <span class = "hljs-keyword" > try { <span class = "hljs-keyword" >in.read(...); } <span class = "hljs-keyword" > finally { <span class = "hljs-keyword" > try { <span class = "hljs-keyword" >in.close(); } <span class = "hljs-keyword" > catch (IOException e) { } } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
数据库访问也涉及到类似的情况:
<span class = "hljs-function" >Car <span class = "hljs-title" >getCar<span class = "hljs-params" >(DataSource ds, String plate) <span class = "hljs-keyword" > throws SQLException { Car car = <span class = "hljs-keyword" > null ; Connection c = <span class = "hljs-keyword" > null ; PreparedStatement s = <span class = "hljs-keyword" > null ; ResultSet rs = <span class = "hljs-keyword" > null ; <span class = "hljs-keyword" > try { c = ds.getConnection(); s = c.prepareStatement(<span class = "hljs-string" > "select make, color from cars where plate=?" ); s.setString(<span class = "hljs-number" > 1 , plate); rs = s.executeQuery(); <span class = "hljs-keyword" > if (rs.next()) { car = <span class = "hljs-keyword" > new Car(); car.make = rs.getString(<span class = "hljs-number" > 1 ); car.color = rs.getString(<span class = "hljs-number" > 2 ); } } <span class = "hljs-keyword" > finally { <span class = "hljs-keyword" > if (rs != <span class = "hljs-keyword" > null ) <span class = "hljs-keyword" > try { rs.close(); } <span class = "hljs-keyword" > catch (SQLException e) { } <span class = "hljs-keyword" > if (s != <span class = "hljs-keyword" > null ) <span class = "hljs-keyword" > try { s.close(); } <span class = "hljs-keyword" > catch (SQLException e) { } <span class = "hljs-keyword" > if (c != <span class = "hljs-keyword" > null ) <span class = "hljs-keyword" > try { c.close(); } <span class = "hljs-keyword" > catch (SQLException e) { } } <span class = "hljs-keyword" > return car; }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
finalize方法误用
错误的写法:
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >FileBackedCache { <span class = "hljs-keyword" > private File backingStore; ... <span class = "hljs-function" ><span class = "hljs-keyword" > protected <span class = "hljs-keyword" > void <span class = "hljs-title" >finalize<span class = "hljs-params" >() <span class = "hljs-keyword" > throws IOException { <span class = "hljs-keyword" > if (backingStore != <span class = "hljs-keyword" > null ) { backingStore.close(); backingStore = <span class = "hljs-keyword" > null ; } } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
这个问题Effective Java这本书有详细的说明. 主要是finalize方法依赖于GC的调用, 其调用时机可能是立马也可能是几天以后, 所以是不可预知的. 而JDK的API文档中对这一点有误导:建议在该方法中来释放I/O资源。
正确的做法是定义一个close方法, 然后由外部的容器来负责调用释放资源。
<span class = "hljs-keyword" > public <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >FileBackedCache { <span class = "hljs-keyword" > private File backingStore; ... <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >close<span class = "hljs-params" >() <span class = "hljs-keyword" > throws IOException { <span class = "hljs-keyword" > if (backingStore != <span class = "hljs-keyword" > null ) { backingStore.close(); backingStore = <span class = "hljs-keyword" > null ; } } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
在JDK 1.7 (Java 7)中已经引入了一个AutoClosable接口. 当变量(不是对象)超出了try-catch的资源使用范围, 将自动调用close方法。
<span class = "hljs-keyword" > try (Writer w = <span class = "hljs-keyword" > new FileWriter(f)) { <span class = "hljs-regexp" > // implements Closable w.write(<span class = "hljs-string" > "abc" ); <span class = "hljs-regexp" > // w goes out <span class="hljs-keyword">of scope here: w.close() <span class="hljs-keyword">is called automatically <span class="hljs-keyword">in ANY case } <span class = "hljs-keyword" > catch (IOException e) { <span class = "hljs-keyword" > throw <span class = "hljs-keyword" > new RuntimeException(e.getMessage(), e); }</span></span></span></span></span></span></span></span></span></span></span> |
Thread.interrupted方法误用
错误的写法:
<span class = "hljs-keyword" > try { Thread.sleep(<span class = "hljs-number" > 1000 ); } <span class = "hljs-keyword" > catch (InterruptedException e) { <span class = "hljs-comment" > // ok } <span class = "hljs-keyword" >or <span class = "hljs-keyword" > while (<span class = "hljs-keyword" > true ) { <span class = "hljs-keyword" > if (Thread.interrupted()) <span class = "hljs-keyword" > break ; }</span></span></span></span></span></span></span></span></span> |
这里主要是interrupted静态方法除了返回当前线程的中断状态, 还会将当前线程状态复位。
正确的写法:
<span class = "hljs-keyword" > try { Thread.sleep(<span class = "hljs-number" > 1000 ); } <span class = "hljs-keyword" > catch (InterruptedException e) { Thread.currentThread().interrupt(); } <span class = "hljs-keyword" >or <span class = "hljs-keyword" > while (<span class = "hljs-keyword" > true ) { <span class = "hljs-keyword" > if (Thread.currentThread().isInterrupted()) <span class = "hljs-keyword" > break ; }</span></span></span></span></span></span></span></span> |
在静态变量初始化时创建线程
错误的写法:
<span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >Cache { <span class = "hljs-keyword" > private <span class = "hljs-keyword" > static <span class = "hljs-keyword" > final Timer evictor = <span class = "hljs-keyword" > new Timer(); }</span></span></span></span></span></span></span> |
Timer构造器内部会new一个thread, 而该thread会从它的父线程(即当前线程)中继承各种属性。比如context classloader, ThreadLocal以及其他的安全属性(访问权限)。 而加载当前类的线程可能是不确定的,比如一个线程池中随机的一个线程。如果你需要控制线程的属性,最好的做法就是将其初始化操作放在一个静态方法中,这样初始化将由它的调用者来决定。
正确的做法:
<span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >Cache { <span class = "hljs-keyword" > private <span class = "hljs-keyword" > static Timer evictor; <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > static <span class = "hljs-title" >setupEvictor<span class = "hljs-params" >() { evictor = <span class = "hljs-keyword" > new Timer(); } }</span></span></span></span></span></span></span></span></span></span></span> |
已取消的定时器任务依然持有状态
错误的写法:
<span class = "hljs-keyword" > final MyClass callback = <span class = "hljs-keyword" > this ; TimerTask task = <span class = "hljs-keyword" > new TimerTask() { <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >run<span class = "hljs-params" >() { callback.timeout(); } }; timer.schedule(task, <span class = "hljs-number" >300000L); <span class = "hljs-keyword" > try { doSomething(); } <span class = "hljs-keyword" > finally { task.cancel(); }</span></span></span></span></span></span></span></span></span></span></span> |
上面的task内部包含一个对外部类实例的应用, 这将导致该引用可能不会被GC立即回收. 因为Timer将保留TimerTask在指定的时间之后才被释放. 因此task对应的外部类实例将在5分钟后被回收。
正确的写法:
TimerTask task = <span class = "hljs-keyword" > new Job(<span class = "hljs-keyword" > this ); timer.schedule(task, <span class = "hljs-number" >300000L); <span class = "hljs-keyword" > try { doSomething(); } <span class = "hljs-keyword" > finally { task.cancel(); } <span class = "hljs-keyword" > static <span class = "hljs-class" ><span class = "hljs-keyword" > class <span class = "hljs-title" >Job <span class = "hljs-keyword" > extends <span class = "hljs-title" >TimerTask { <span class = "hljs-keyword" > private MyClass callback; <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-title" >Job<span class = "hljs-params" >(MyClass callback) { <span class = "hljs-keyword" > this .callback = callback; } <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > boolean <span class = "hljs-title" >cancel<span class = "hljs-params" >() { callback = <span class = "hljs-keyword" > null ; <span class = "hljs-keyword" > return <span class = "hljs-keyword" > super .cancel(); } <span class = "hljs-function" ><span class = "hljs-keyword" > public <span class = "hljs-keyword" > void <span class = "hljs-title" >run<span class = "hljs-params" >() { <span class = "hljs-keyword" > if (callback == <span class = "hljs-keyword" > null ) <span class = "hljs-keyword" > return ; callback.timeout(); } }</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span> |
以上是关于Java编程常见问题汇总的主要内容,如果未能解决你的问题,请参考以下文章