1

I was wondering what's the timeout accuracy of the method java.net.Socket.connect(SocketAddress, int timeout)?

Initially I'd thought that it's built atop java.lang.Object.wait and thus have a 10-15 millisecond error (source),

But after examining the source code, it looks like all it does is to delegate the call to java.net.SocketImpl.connect(SocketaAddress, int).

Does this mean that java.net.Socket.connect(SocketAddress, int) does not use Object.wait and hence is not subject to the 10-15 millisecond error Object.wait has?

Community
  • 1
  • 1
Pacerier
  • 86,231
  • 106
  • 366
  • 634

2 Answers2

2

Firstly, I would expect that the socket connect timeout is handled directly by the OS/kernel. The C socket API supports connect timeouts, so I expect the JVM native implementation will simply delegate to it.

Secondly, why do you care about accuracy of 10-15ms on a network connect? It sounds like you'll end up with something very brittle.

dty
  • 18,795
  • 6
  • 56
  • 82
  • No I was wondering if java.net.Socket.connect uses timing based on Object.wait or some *internal* functions. – Pacerier Jan 27 '12 at 14:12
  • @Pacerier The answer to "Why do you care...?" would probably help responders give you the answer your looking for. You'll also have to define 'internal'. Delegating to the native OS socket implementation is what I would consider to be 'internal'. – Dev Jan 27 '12 at 14:25
1

it looks like all it does is to delegate the call to java.net.SocketImpl.connect(SocketaAddress, int).

which is an abstract method of the SocketImpl class.

The subclass actually implementing it (the system-default SocketImpl implicitly retrieved from SocketImplFactory.createSocketImpl() in the Socket constructor) in turn relies on a native method, so it's not possible to know the inaccuracy in a platform-independent way.

-- EDIT (response to comment)

If not using a Socket subclass that specifies a custom SocketImpl via the protected Socket(SocketImpl impl) constructor, the standard Socket instance created by the Socket() constructor uses a SocksSocketImpl (which in turn extends PlainSocketImpl).

SocksSocketImpl.connect(SocketAddress address, int timeout)

calls

super.connect(SocketAddress address, int timeout) (PlainSocketImpl.connect(SocketAddress address, int timeout)),

which in turn calls

PlainSocketImpl.connectToAddress(InetAddress address, int port, int timeout),

which in turn calls

PlainSocketImpl.doConnect(InetAddress address, int port, int timeout),

which in turn calls

PlainSocketImpl.socketConnect(InetAddress address, int port, int timeout),

which is a private native method, and we don't know what's inside :)

So no, we're not relying upon Object.wait.

--

See http://jcs.mobile-utopia.com/jcs/18846_PlainSocketImpl.java and http://jcs.mobile-utopia.com/jcs/31401_SocksSocketImpl.java for source code

Unai Vivi
  • 3,073
  • 3
  • 30
  • 46