FileChannel没有自动释放!!!!
其他的垃圾回收会自动释放,但不能依赖于垃圾回收,还是都要手动close()
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class F2 {
public static void main(String[] args) throws Exception {
File file = new File("a.txt");
if (!file.exists()) {
file.createNewFile();
}
read();
file.delete();
// System.gc();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void read() throws Exception{
// FileInputStream in = new FileInputStream(new File("a.txt"));
// in.read();
FileChannel f = new RandomAccessFile(new File("a.txt"),"r").getChannel();
f.close();
}
}
FileInputStream
protected void finalize() throws IOException {
if ((fd != null) && (fd != FileDescriptor.in)) {
/* if fd is shared, the references in FileDescriptor
* will ensure that finalizer is only called when
* safe to do so. All references using the fd have
* become unreachable. We can call close()
*/
close();
}
}
FileOutputStream
/**
* Cleans up the connection to the file, and ensures that the
* <code>close</code> method of this file output stream is
* called when there are no more references to this stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileInputStream#close()
*/
protected void finalize() throws IOException {
if (fd != null) {
if (fd == FileDescriptor.out || fd == FileDescriptor.err) {
flush();
} else {
/* if fd is shared, the references in FileDescriptor
* will ensure that finalizer is only called when
* safe to do so. All references using the fd have
* become unreachable. We can call close()
*/
close();
}
}
}
SocketInputStream socketOutputStream
/**
* Overrides finalize, the fd is closed by the Socket.
*/
protected void finalize() {}
socket->socketImpl->PlainSocketImpl->AbstractPlainSocketImpl
/**
* Cleans up if the user forgets to close it.
*/
protected void finalize() throws IOException {
close();
}
/**
* Closes the socket.
*/
protected void close() throws IOException {
synchronized(fdLock) {
if (fd != null) {
if (!stream) {
ResourceManager.afterUdpClose();
}
if (fdUseCount == 0) {
if (closePending) {
return;
}
closePending = true;
/*
* We close the FileDescriptor in two-steps - first the
* "pre-close" which closes the socket but doesn't
* release the underlying file descriptor. This operation
* may be lengthy due to untransmitted data and a long
* linger interval. Once the pre-close is done we do the
* actual socket to release the fd.
*/
try {
socketPreClose();
} finally {
socketClose();
}
fd = null;
return;
} else {
/*
* If a thread has acquired the fd and a close
* isn't pending then use a deferred close.
* Also decrement fdUseCount to signal the last
* thread that releases the fd to close it.
*/
if (!closePending) {
closePending = true;
fdUseCount--;
socketPreClose();
}
}
}
}
}

1399

被折叠的 条评论
为什么被折叠?



