When should one create new Thread Groups - java

I was wondering, what are the advantages of assigning threads to a thread group instead of containing them all in one (The Main) group?
Assuming there are 10 or more constantly active threads, and a couple of threads been initiated every now and again as the application requires, how would one approach grouping these?
Thanks,
Adam.

There is no advantage at all. ThreadGroups are there for backward compatibility, but I've never seen them used.
Here's what Brian Goetz (author of Java Concurrency in Practice - the bible) said about them a long time ago:
The ThreadGroup class was originally intended to be useful in
structuring collectionsof threads into groups. However, it turns out
that ThreadGroup is not all that useful. You are better off simply
using the equivalent methods in Thread. ThreadGroup does offer one
useful feature not (yet) present in Thread: the uncaughtException()
method. When a thread within a thread group exits becauseit threw an
uncaught exception, the ThreadGroup.uncaughtException() method
is called. This gives you an opportunity to shut down the system, write
a message to a log file, or restart a failed service.
Threads now have an uncauht exception handler, and this single reason to use thread groups isn't valid anymore.

Related

What is active thread group in Java?

There is method java.lang.ThreadGroup.activeGroupCount() returns an estimate of the number of active groups in a thread group. In response to this question, the active thread is defined. But what does active thread group mean?
As you noted, the terminology "active thread group" appears in the javadoc for ThreadGroup::activeGroupCount.
An active thread group is a ThreadGroup containing at least one active thread.
An active thread is one for which Thread::isAlive returns true. In other words, it has been started and has not yet terminated.
Note that thread groups are are only really suitable for debugging; see What is the benefit of ThreadGroup in java over creating separate threads?. For example, the enumerate method has this javadoc caveat:
"Due to the inherent race condition in this method, it is recommended
that the method only be used for debugging and monitoring purposes."
This also applies to the "count" methods.
In Java there is a group abstraction around a group of threads, so it is easier to manage a group of threads. See e.g. Java: Thread Group
Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.
For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the ThreadGroup(in the API reference documentation) class in the java.lang package.

Multithreaded debugging in java

I have a program that runs about 50 threads. I employ a producer consumer design pattern to communicate data between the threads. After the program has been running for a while, sometimes it freezes due to one of the BlockingQueue's I use to distribute data between the threads becomes full, and therefore the main distribution part of the program blocks when it tries to add data to this BlockingQueue. In other words, one of the threads stops for some reason and then the blockingQueue it uses to receive data becomes full.
How do I go about debugging this in an efficient manner? I have tried surrounding the content in all run() methods with catch(Exception e), but nothing is ever thrown. I develop in Java/IntelliJ.
Any thoughts, ideas or general guidelines?
"Debug it" by using a logger. I like SLF4J.
Set up log.debug statements before and after each critical operation. Use log.entering and log.exiting calls at the start and end of each method.
While you are 'debugging' you'll run your application with the logger set to a very low level (FINEST) then run your application and watch the logging statements to learn when it fails and what the state is when it fails.
Since you're worried about a threading issue, make sure your log format includes the thread name or number.
general guidelines?
I don't know if this applies to your situation, but a very important guideline is to never have locks being taken in different orders.
An example:
Thread 1:
ResourceA.lock();
ResourceB.lock();
...
ResourceB.unlock();
ResourceA.unlock();
Thread 2:
ResourceB.lock();
ResourceA.lock();
...
ResourceA.unlock();
ResourceB.unlock();
Now if thread 1 is interrupted when it already owns ResourceA but not yet ResourceB, and thread 2 is allowed to run, thread 2 will take ResourceB. Then thread 1 owns ResourceA and waits for ResourceB, and thread 2 owns ResourceB and waits for ResourceA, so you have a deadlock.

Do Java threads have a tree structure?

