views:

67

answers:

5

Is there a default timeout for threads waiting on a synchronised method in Java? Some threads in my app are not completing as expected. Is there anyway to check whether threads have died as a result of timeouts?

A: 

If a method is waiting on a synchronization object it should never die, but it could be waiting for an awfully long time (as in, "forever") if something goes wrong. Perhaps your program is never releasing a lock on a resource?

Justin Ethier
Thanks, I don't *think* there are any deadlocks, but that could be the cause..
MalcomTucker
+3  A: 

The JLS does not specify any timeout for synchronized sections. It just mentions

While the executing thread owns the lock, no other thread may acquire the lock.

ewernli
+4  A: 

You can set a timeout on the join() method to make sure you don't wait forever.

I'd have a look at the java.util.concurrent packages to see if there were new features added to help your situation.

I'd also recommend "Java Concurrency In Practice" by Brian Goetz. (I need to re-read it again myself.)

duffymo
Good point: also worth to note that the term "deadlock" means that two threads are waiting for each other. If there was a timeout, the term "deadlock" wouldn't exists.
Pindatjuh
duffymo - if one thread starts another thread, with the second thread having to report its progress to the first, but the first thread dies before the second has finished, what would you expect to happen?
MalcomTucker
I don't know. It sounds like it needs to be a bi-directional communication, but it's not. You need callbacks here. That's why I'd recommend going beyond raw java.lang.Thread and looking into the java.util.concurrent packages, because there are new features that might be applicable.
duffymo
A: 

Threads in Java don't just die suddenly. Either they are not progressing (blocked on a lock or infinite loop or similar), or if an exception is thrown and it is not handled, then the thread's execution will stop when the exception propagates to the top level (which should then print the exception's stack trace to System.err).

If your application is deadlocking, one way to find out the reason is to make a thread dump. The JVM can also itself detect simple deadlocks, in which case it will report them in the thread dump.

You can generate a thread dump under Linux by running kill -QUIT <pid> and under Windows by hitting Ctrl + Break in the console window. Or even simpler, use VisualVM, StackTrace or a similar tool.

Esko Luontola
A: 

I suggest you use kill -3 to see a thread dump, and then see what the problematic threads are.

Yuval F