Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Can a Thread be a Singleton?

 
Murad Iqbal
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, Please advise if there is a problem in creating a Singleton Thread. The only doubt I have in mind is what will happen if the instance of the Singleton Thread is in its run method and another Object gets access to the thread by singletonThread = SingletonThread.getInstance() call and then invokes its run method?
Please advise.
Regards,
Murad.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you generally don't want to call run() methods. That doesn't do any threading for you. The code in the run() method will run on the caller's thread like any other ordinary method call.
To start a thread call start(). If you call start() on a running thread you get an invalid state exception. Make a new thread object and call start twice to see the exact error.
Can you make a single thread that will do work on behalf of numerous other threads? Yes. Take a look at the Timer object and think about what it might be doing with the TimerTasks you give it. Something like:

Other threads can put commands into the queue. If the queue is empty our run method should wait until the queue is not empty. Google for "blocking queue". Here's one http://www.javaspecialists.co.za/archive/Issue016.html from a newsletter that tends to be fairly advanced and very interesting.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are mixing the concept of a thread of execution with the concept of a Thread object. Why would you need a singleton Thread object?
 
Brice Laurencin
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry to punch that topic back up so long after the last message, but I have kind of the same concern, and google was not really helping me...

Here is the context : I need a thread to scan a folder for new files, and then do things with them. As that scanner will be in a J2EE context, I was thinking of using a singleton to access that thread (and so having only one instance of the thread), to be able to start and stop it. I tried to start the Thread at server startup, using really small a struts plugin.

Here is my thread :

When I try to check thread health ( FolderScan.getInstance().isAlive() ), it works, but starting is kills my J2EE server. I tested JOnAS 4.6.6 and WAS6.

Thanks for any help !!
[ May 09, 2006: Message edited by: Brice Laurencin ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!