• Post Reply Bookmark Topic Watch Topic
  • New Topic

calling object.start() in a constructor  RSS feed

 
Dean J
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am curious to know if calling the start() method in a constructor is a good idea. Say,
public class MyClass extends SomeClass implements Runnable
{
public MyClass(String myName)
{
Thread thread = new Thread(this,myName);
.....
..
thread.start();
}

// run and other methods
}
Is it possible that the thread starts running even before the object (i.e. this) is fully set.
-D.J
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it's usually a good idea. You might be alright if you take care to call start() at the end of the constructor. But, what happens when someone wants to subclass your class? The run() method might execute before the subclass constructor had finished, and access a partially initialised object. Not a good idea.
Don't do it, and if you have to do it, declare your class to be final (and clearly document why it has to be final).
- Peter
 
shailesh sonavadekar
Ranch Hand
Posts: 1874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dean J, Welcome to javaranch.
PROPER NAMES ARE NOW REQUIRED
Please refer to Official Javaranch Naming Policy & reregister yourself with proper first & last name. Please follow the naming policy & help maintain the decorum of the forum.
Waiting for your post with proper rergistered name.

YOur Friendly Bartender
Shailesh
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!