What is active thread group in Java? - 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.

Related

how to bound the number of threads running simultaneously

Let's say i've got a list which holds 100 threads inside it.
i want to allow only 5 threads run simultaneously until all my threads in list have done their job.
i also can't use the java threadpool for this task.
could you give me a clue how to bound the number of my running threads?
I think what you need is semaphore. Check the doc.
Briefly speaking, semaphore is a locking method. You ask the resource from the semaphore singleton class, which is process scope unique, control the running number of function process.

Stop running Thread By Name

I have a multithreaded application and I assign a unique name to each thread through setName() property.
Now, I want functionality to get access to the threads directly with their corresponding name to stop it.
How can i get that?
To find a thread you use this: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ThreadUtils.html (https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/ThreadUtils.java)
But that gives you only a reference to the thread and you cannot simply terminate it (stop() is deprecated). Depending on what the Thread is doing maybe interrupting it is an option?
I assume you are trying to get to the thread (by its name) to call Thread.stop() on it. If that is the case - don't do that. The method is deprecated - see why.
This question has some suggestions on how to properly stop a thread.
If you really want to access a thread by name and you don't have a reference that can be used, you could use ThreadGroup and search the tree formed by groups and threads for the one with the correct name.
From the JavaDoc:
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
Thus you should be able to call Thread.currentThread().getThreadGroup(), use getParent() to find the initial/root group, list all active threads using enumerate(Thread[]) and search the threads.

When should one create new Thread Groups

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.

What's the meaning of an object's monitor in Java? Why use this word?

When reading articles about Java threads, I often notice the expression: "current thread is the owner of this object's monitor". I get the meaning: the thread gets the right to operate on the object. But I am puzzled why we use the phrase "the object's monitor" instead of "the object's lock"?
In brief, I don't know the meaning of the word 'monitor'
The question may be strange and simple. But I wish anybody can help to solve it. 3ks
but I am puzzled why use word "the object's monitor" instend of "the object's lock"?
See ulmangt's answer for links that explain the term "monitor" as used in this context. Note that:
"Monitors were invented by Per Brinch Hansen and C. A. R. Hoare, and were first implemented in Brinch Hansen's Concurrent Pascal language."
(Source: Wikipedia)
Why use the term "monitor" rather than "lock"? Well strictly speaking, the terms do mean different things ... especially if you use them in the way that they were originally intended to be used.
A "lock" is something with acquire and release primitives that maintain certain lock properties; e.g. exclusive use or single writer / multiple reader.
A "monitor" is a mechanism that ensures that only one thread can be executing a given section (or sections) of code at any given time. This can be implemented using a lock (and "condition variables" that allow threads to wait for or send notifications to other threads that the condition is fulfilled), but it is more than just a lock. Indeed, in the Java case, the actual lock used by a monitor is not directly accessible. (You just can't say "Object.lock()" to prevent other threads from acquiring it ... like you can with a Java Lock instance.)
In short, if one were to be pedantic "monitor" is actually a better term than "lock" for characterizing what Java is providing. But in practice, both terms are used almost interchangeably.
A monitor is simply a term for an object whose methods can be safely used in a multithreaded environment.
There's a great Wikipedia article on Monitors:
http://en.wikipedia.org/wiki/Monitor_(synchronization)
If you scroll down, it's even got a section explicitly about Java.
Quote from Inside the Java Virtual Machine
A thread in the Java virtual machine requests a lock when it arrives
at the beginning of a monitor region. In Java, there are two kinds of
monitor regions: synchronized statements and synchronized methods.
Monitor
A monitor is like a building that contains one special room that can
be occupied by only one thread at a time. The room usually contains
some data. From the time a thread enters this room to the time it
leaves, it has exclusive access to any data in the room. Entering the
monitor building is called "entering the monitor." Entering the
special room inside the building is called "acquiring the monitor."
Occupying the room is called "owning the monitor," and leaving the
room is called "releasing the monitor." Leaving the entire building is
called "exiting the monitor."
In addition to being associated with a bit of data, a monitor is
associated with one or more bits of code, which in this book will be
called monitor regions.
As mentioned earlier, the language provides two built-in ways to
identify monitor regions in your programs: synchronized statements and
synchronized methods. These two mechanisms, which implement the mutual
exclusion aspect of synchronization, are supported by the Java virtual
machine's instruction set.
Lock
To implement the mutual exclusion capability of monitors, the Java
virtual machine associates a lock (sometimes called a mutex) with each
object and class. A lock is like a privilege that only one thread can
"own" at any one time.
A single thread is allowed to lock the same object multiple times. For
each object, the Java virtual machine maintains a count of the number
of times the object has been locked. An unlocked object has a count of
zero. When a thread acquires the lock for the first time, the count is
again incremented to one. Each time the thread acquires a lock on the
same object, the count is again incremented.
A synchronized block around an object is its monitor, which controls a lock on the object. Here an example
synchronized (object) {
while (<condition does not hold>)
object.wait(timeout);
... // Perform action appropriate to condition
}
The Java Virtual Machine uses monitors to support multithreading. Monitors achieve this through two concepts - Mutual exclusion while running the threads (here is where 'locking' comes into picture) and coordination as a means of inter thread communication (here is where object's wait and notify methods come into picture).
Reading the following part from "Inside JVM" will clear this doubt, is it very nicely explained over here (Chapter 20, Thread synchronization) -
https://www.artima.com/insidejvm/ed2/threadsynchP.html
Even though it is late to answer this question, I thought to just add in-case it is useful.
Here is a synchronized block of Java code inside an unsynchronized Java method
public void add(int value){
synchronized(this){
this.count += value;
}
}
In the example "this" is used, which is the instance the add method is called on.
A synchronized instance method uses the object it belongs to as monitor object.
=> Only one thread can execute inside a Java code block synchronized on the same monitor object.

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