This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Well, Future itself doesn't have any methods to support that - the closest it comes to is the isDone() method. Or isCancelled(). If you want to know the state of the Thread which is executing a given Future's run() or call() method (or whatever the Future uses to perform its work), there are several options. You could use Thread.getAllStackTraces() to get info on all the threads in the JVM, and figure out which my be running your Future. Or you could use ThreadFactory to keep track of just the threads that are used in your ExecutorService (which is at least a smaller group than tracking every thread in the JVM). You can use getStackTrace() and getState() on each thread to figure out what it's doing. Or you could wrap your Runnable or Callable in a custom implementation that identifies which thread is running it:
If you tell us the motive behind knowing the state we can help you better. Is your future task waiting for a monitor inside its execution and you want to know whether at any instant the Future is waiting for that monitor or not?
To Jim: Thank you, interesting, I think I'll use it if I won't find any other way.
To Nitesh: The problem I am facing is interesting. I wrote a lock class, to be exact a SQL table locking mechanism (read/write). When a thread is accessing a table, if it can't acquire a lock, it is put into waiting state. Now, I wrote the testing code, and it works, but the interesting thing I found is that it's difficult to write deterministic tests when threading is involved. To achieve this, at least partially, I need to know if a thread is locked, but the only way I found, without changing the lock class, is to check if a given thread is in waiting state. Since in my test class I use Future[s], here arises the problem :-)
hmmmm .... even if you get the thread state, by the time you assert results based on the thread state, the state may have changed. I think thats what you meant when you said you can not deterministically test a concurrent application. So, my next question, what are you trying to test? Is your lock working kind of a thing?