I have several threads. And I'd like to create sub-threads in one of them. So I'd like know whether java thread has a tree structure. Or the new created sub-threads is just the sibling of other threads. And What's the resource allocation strategy when these thread are competing for resources? Does the parent thread has higher priority ?
Thanks.
Jeff
Threads do not strictly have a tree structure. However, you can use ThreadGroups to make a hierarchical nesting of Threads and other ThreadGroups.
I don't believe that there is a hard rule for thread priority inside groups, as each thread can be set separately.
Why do you need "sub-threads"? In my experience, Thread should be avoided in favor of ExecutorService. The service won't give you a hierarchy of stuff easily, but I'm having a hard time thinking of a case where the hierarchy would be useful.
There's no thread hierarchy, all threads are siblings of each other. There is no concept of "parent thread" or "child thread". You'll have to be more specific about what you mean by resource allocation strategy -- what resources are you referring to?
If it's memory (by far the most common type of resource), then the answer is that the memory allocator is thread safe: multiple simultaneous allocations happening on different threads will always work correctly. If you run out of memory, then some unlucky thread is going to get an OutOfMemoryError.
If you're referring to other types of resources, then it depends entirely on the implementation of the resource. It's either going to be thread-safe or non-thread-safe. If it's thread-safe, you can allocate the resources freely from multiple threads. If it's not thread-safe, then read the documentation for that type of resource.
There is no concept of "subthread" in the way you describe, certainly no (apparent) tree structure. You can adjust the priority of threads if you like, though the actual meaning of thread priority is essentially undefined (unless you go to RTSJ). CPU resource allocation, by and large, is managed by the OS scheduler... you can try to influence it with priorities, but again that's a dicey proposition.
If you are looking for a framework to break a problem into subcomponents and process them concurrently, look at JDK5/JDK6's java.util.concurrent package, with specific attention to Callable and the Executor framework. Also, the ForkJoin framework might match.
The closest that there is to a thread hierarchy in Java is the ThreadGroup. By default, every application thread goes into the same ThreadGroup, but you can create new ThreadGroups and create new Threads within them. ThreadGroups are inherently hierarchical, and offer methods for doing things like enumerating the threads and child groups, interrupting all threads, setting a default uncaught exception handler, and so on.
Unfortunately, this doesn't do what you want to do. In particular, thread groups are not taken into account when allocating resources or scheduling.
There is a setMaxPriority method, but it only (indirectly) affects new threads or existing threads that change priority. Existing threads whose current priority is greater than the new "max" are not changed. So even this is not much use if you want to alter the priority of a number of threads.
(I understand, that the primary motivation of thread groups was to enable things like suspending or killing a bunch1 of related threads. But that use-case went out of the window when the Sun engineers realized that suspending and killing threads was fundamentally unsafe ... and deprecated the Thread API methods for doing that.)
1 - Anyone know the proper collective noun for a group of threads is?
Thread inherit a default priority from their parents (the one which created them) however this is just a hint and is ignored in many cases on most OSes.
Threads are designed to share resources as much as possible in as light wieght (ie simple) way possible. If you want to manage resources of tasks you need to have different processes. However these are not simple or light weight i.e they are much more expensive resource and code complexity wise.
What sort of problem are you trying to solve? It is likely for any problem there is a fairly simple solution.

Usage of Executors.newSingleThreadScheduledExecutor

The javadoc for
Executors.newSingleThreadScheduledExecutor
says
"... the returned executor is guaranteed not to be reconfigurable to use additional threads".
What does the above sentence mean? Does it mean the returned instance may not have nested threads?
It means that you cannot add additional threads to this executor after it has been created. It is guaranteed to have only one thread.
This is useful when want to ensure that only a single background task is active at any given time in your application. Mostly useful when you will be providing a reference to this executor to potentially untrusted code (code written by someone other than you).
It means, that if you share the Executor, without worying that some piece of code reconfigures the Executor to use 23 Threads and thereby killing your machine.
I guess it means that only one thread is processing the tasks, and there is no way to add more threads after the creation

What is the benefit of ThreadGroup in java over creating separate threads?

Many methods like stop(), resume(), suspend() etc are deprecated.
So is it useful to create threads using ThreadGroup?
Using ThreadGroup can be a useful diagnostic technique in big application servers with thousands of threads. If your threads are logically grouped together, then when you get a stack trace you can see which group the offending thread was part of (e.g. "Tomcat threads", "MDB threads", "thread pool X", etc), which can be a big help in tracking down and fixing the problem.
Don't use ThreadGroup for new code. Use the Executor stuff in java.util.concurrent instead.
Somewhat complimentary to the answer provided (6 years ago or so). But, while the Concurrency API provides a lot of constructs, the ThreadGroup might still be useful to use. It provides the following functionality:
Logical organisation of your threads (for diagnostic purposes).
You can interrupt() all the threads in the group. (Interrupting is perfectly fine, unlike suspend(), resume() and stop()).
You can set the maximum priority of the threads in the group. (not sure how widely useful is that, but there you have it).
Sets the ThreadGroup as a daemon. (So all new threads added to it will be daemon threads).
It allows you to override its uncaughtExceptionHandler so that if one of the threads in the group throws an Exception, you have a callback to handle it.
It provides you some extra tools such as getting the list of threads, how many active ones you have etc. Useful when having a group of worker threads, or some thread pool of some kind.
The short answer is - no, not really. There's little if any benefit to using one.
To expand on that slightly, if you want to group worker threads together you're much better off using an ExecutorService. If you want to quickly count how many threads in a conceptual group are alive, you still need to check each Thread individually (as ThreadGroup.activeCount() is an estimation, meaning it's not useful if the correctness of your code depends on its output).
I'd go so far as to say that the only thing you'd get from one these days, aside from the semantic compartmentalisation, is that Threads constructed as part of a group will pick up the daemon flag and a sensible name based on their group. And using this as a shortcut for filling in a few primitives in a constructor call (which typically you'd only have to write once anyway, sicne you're probably starting the threads in a loop and/or method call).
So - I really don't see any compelling reason to use one at all. I specifically tried to, a few months back, and failed.
EDIT - I suppose one potential use would be if you're running with a SecurityManager, and want to assert that only threads in the same group can interrupt each other. Even that's pretty borderline, as the default implementation always returns true for a Thread in any non-system thread group. And if you're implementing your own SecurityManager, you've got the possibility to have it make its decision on any other criteria (including the typical technique of storing Threads in collections as they get created).
Great answer for #skaffman. I want to add one more advantage:
Thread groups helps manipulating all the threads which are defined in this at once.

Categories

Resources