views:

247

answers:

3

Have seen this comment in a method:

//I wonder why Sun made input and output streams implement Closeable and left Socket behind

It would prevent creation of wrapper anonymous inner class which implements Closeable which delegates its close method to an instance of Socket.

A: 

public interface Closeable

A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).

I think this is because the socket itself isn't a source or destination of data, but they are the inputstream/outputstream associated with the socket.

akappa
Why the downvote?
akappa
perche' sei un pisano :)
dfa
mi sembra una ottima motivazione :D
akappa
A: 

I have no idea but I guess at the time they considered having it on the nio SocketChannel good enough...

Also, Socket has been around for a long time. New code that started to refer to it as a Closeable instead of calling Socket.close() would not be backwards compatible so maybe at the time of 1.5 (when they added Closeable) they just didn't think it was worth the effort considering that quite a few users would still want to be compatible with 1.4 and as it has no other generic interfaces you rarely treat it as anything but a Socket.

I guess backwards compatibility with 1.4 is less of an issue nowadays which could be why it is coming in Java7.

"akappa" has an IMHO other valid point.

Fredrik
+6  A: 

Closeable was introduced in Java5 whereas Socket was introduced in JDK 1.0. In Java7 Socket will be Closeable.

EDIT

You can use reflection in order to close any "closeable" object in Java 4/5/6 simply by testing the presence of a close method. Using this technique allow you to close, say, a ResultSet (that has a close() method but doesn't implements Closeable):

public static universalClose(Object o) {
    try {
        o.getClass().getMethod("close", null).invoke(o, null);
    } catch (Exception e) {
        throw new IllegalArgumentException("missing close() method");
    }   
}
dfa
So do you mean, Sun simply forgot Socket, as they introduced Closeable?
Mnementh
it's hard to say... also ResultSet has a close() method but it isn't Closeable
dfa