Java Threads

Threads
Q: Can anyone please explain the difference between the two types: green threads and
native threads?
Answer: Green threads is thread mechanism implemented in JVM itself.
It is blind and can run on any OS, so actually all threads are run in one
native thread and scheduling is up to JVM. This is disadvantageously for
SMP systems, since only one processor can serve Java application.
Native threads is a mechanism based on OS threading mechanism. This allows
to use features of hardware and OS. For example,there is IBM's JDK for
AIX that supports native threads. The perfomance of applications
can be highly imploved by this.
Q: I use myThread.isAlive() method to test that thread is still alive. But sometime even if it
indicates that some thread is still running I am getting errors when try to use that thread. What
is wrong?
Answer: the method is Alive makes you sure that thread actually "was" not "is" alive at the
moment when you used it. I think it could be better if SUN rename it to wasAlive() and did not
confuse people. This method just checks once when you use it and does not keep eye on what
happens after.
Probably the thread will exit right after that.
The method activeCount() does the same: it counts all running threads. This information
becomes obsolete immediately next moment!
file:///C|/330_new/330_new/threads.htm (1 of 9) [2003-07-22 22:08:06]
Threads
enumerate() method is another example.
All those methods are useful only for statistic collection, nothing else. Avoid using them for
other purposes!
To know when the thread exits use join() method.
--
AP (J.A.)
Q: What are Thread Groups useful for? I do not see big reason to have them in Java API...
Answer: From the beginning Thread Groups were added for security reasons. Assumed, that
not trusted code from third parties will run in dedicated Thread Group. Of course it can not
affect the rest of program. Those threads from external companies were not allowed to start,
stop and suspend your threads. Then this model is changed and we have no such protection
now.
Now the Thread Groups will let you a little bit easier manage your threads. You can manage
many threads simultaneously rather than each separately. For example you can set maximum
priority level, call suspend(), interrupt() on all threads in your group. Also giving good names
will help you to easily track and debug your program.
M.
Q: What was wrong with stop() method for threads? Why did SUN deprecate it?
I really need it...
Answer: stop() method was very cruel. It stopped the thread without giving any possibility to
save the data.
It was not possible to predict when it will be applied. Even using finally method could not help -
stop() interrupted it as well.
Really it is still possible to use it. Simple solution:
use boolean variable, for example:
boolean letStop;
and add two functions - prepareForStop() and doMyStop().
Method prepareForStop() must save all your data and make sure that you run all your code in
thread, then set letStop to true.
Method doMyStop() will call stop() if only letStop value is true, otherwise do nothing (or inform
you and you call prepareForStop()).
Keep in mind that stop() is deprecated.
--
AP (J.A.)
Q: I tried to use destroy() method on my thread. But nothing happens! I double checked
my code and sure it is Ok. What is problem?
Answer: The problem is that SUN did not implement this method. So, it exists, but does not
destroy anything. Why?
file:///C|/330_new/330_new/threads.htm (2 of 9) [2003-07-22 22:08:06]
Threads
Sun says that if you use such powerful method your program will crash/hang later, maybe even
sooner. I believe to it because they left stop() method even, although in deprecated form, but
not destroy().
--
E
Q: I know that exist Win32 and POSIX threads. Are Java threads different on different
OSs? How can it affect my program?
Answer: Although Java designed to run on different OSs it does not mean that your program
will run in the same way, especially if you have threads.
The problem is that Java runs on some OS, not Java OS. And underlying OS implementation is
different on different OSs. UNIX uses POSIX threads - Portable Operating System Interface.
This is standard for UNIX and approved by IEEE. Microsoft as usually made it "slightly"
different that causes standard incompatibility - Win32 threads.
And implementation is different. For example, on Windows you have just limited number of
priority levels, I do not remember how many, but it was something ~10-20. In UNIX -
thousands!
So, if your program uses priority comparison of threads, let say priority 23453 and priority
23454 then it will be no difference on Windows. Be aware about it.
--
AP (J.S.)
Q: I read this statement: “The main thread must be the last thread to finish execution.
When the main thread stops, the program terminates.”
Is it true?
Answer: Absolutely wrong!
The correct one:
When you start a program, JVM creates one thread to run your program. The JVM creates one
user thread for running a program. This thread is called main thread.
The main method of the class is called from the main thread. If program spawns new threads
from the main thread it does stop until last thread id died. Even if the main thread dies program
keep running.
Q: I move from C to Java now. My friend says that I still do my programming in an old way
since do not use threads. But I do not see any reason to use them in my program. Could you
advice where I should use them and why?
Answer: You are right! Having threads functionality in Java does not mean that you MUST use
them.
A lot of programs work better without any threads. For example, editors, calculators.
Some programs run better and more reliable if they are multithreaded, for example servers,
programs with repetitive, independent tasks. The final decision of course will be done by you.
Multithreaded programs much more difficult to debug, avoid dead lock situation. Because
threads are running often independently you can not predict exactly what happens in your
program right now. Often multithreaded programs behave differently each time you start them
file:///C|/330_new/330_new/threads.htm (3 of 9) [2003-07-22 22:08:06]
Threads
and it is difficult to repeat problem exactly when you debug your program. So, if you have
simple logic, possibly no need to run multiple tasks - try to avoid the thread usage.
--
JA
Q: Why suspend() and resume() methods were deprecated?
Answer: These two functions were included into API with purpose to let do Garbage Collecting
(GC) and debugging.
For these two task the usage of suspend() and resume() is meaningful. But for all other things
they are real disaster because suspended thread can work as a controlling thread and hold a
lock. Suspending of this thread can cause hanging of program and really can be used
effectively. That's why they were deprecated.
But you can still use them if you sure that do right thing. Nobody knows how long SUN is going
to keep deprecated methods and classes. Quite possible that they never will be removed.
--
AP (J.A.)
Q: Is it true that ThreadDeath exception was "secret" and accidentally exposed to public?
Answer: Yes it is true. The original implementation was not intended to show it to us. But due to
some mistakes of SUN programmers it got out and now it is a part of API.
Warning: "An application should catch instances of this class only if it must clean up after being
terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be
rethrown so that the thread actually dies." from API reference for java.lang.ThreadDeath.
--
AP (J.A.)
Q: I know how to start thread - to run run() method... But seems there is no exit() method.
How do I stop my thread? Will it run forever?
Answer: Nothing can be run forever :-). In Java there is no exit() method. It was made
intentionally. The idea was that thread will exit when run method returns. So, when you reach
return in your run method - your thread will exit and die.
If you need to keep your thread working you do not let it reach the return :-)
--
AP (J.A.)
Q: When should I use a daemon thread? Why would I use one instead of a regular thread?
What is the purpose of daemon threads?
Answer: Any Java thread can be a daemon thread. Daemon threads are service providers for
other threads or objects running in the same process as the daemon thread. For example, the
HotJava browser has a daemon thread, named Background Image Reader, that reads images
from the file system or the network for any object or thread that needs an image.
Daemon threads are typically independent threads within an application that provide services
file:///C|/330_new/330_new/threads.htm (4 of 9) [2003-07-22 22:08:06]
Threads
for other objects within that same application. The run() method for a daemon thread is typically
an infinite loop that waits for a service request.
When the only remaining threads in a process are daemon threads, the interpreter exits. This
makes sense because when there are only daemon threads remaining, there is no other thread
for which a daemon thread can provide a service.
To specify that a thread is a daemon thread call the setDaemon() method with a boolean
parameter that is true. To determine if a thread is a daemon thread use the accessor method
isDaemon().
Q: Hi, Is there somebody who can tell me why my thread sleeps longer then I told him to
do...
I have a thread that has to sleep for 60000 millesec. But every 4, 5 minutes
it sleeps for 61000 millesec.? I have to built an application that get the
time every minute, but with this sleep I can't trust the java threads.
So can somebody tell me what is going wrong???
Answer: Really JDK never give you warranty that will wake your thread after XXX ms.
You can be sure only
that your thread will not be waked up before!
For good timing you should take another, better for real time perfomance, VM.
For example PERC from Nemonics.com or something else...
Q: I would like to ask a question about garbage collection of Thread Object.
When will a Thread Object be garbaged collected?
When the reference count to it becomes zero, or when it enters the "Dead" state, i.e. the run()
member function terminates?
Answer, part1: Since Thread is also an Object, it will only garbage collected when the reference
count is zero. You may think it is quite non-sense. the thread is useless when it enter "dead"
state. why not garbage collect it?
That's because the thread object itself may contain some other useful information even the
thread dead , e.g. the result of the execution of the thread. Thus, it is not sensible to do
garbage collect when the reference count is not zero.
--
Anthon
P.S. Important ad! Except when object A holds a reference only to object B and object B holds
a reference only to object A. Both reference counts are non-zero, but both objects are eligible
for garbage collection. Which is why few, if any, modern VMs use reference counting to
determine eligibility for garbage collection.
file:///C|/330_new/330_new/threads.htm (5 of 9) [2003-07-22 22:08:06]
Threads
Jim
Answer, Part 2: You can consider a Thread object as a normal Object for garbage collection
purposes if you consider this one rule: A running thread will not be garbage collected.
That is, a normal running thread is a root object, so the Garbage Collector will not attempt to
mark it for collection. When the thread is not running, though, normal Garbage Collection rules
apply (i.e. total # references == 0 then collect).
To get a thread with different behavior,
see the Thread.setDaemon(boolean bState) method.
--Brian
Q: I was until recently using the MS version of the Java API and I was using Thread.stop()
when I switched to SUN I see it is deprecated.
I understand why, in fact it was causing a problem that has been solved by taking it out.
However, I do need to halt the thread from running without making it sleep.
How can I do this?
Answer: One simple way to kill a thread is to have a boolean stop variable
with a method to set it to true, like so:
endThread(){
stop = true;
}
run(){
while(!stop){
//all run code goes here
}
}
If the rest of your code is okay with the last loop finishing before run() ends and the Thread
dies, this works great as it is simple and can't cause any bad states. If not you can add more
conditional statements just before you would affect something your stopped thread shouldn't.
After a certain point adding conditionals would become too inefficient and I'm sure there's a
solution to that but I don't want to figure it out right now.
--
Ben
Q: How to overcome failures in threads?
How can I monitor multiple threads? I need to find what my threads do.
I have found thread.isalive() but I have a pool of threads and they are always alive. What I need
is more specific info.
I have also found thread.getclass() but I didn’t understand how to use it.
file:///C|/330_new/330_new/threads.htm (6 of 9) [2003-07-22 22:08:06]
Threads
For example, if I write:
public class test implements Runnable .....{
private int data;
public int getData() { return data; }
}
Is it possible to use:
test test1 = (test)Thread.currentThread().getClass(); ?
I have multiple threads and I need to create a model which can handle the problems with
threads. For example if one thread fails I need to interrupt that thread and complete its work.
Answer: Try to use such kind of inspecting pattern:
A. you have an inspector class Inspector which extends Thread and has a method:
public void
handleProblem(ObjectContainingAllInformationsAboutTheProblem o) {
// here you get the information about the problem
// from the object o and use them to handle this
// problem.
}
B. You have a Pool of thread objects MyThread each of them implementing two methods :
public void inspect(Inspector i) {
if (thereIsAProblem) {
i.handleProblem(new
ObjectContainingAllInformationsAboutTheProblem(...))
}
}
C. Your main program creates an instance of Inspector and informs it about the thread pool
(gives it a reference to the pool) and starts Inspectors thread.
D. In its run() method, Inspector will periodically inspect all MyThread objects calling a method
such as the following :
private void inspectAll() {
// threadPool is the reference to the TreadPool...
for (int i=0 ; i < threadPool.numberOfThreads ; i++) {
threadPool.getThread(i).inspect(this);
}
}
Well, I hope it helps you :-)
Anyway you can extends the inspectors interface to gather more information and to be able to
monitor your threads in the way you want and when you want (if you don't inspect the Threads
you don't get any information)
--
file:///C|/330_new/330_new/threads.htm (7 of 9) [2003-07-22 22:08:06]
Threads
Michel
Q: Anyone know how I can stop a thread without using the deprecated stop() method?
Normally I would just have a "while(alive) {...}" loop, and some "stop()
{alive = false;}" method.
However, this time all the thread does is call one method, which it sits in until it finishes, and I
want to stop it in certain situations. The method isn't one I've written, so I can't alter that.
Answer: I always construct my threads so they can be killed at any time. An outline of the code
(this is just a sketch) is the following.
Mumble mumble = new Mumble(args);
Thread t = new Thread(mumble);
t.setDaemon(true);
t.start();
private class Mumble implements Runnable {
private Thingy args = null;
public Mumble(Thingy args) {
this.args = args;
}
public void run() {
try {
process();
}
catch (InterruptedException e) {
// cleanup processing and fall through to method end
}
}
private void process() {
while(true) {
// do something with args
}
}
}
Note that calling interrupt() on a Thread doesn't just instantly generate an InterruptedException.
The interrupt does happen instantly because the thread calling it is executing, not the thread
executing the process() (unless you are on a multi-processor machine in which case this may
not be true). The point of having interrupt() is to be able to stop something like a long running
method to complete.
The only very difficult problem lies in blocking I/O operations, which do not throw
file:///C|/330_new/330_new/threads.htm (8 of 9) [2003-07-22 22:08:06]
Threads
InterruptedException and probably should. Blocking I/O will block until either the underlying
stream is closed or the operation is complete... so be careful about using large blocking I/O
operations for cancellable I/O.
--
Allan Wax
Q: I want to have a program that does something every 5 seconds. Is there a method called
pause(5000) or wait(5000)?
The point is that I don’t want to create a thread simply for this purpose.
Thread.sleep() can have the current thread sleep/idle for certain period of time, but can the job
be done without threading?
Answer: You can use Thread.sleep( 5000 ) without creating a new Thread object because the
method is static. You can look at the example below:
public class TestSleep {
public static void main ( String args[] ) {
System.out.println( "Starting" );
for ( int i = 1; i < 101; i++ ) {
System.out.print( i + "\t" );
if ( i % 10 == 0 ) {
System.out.print( "\n" );
try {
Thread.sleep(1000);
}
catch( java.lang.InterruptedException Ie ) {
Ie.printStackTrace();
}
}
}
}
}

No comments: