Russell
Russell

Reputation: 4085

Java threads extended runnable state

Is there a nice way that's not CPU intensive to have a Java thread be in the Runnable state for a long period of time, like one hour?

EDIT: I'm trying to reproduce a bug. I'm suspecting a database connection is reset after a period of time, but thread sleep didn't do it. Before I move on to other possible root causes, I want to make sure that a thread in a runnable state also doesn't cause the connection to be reset.

EDIT: I found a workaround which looks like a big fat hack. Posted the answer to my own question if it helps other people at all.

Upvotes: 1

Views: 485

Answers (4)

Russell
Russell

Reputation: 4085

I think I kind of found a workaround just now.

If I try to connect to a non-existing domain, the thread will be in the running state until the connection times-out (I think this depends on the OS).

try {
    new URL("http://thisdomaindoesnotexist.com").
    openConnection().
    getInputStream().
    read();
} 
catch (Exception e) {}

On my machine this takes about 20 seconds.

The System.in InputStream also works but my web application doesn't have console input.

Upvotes: 1

Neil Coffey
Neil Coffey

Reputation: 21795

If a thread is runnable (at the OS level, there's generally a difference between "runnable" and "actually running on a CPU as we speak"), then at some point sooner or later, the OS will try to give it some CPU time. There's kind of no way round that-- there's not really a category of "runnable but I don't to actually give it any CPU time". A potential option may be to give the thread a low priority: just be clear about what that actually means on your particular system (I've written a little about thread priorities and what they really mean on different OS's in case it helps).

Also have a look at Thread.yield() -- again, just be aware that it means different things on different OS's.

However, I stress from my comment above-- I wonder if your OS is simply closing connections after a certain time open and/or at a certain scheduled time closing all idle connections, rather than things being dependent on thread state/CPU usage.

Upvotes: 0

finnw
finnw

Reputation: 48619

I don't think so. The only way a thread could stay runnable is to be CPU-bound or to be waiting for a higher-priority thread that was CPU-bound.

Upvotes: 2

adrianboimvaser
adrianboimvaser

Reputation: 2641

A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

Have the processor work on something else :)

Upvotes: 2

Related Questions