This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

Is a Thread class a one-run wonder?

Dan Kempten
Greenhorn

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
Marshal

Joined: Mar 22, 2005
Posts: 42028
    
  64
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.


Ping & DNS - my free Android networking tools app
Sam Epple
Greenhorn

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
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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).


Steve
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is a Thread class a one-run wonder?