File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Is a Thread class a one-run wonder? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Is a Thread class a one-run wonder?" Watch "Is a Thread class a one-run wonder?" New topic

Is a Thread class a one-run wonder?

Dan Kempten

Joined: Dec 26, 2008
Posts: 25
This is my hopper which hops in 1 second intervals. I can call 5 1 second hops with fiveHops() and it will
function fine the first time.

However the second time I call fiveHops() it has an java.lang.IllegalThreadStateException

for timing reasons I don't want to call hopper = new Hopper() each time I call fiveHops()

How can the hopper object be reset in sufficient manner to stop calling this exception??

is a Thread object meant to always be used once and then discarded??

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
From the javadocs of the java.lang.Thread#start() method: It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Why don't you want to create 4 additional objects? Object creation and the resulting memory management will likely have a performance impact that is not even measurable.
Sam Epple

Joined: Jul 11, 2008
Posts: 4
Thanks for the tip Ulf.
It is measurable. 13 ms of time spent doing new Hopper()
when doing a 50 ms hop is a 26% bite.
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

Then you have to come up with a different scheme. You can't re-start the same thread. You could make Hopper not-a-Thread, and use a single thread that waits on a signal that it should go (then re-send the Hopper to run as that signal.) This can be done a number of ways, such as through TimerTasks, or ThreadPoolExecutor (or ScheduledThreadPoolExecutor).

I agree. Here's the link:
subject: Is a Thread class a one-run wonder?
jQuery in Action, 3rd edition