Singleton thread

D

dushkin

Hi,
I would like to run a singleton class as a thread.
The following statement fails to compile of course, because the class
ctor is private as the pattern requests...

new Thread(new MySingletonClass()).start();

Any help will be valuable!
Thanks.
 
A

Alex Hunsley

dushkin said:
Hi,
I would like to run a singleton class as a thread.
The following statement fails to compile of course, because the class
ctor is private as the pattern requests...

new Thread(new MySingletonClass()).start();

Any help will be valuable!

What you're trying to do is a bit odd.
Singletons are classically made to ensure only one instance exists,
right? So code can call getInstance() and not care.
And so the singleton class itself usually does any setup required for
its inner state.

If in your example you had:

MySingletonClass.getInstance().start();

it wouldn't really make much sense, because if another bit of code had
already called this, you'd get IllegalThreadStateException (because
thread has already started).

The classic thing for a singleton to do is to do any setup required in
getInstance, thus hiding such setup code from the caller of getInstance.
I can't comment much further without knowing what it is you're trying to
achieve here, but why not have the singleton's getInstance method do any
thread stuff that is required?

lex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,848
Messages
2,569,769
Members
45,555
Latest member
isabelferr

Latest Threads

Top