JDK-4804331 : File{In/Out}putStream close always called twice
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.io
  • Affected Version: 1.4.0
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: generic
  • CPU: generic
  • Submitted: 2003-01-16
  • Updated: 2003-01-21
  • Resolved: 2003-01-21
Related Reports
Relates :  
Description
In FileInputstream & FileOutputstream finalize() calls close() if FileDescriptor is null.
But when close is called it usually sets FD to -1   (i.e. invalid) 
And hence finalize will always call close() regardless of whether it was called already. 

Perhaps finalise() should also check for FD being invalid  as well as checking if null?

Here's some example code to show ...

// CloseTest.java

import java.io.*;

public class CloseTest extends FileOutputStream {

	String m_name;

	public CloseTest(String name) throws FileNotFoundException {
		super(name);
		m_name = name;
	}

	public void close() throws IOException {
		System.out.println("CloseTest#close() - " + m_name + " called ..");
		super.close();
	}


	public static void doTest(String name) throws Exception {
		CloseTest test = new CloseTest(name);

		test.close();
		for (int i=0; i < 10; i++) {
			byte dummy[] = new byte[20*1024];
		}
	}

	public static void main(String args[]) throws Exception  {
		for (int i=0; i < 10; i++) {
			CloseTest.doTest("test" + i);
		}	
	}
}
//////////////////////////////////////////////////////////////////////////

This bug shows up in all j2se but not jdk 1.1.x since in that version  FD was 
set to null when Stream closed.
###@###.### 2003-01-16

Comments
EVALUATION Will not fix. These two classes are already burdened simply by having finalize() methods. Invoking the native close method twice is of little consequence to overall performance. -- ###@###.### 2003/1/21
01-11-0187