David Key
David Key

Reputation: 21

What needs to be considered when invoke threads inside a thread in Java or It should be avoided?

I am trying to use multithread, a thread pool in fact, for a large group of concurrent tasks. Unfortunately, the tool need to be used by the thread is also implemented by using thread and it is provided by third party. Is it safe to use thread inside thread? What should be considered or should it just be avoided totally.

Upvotes: 1

Views: 126

Answers (4)

Stephen C
Stephen C

Reputation: 718788

What should be considered or it is just should be avoided totally.

A couple of things need to be considered:

  • Threads are resource hungry.
  • Thread creation is expensive.
  • A thread pool ameliorates the cost of thread creation, but a bounded thread pool can cause fatal problems in certain cases.
  • Threads are not good for solving divide and conquer problems, unless your algorithm uses the threads wisely. (Don't use / waste threads where you should use recursion.)

The fatal problem I'm talking about is when threads recursively fork other threads and wait for them to finish. If you use an unbounded thread pool you can end up with an unreasonable number of threads. If you use a bounded thread pool, you can end up in a form of deadlock, where all threads are in use, and (possibly) all of them are blocked waiting to create more threads.

(It sounds like there is potential for that kind of thing in your scenario.)

Upvotes: 2

Vishal
Vishal

Reputation: 2752

I think there is no such concept of 'Thread inside a Thread' All the threads are invoked by some thread or another. (Except few obvious) So they all kinda work in parallel.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

All threads are used "inside" other threads. (Except the ones you start with)

Perhaps you could explain your doubt in more detail.

Upvotes: 1

aioobe
aioobe

Reputation: 420951

Is it safe to use thread inside thread?

If the library is thread safe, you should be able to use it from several threads.

What should be considered or it is just should be avoided totally.

As stated above, you should make sure all classes involved (the library classes, and your classes) are thread safe.

Personally, I try to avoid several threads entirely, or at least use as high-level constructs as possible, for instance by using classes from the java.util.concurrent package.

You may want to read up on

Upvotes: 1

Related Questions