import java.io.File;
import java.io.FileWriter;
import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.helpers.DefaultHandler;

public class JI9046898 {

	public static void main(String[] args) throws Exception {
		MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 
		tryParsing(true); 
		tryParsing(false); 
		System.out.printf("At launch there are %d open descriptors\n", openFds(mbs)); 

		for (int i = 0; i < 5; i++) 
		{ 
			tryParsing(true); 
			System.out.printf("After parsing valid XML there are %d open descriptors\n", openFds(mbs)); 
			tryParsing(false); 
			System.out.printf("After parsing invalid XML there are %d open descriptors\n", openFds(mbs)); 
		} 
	} 

	private static void tryParsing(boolean valid) throws Exception 
	{ 
		SAXParserFactory factory = SAXParserFactory.newInstance(); 
		SAXParser parser = factory.newSAXParser(); 

		File temp = new File("/tmp/test.xml"); 
		try (FileWriter w = new FileWriter(temp)) 
		{ 
			w.write(valid ? "<validxml/>" : "invalidxml"); 
		} 

		try 
		{ 
			parser.parse(temp, new DefaultHandler()); 
		} 
		catch (Exception e) 
		{ 
			// discard 
		} 
	} 

	private static Long openFds(MBeanServer mbs) throws Exception 
	{ 
		ObjectName os = new ObjectName("java.lang:type=OperatingSystem"); 
		return (Long) mbs.getAttribute(os, "OpenFileDescriptorCount"); 
	} 

}
