Core java里有这样一段话
If a resource needs to be closed as soon as you have finished using it, you need to manage it manually. Supply a method such as dispose or close that you call to clean up what needs cleaning. Just as importantly, if a class you use has such a method, you need to call it when you are done with the object.
什么叫a resource needs to be closed as soon as you have finished using it,是当你用完这个资源就想马上释放的意思?那这个close()函数该怎么写?
不是很理解,哪位高人能给俺举个例子呢~~
------解决方案--------------------
If a resource needs to be closed as soon as you have finished using it, you need to manage it manually.
当你使用完一个资源,就必须关闭它,而且你必须手工完成这个动作。
举个例子,数据库操作
Connection conn = DriverManager.getConnection(/*数据库驱动*/);
Statement stmt = conn.createStatement();
stmt.execute(/*SQL语句*/);
/*某些其他操作*/
//最后关闭连接,释放资源
stmt.close();
conn.close();
可以看到,这里的Connection对象和Statement对象是手工调用close()关闭的,虽然垃圾回收器会在这些对象的生命周期结束的时候回收这些对象,但并不推荐这么做。因为我们不知道垃圾回收器什么时候启动,什么时候回真正将这些资源释放,所以要手工清理。