kenny
kenny

Reputation: 2040

Creating threads within singleton

I have a singleton class that is shared by some threads.

within a method of this singleton i want to create another thread to do some job (so any thread that uses this singleton can start the additional thread job)

Right now I start threads in simple way:

mSThread = new Thread(job that implements Runnable);
mSThread.start();

Thread mSThread is declared as class member, I don't think that I need to keep reference to the threads so it's ok that every time a new thread is created the reference will be lost

Is it ok to do what i did or i should use a different technique like thread pool?

Upvotes: 0

Views: 1558

Answers (4)

Binil Thomas
Binil Thomas

Reputation: 13779

Threads are a scarce resource of the runtime. Spawning a new one every time your method is called is wasteful - especially since in your case it seems that all you care for is for the calling thread not to be blocked. So, you should make sure that your method does not get called too often.

For now, from the comments, you seem to have done that. You should also document the expectation that your method should not be called too often. Yet, some future colleague can accidentally miss this documentation and call it in a tight loop.

To prevent such occurrences, you might want to consider using a thread pool - it prevents future accidental misuse - especially since Sun/Oracle has provided the awesome java.util.concurrent package which abstract away most of the messy details.

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Thread mSThread is declared as class member,

Do you mean it is an instance variable of the singleton? If so you may have problems. Better to make it a local variable.

Upvotes: 0

Sarel Botha
Sarel Botha

Reputation: 12700

It's ok in my opinion.

What you're really facing here is possibly a premature optimization question. How often will threads be created? Will your app ever become busy enough that this becomes a problem? On your target platform how much resources and time does it take to create a new thread and is this acceptable?

Another questions is do you want to keep track of the number of threads created for management (JMX) purposes?

Upvotes: 0

Jesper
Jesper

Reputation: 206816

It is not absolutely necessary to keep a reference to the thread object, so if you don't need it for anything else, you don't need to store it in a member variable; you can just start the thread and forget the reference.

Whether you should use a thread pool, depends on what exactly your application does, how often you expect to start new threads, etc.; without further information it's hard to say whether this is worth it or not. If you do this, you'll want to use the classes from the java.util.concurrent package. Using an ExecutorService you can start background tasks in a thread pool.

Upvotes: 3

Related Questions