Thursday, August 12, 2010

Preventing grizzly timeouts

In grizzly, the default timeout for an http process is 5 minutes. This applies to the total activity time. In most cases, this is fine, however for long uploads you may need to extend this. Oh say for uploading 50g files. There is a switch for disabling timeouts, however this is global. What we need is a timeout for connections that are still active. Inactive connections should close 5m after last activity. Grizzly logs the following:
Aug 12, 2010 3:17:25 PM com.sun.grizzly.http.KeepAliveThreadAttachment timedOut
WARNING: GRIZZLY0023: Interrupting idle Thread: Grizzly-8080(2).
Aug 12, 2010 3:17:27 PM com.sun.grizzly.http.KeepAliveThreadAttachment timedOut
WARNING: GRIZZLY0023: Interrupting idle Thread: Grizzly-8080(3).
The somewhat messy solution is the pick apart the thread that your request is running in and toggle timeouts as needed.
while ((read = in.read(byteArray)) != -1)
            {
                if ((System.currentTimeMillis() - lastXmit) > 5000)
                {
                    HttpWorkerThread thread = (HttpWorkerThread)Thread.currentThread();
                    ((SelectionKeyAttachment) thread.getProcessorTask().getSelectionKey().attachment()).setTimeout(lastXmit);
                    lastXmit = System.currentTimeMillis();
                }
                buffer.clear();
                buffer.limit(read);
                openFile.write(buffer);
            }