#StackBounty: #java #c #windows #sockets #jni Socket read timeout under windows: strange hardcode in native method

Bounty: 50

I was trying to grasp how socket read timeout is processed in native code and found some strange hardcoded value of 5000 milliseconds there:

if (timeout) {
    if (timeout <= 5000 || !isRcvTimeoutSupported) {
        int ret = NET_Timeout (fd, timeout);
        .....
        .....
    }
}

Source: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/net/SocketInputStream.c

As I can see, the variable isRcvTimeoutSupported is generally set to true, but could be dropped to false when setting socket options:

    /*
     * SO_RCVTIMEO is only supported on Microsoft's implementation
     * of Windows Sockets so if WSAENOPROTOOPT returned then
     * reset flag and timeout will be implemented using
     * select() -- see SocketInputStream.socketRead.
     */

    if (isRcvTimeoutSupported) {
        jclass iCls = (*env)->FindClass(env, "java/lang/Integer");
        jfieldID i_valueID;
        jint timeout;

        CHECK_NULL(iCls);
        i_valueID = (*env)->GetFieldID(env, iCls, "value", "I");
        CHECK_NULL(i_valueID);
        timeout = (*env)->GetIntField(env, value, i_valueID);

        /*
         * Disable SO_RCVTIMEO if timeout is <= 5 second.
         */

        if (timeout <= 5000) {
            timeout = 0;
        }


        if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
            sizeof(timeout)) < 0) {

            if (WSAGetLastError() == WSAENOPROTOOPT) {
                isRcvTimeoutSupported = JNI_FALSE;
            } else {
                NET_ThrowCurrent(env, "setsockopt SO_RCVTIMEO");
            }

        }
        ......
        ......
    }

Source: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/net/TwoStacksPlainSocketImpl.c

While I’m not quite sure, it looks like read timeout is supposed to be set through socket options when higher than 5 seconds and through NET_Timeout if less or equal to 5 seconds. Is it correct?

And anyway, where these hardcoded 5 seconds come from?
I do not see any explanation on MSDN.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.