Why StAX classes were not retrofitted for ARM in Java 7
Asked Answered
T

2

11

I expected to find XMLStreamReader to be AutoCloseable in Java 7. However, that is not the case. Is there a technical reason why StAX reader/writer interfaces were not (or should not be) retrofitted to implement AutoCloseable ? They already have close methods, whose intent is not different from the close method of AutoCloseable.

Tuberosity answered 10/5, 2012 at 15:24 Comment(0)
L
9

If you look closer to the close() method of AutoCloseable :

Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.

Or even Closeable close() method :

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.

Whereas the close() method of XMLStreamReader says :

Frees any resources associated with this Reader. This method does not close the underlying input source.

Indeed the input source is managed by the Reader which implement the Closeable interface. So it's the reader that can be close in the try-with-ressource.

For example :

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    try (FileReader fr = new FileReader("file.xml")) { //Will close the FileReader
        reader = factory.createXMLStreamReader(fr);
        reader.close();
    }
    catch (XMLStreamException ex) {
        if(reader!=null)try {
            reader.close();
        } catch (XMLStreamException ex1) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
Liddle answered 14/6, 2012 at 10:40 Comment(1)
I would personally restructure that code. reader.close() should be in a finally block in case an exception occurs (your catch is only for XMLStreamException but it could throw an unchecked exception too.) I would also remove the check for reader being null and simply nest a second level of try-finally inside the other try block.Myo
M
0

There is no technical reason why they couldn't have made these things AutoCloseable. I figure it just comes down to laziness or insufficient time looking for methods called close().

Myo answered 9/11, 2012 at 5:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.