• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Is a Thread class a one-run wonder?

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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??


 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic