Threads FAQ From Jguru

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 127

Threads FAQ From jGuru

Generated Sep 13, 2005 1:16:37 PM

Location: http://www.jguru.com/faq/Threads
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.

What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?


Location: http://www.jguru.com/faq/view.jsp?EID=8963
Created: Jan 26, 2000 Modified: 2000-02-01 06:16:27.889
Author: Scott Stanchfield (http://www.jguru.com/guru/viewbio.jsp?EID=11)
Question originally posed by Mohamed M.
(http://www.jguru.com/guru/viewbio.jsp?EID=3439

When you run a GUI applet or application, the code in your main() method creates a
GUI and sets up event handling. When you call setVisible(true) for your Frame,
Window, Dialog, or when the browser displays the Applet, the user must be able to
interact with the GUI.

The problem is that your main() method may not end at that point. It could be busy
doing some other task, such as computing PI to 40,000 decimal places. If the user
had to wait for the main() method to finish before they could interact with the GUI,
they could end up quite unhappy.

So the AWT library implements its own thread to watch GUI interaction. This thread
is essentially a little loop that checks the system event queue for mouse clicks, key
presses and other system-level events. (You can also put your own events in the
system queue, but that's another story...).

The AWT thread (aka the "Event Dispatch" thread) grabs a system event off the
queue and determines what to do with it. If it looks like a click on top of a
component, it calls the mouse click processing handler for that component. That
component, in turn, could fire other events. For example, if you click on a JButton,
the AWT thread passes the mouse click to the JButton, which interprets it as a
"button press", and fires its own actionPerformed event. Anyone listening will have
their actionPerformed method called.

The AWT thread also handles repainting of your GUI. Anytime you call repaint(), a
"refresh" request is placed in the event queue. Whenever the AWT thread sees a
"refresh" request, if examines the GUI for damaged areas or components marked
invalid (ie, the text has changed on a Label), then calls the appropriate methods to
layout the GUI and paint any components that require painting.

Note: The AWT "thread" may in fact be implemented by multiple threads under some
runtime environments. These threads coordinate effort to watch for mouse clicks,
keypresses, repaint requests, etc. As far as you're concerned you can treat this all as
one "AWT thread".

AWT components are threadsafe, in that if you call a Label's setText() method, it
synchronizes such that the displayed text cannot appear with a partially old value
and partially new value. However, Swing components, are generally not threadsafe.
Because of this, you must make sure that any changes to Swing components that
might affect their display are done through the AWT event thread. If the same thread
both updates and displays a component, you are guaranteed that the display is
consistent.

You can use SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() to defer


processing to the AWT thread.

Comments and alternative answers

Jdialog modal
Author: nandhini eswaran (http://www.jguru.com/guru/viewbio.jsp?EID=399227),
Apr 9, 2001
I have an application written in java that waits for a C++ code to write result in a file.
The data in the file is used to display figures in a UI which is a JDialog. when the user
chooses a option on this dialog scrren then the next file from the C++ program is
awaited. During this process if the JDialog screen is made modal then all the figures
in the dialog screen and the main application screen are diplayed properly. But now I
want the user to interact with the main application screen when the dialog is open. So
I tried to make the Jdialog non-modal or make it a JFrame instead. But then I see only
blank screens because the paint method is not entered at all. I think this has got some
thing to do with the event handling threads which are not allowing the paint method
to be entered at all Is this the case or is there some other problem? Is there a way
around this?

See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 7, 2001
See also When exactly is the AWT thread started?

Delay in repainting GUI


Author: Andrew Siegel (http://www.jguru.com/guru/viewbio.jsp?EID=70978), Mar
14, 2003
This is very helpful but still leaves some vexing questions for me. For example, why
does a JTextArea.append, when called within an event handler running on the EDT,
not appear on the GUI until after the event handler is exited? This must be a very
common question but none of my books addresses it. What's wierder to me is that
awt's TextArea does _not_ work this way (but awt's label.setText(...) does). If the
answer has to do with JTextArea.append being one of the few synchronized Swing
methods, then why would TextArea not work the same way, if indeed awt is
threadsafe as mentioned above. Even if that can be resolved, what thread would be
locking the JTextArea for the duration of the actionPerformed method? I should say
that I program around this all the time with invokeLater, but I would really like to
understand what is going on. Something seem awry ...thanks!

Re: Delay in repainting GUI


Author: Bill Kress (http://www.jguru.com/guru/viewbio.jsp?EID=1142405), Jan
30, 2004
Generally when you update the screen it does not happen immideatly, it is added to
a queue and all done at once. You have to have the EDT to update the component,
but I'd guess that the EDT won't update the screen until after all the events (such as
yours) have been handled.

Should I use the SingleThreadModel interface or provide explicit


synchronization to make my JSP pages and servlets thread safe?
Location: http://www.jguru.com/faq/view.jsp?EID=15653
Created: Feb 18, 2000 Modified: 2000-12-06 17:23:26.122
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

You can have a any servlet implement the SingleThreadModel interface. JSP pages
implement this in the background when you specify
<%@ page isThreadSafe="false" %>

Although the SingleThreadModel technique is easy to use, and works well for low
volume sites, it does not scale well. If you anticipate your users to increase in the
future, you may be better off implementing synchronization for your variables. The
key however, is to effectively minimize the amount of code that is synchronzied so
that you take maximum advantage of multithreading.

Also, note that SingleThreadModel is pretty resource intensive from the server's
perspective. The most serious issue however is when the number of concurrent
requests exhaust the servlet instance pool. In that case, all the unserviced requests
are queued until something becomes free - which results in poor performance. Since
the usage is non-deterministic, it may not help much even if you did add more
memory and increased the size of the instance pool.

Comments and alternative answers

Thread safety
Author: Surya Sun (http://www.jguru.com/guru/viewbio.jsp?EID=729798), Jan 22,
2002
But i guess as far as servlets are concerned to some extent servlets are thread safe,
until unless you wont use global level variables. In which case either you need to use
single thread model or sychronization. As said Single Thread Model may sometimes
be a overhead as far as performance is concerned.

Re: Thread safety


Author: Games Id (http://www.jguru.com/guru/viewbio.jsp?EID=1168668), May 5,
2004
You just have repeated what Govind wrote in your confused english

Re[2]: Thread safety


Author: Murthy V (http://www.jguru.com/guru/viewbio.jsp?EID=1247172), Jun
4, 2005
Do not use SingleThreadModel as it can not guarantee thread safety in case of
session variables and static variables. In fact SingleThreadModel is deprecated
from Servlet 2.4 onwards.

Re[3]: Thread safety


Author: Dan F (http://www.jguru.com/guru/viewbio.jsp?EID=1258757), Aug
19, 2005
So what are commonly accepted best practices in coarse-grained (i.e., servlet-
level) thread-safety?

Dan

How do I have one thread wait for another thread to finish before
continuing?
Location: http://www.jguru.com/faq/view.jsp?EID=15716
Created: Feb 18, 2000 Modified: 2000-02-18 16:19:06.556
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can wait for a thread to finish by calling its join() method. For instance, in the
following code, the current thread will wait until thread2 finishes before printing
Done.

thread2.start();
// do more stuff here
thread2.join();
System.out.println("Done");
Comments and alternative answers

Thread.join()
Author: Mike Lai (http://www.jguru.com/guru/viewbio.jsp?EID=437679), Jun 12,
2001
I'm not familiar with Thread.join, just have one question regarding your sample code.
If the thread get all cpu and finished its run method assigned before the current thread
have a chance to execute thread.join(), will the code still works? Will there be any
difference if I call the thread.join() method before the thread.start()?

Re: Thread.join()
Author: Luis de la Rosa (http://www.jguru.com/guru/viewbio.jsp?EID=453550),
May 22, 2002

If you have code that looks like:

Thread a = new YourThread();


a.start();
a.join();

If thread a completes its run method before the current thread gets a chance to
execute the join method on a, that is ok. The thread is considered to be "dead" and
thus when you call join on it, the join returns right away.

The way this works is explained if you look at the code for Thread.join(). It tests to
see if the thread is still alive with the isAlive() call. Unfortunately, you cannot see
how the isAlive() method works since it is a native method and you cannot see
where the thread actually changes its state from alive to dead. However, if you
debug your a thread and ask it if it is alive, then you can see the transition. Since
thread scheduling can vary, this can happen at different times during different runs.

Here is some code to illustrate:

Thread a = new YourThread();


System.out.println( "is the thread alive before starting? " +
a.isAlive() );
a.start();
System.out.println( "is the thread alive after starting? " +
a.isAlive() );
a.join();
System.out.println( "is the thread alive after joining? " +
a.isAlive() );

The thread should be dead before starting and after joining. Depending on how fast
the thread's run executes, it may tell you it is still alive after starting.

I think the Thread lifecycle (in this context) is as follows:

1. thread created: it is dead.


2. thread started: it is now alive.
3. thread executes its run method: it is alive during this method.
4. after thread finishes its run method: it is dead.

You should not call the join() method before the start() method, because the join()
will return right away, the start() will trigger, and your current thread will happily
continue executing. However, this is probably not what you wanted if you wanted
to wait for the thread to finish before your current thread continues.

Re[2]: Thread.join()
Author: sreedevi nair (http://www.jguru.com/guru/viewbio.jsp?EID=1129328),
Nov 20, 2003
Hi even am not so familiar with JOIn().my dbt is that y we cant use wait for the
current thread and execute the 1 we want.and after the required steps.use resume
method on thread 1?

Re[2]: Thread.join()
Author: raghu veer (http://www.jguru.com/guru/viewbio.jsp?EID=1185343), Jul
20, 2004
hi Luis de la Rosa, can u brief what exactly join will do in this example..

How can I catch exceptions thrown in secondary threads I create?


Location: http://www.jguru.com/faq/view.jsp?EID=17875
Created: Feb 24, 2000 Modified: 2000-02-25 03:01:03.355
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You need to create the secondary threads in a custom ThreadGroup. Subclass


ThreadGroup and override public void uncaughtException(Thread source,
Throwable throwable). This method would then be notified when an uncaught
exception is thrown.
Comments and alternative answers

Another, less formal, technique I've found to be h...


Author: Terren Suydam (http://www.jguru.com/guru/viewbio.jsp?EID=18740), Feb
28, 2000

Another, less formal, technique I've found to be helpful is the following:

Primary thread creates secondary thread, which throws an exception.


Secondary thread catches the exception and stores it. A method is defined that
accesses this stored exception.
Primary thread calls accessor method and retrieves the exception, if any.
Alternately, the accessor method can simply throw the stored exception if one
exists.

Where can I get free source code for multi-threading in Java?


Location: http://www.jguru.com/faq/view.jsp?EID=35426
Created: Apr 12, 2000 Modified: 2000-04-12 11:42:38.197
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out Doug Lea's concurrent programming package.

Are there any good books on using Java threads out there?
Location: http://www.jguru.com/faq/view.jsp?EID=35445
Created: Apr 12, 2000 Modified: 2000-04-12 11:44:40.463
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

It depends upon your needs. The O'Reilly Java Threads book is a great book for
teaching about using the API. Doug Lea's book, Concurrent Programming in Java
discusses how to properly design your programs to take advantage of multiple
threads.
Comments and alternative answers

Doug Lea's book is at this url The O'Reilly book is...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Apr 14, 2000
Doug Lea's book is at this url
The O'Reilly book is here

I think the O'Reilly book is confusingly structured....


Author: Peter Booth (http://www.jguru.com/guru/viewbio.jsp?EID=39133), Apr 22,
2000
I think the O'Reilly book is confusingly structured. The second edition of Doug Lea's
book is fascinating but very sophisticated. I think that Paul Hyde's "Java Thread
Programming" is better than either for an intermediate to advanced Java programmer
who nees to get to grips with multithreaded Java programming in a hurry. It's well
structured and very readable. pbooth@nocoincidences.com

I agree with Peter's comments. The O'Reilly book left...


Author: Spencer Marks (http://www.jguru.com/guru/viewbio.jsp?EID=24112), Apr
26, 2000
I agree with Peter's comments. The O'Reilly book left me cold, Lea's book seems to
be the standard. (Most things I've read regarding Java threads seem to point back to
it.) However, it is pretty sophisticated (dense). Paul Hyde's book on the other hand
seems to an excellent blend of theory and practice. I found it useful almost
immediately.

How do I create a variable local to a Thread?


Location: http://www.jguru.com/faq/view.jsp?EID=38789
Created: Apr 21, 2000 Modified: 2000-04-21 12:27:30.034
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Java 1.2 release introduced the concept of thread local variables as a standard
class. Previously, they existed in the sun.server.util package of the Java WebServer
product. Now, you get them in the java.lang.ThreadLocal and
java.lang.InheritableThreadLocal classes. These classes permit individual threads to
have independent copies of variables. With ThreadLocal, only a particular thread sees
the variable, with InheritableThreadLocal a thread and all its descendents can see it.

Here's an example, taken from my Mastering Java 2 book.

public class LocalThreadVars implements Runnable {


static private class MyThreadLocal extends ThreadLocal {
protected Object initialValue() {
return new Double (Math.random() * 1000.0);
}
}
static ThreadLocal threadLocal = new MyThreadLocal();
static int counter = 0;
private LocalThreadVars() {
counter++;
}
public void run() {
LocalThreadVars myLTV = new LocalThreadVars();
displayValues();
try {
Thread.currentThread().sleep (
((Double)threadLocal.get()).longValue());
myLTV.displayValues();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void displayValues() {
System.out.println (threadLocal.get() + "\t" + counter
+
"\t" + Thread.currentThread().getName());
}
public static void main (String args[]) {
LocalThreadVars ltv = new LocalThreadVars();
ltv.displayValues();
for (int i=0;i<5;i++) {
Thread t = new Thread (ltv);
t.start();
}
}
}
Comments and alternative answers

article about ThreadLocal


Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Apr
18, 2002
If you want to learn more about Java's ThreadLocal, read this article:

http://www-106.ibm.com/developerworks/java/library/j-threads3.html

Why are resources tied to ThreadGroups?


Location: http://www.jguru.com/faq/view.jsp?EID=40141
Created: Apr 25, 2000 Modified: 2000-04-26 10:49:59.827
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4

Every thread of execution on any given platform has its own context, which contains
an execution state, and a set of access rights (among other things). A thread's
access rights are equal to that of the parent thread, minus rights denied by the
parent. In Java, all threads of execution, and thread groups within an applet (or
application) belong to a parent ThreadGroup object. A thread's access to Java
resources is therefore determined by its parent ThreadGroup object (including the
thread of execution that passes through init(), start(), stop(), processEvent(…),
bla,bla,bla).

Some of the resources on older servers (ie:X11-R5) are single threaded,


complicating access further.

What is a thread?
Location: http://www.jguru.com/faq/view.jsp?EID=41901
Created: Apr 28, 2000 Modified: 2000-04-30 10:46:57.883
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

A thread is a set of instructions executing apart from other threads (with its own
stack) but sharing the same memory space (with the same heap).
Comments and alternative answers

A thread is a flow of control that is running in the...


Author: s.v.rama mohan gupta (http://www.jguru.com/guru/viewbio.jsp?EID=36140),
May 1, 2000
A thread is a flow of control that is running in the backend. With the use of threads we
can move or destroy like animations,scrolling texts,counters etc..This plays a vital
role in the JVM, where thread control is running during compilation and execution.

Thread is a single flow of control like a process but...


Author: Deepak Kalra (http://www.jguru.com/guru/viewbio.jsp?EID=99188), Jul 24,
2000
Thread is a single flow of control like a process but it is easier to create and destroy
than a process because less resource management is involved. Therefore,a thread may
also be called a lightweight process.

What is a thread?
Author: Hugh Blanchard (http://www.jguru.com/guru/viewbio.jsp?EID=1027795),
Nov 20, 2002
A thread is a flow of execution: there may be several distinct flows created that
execute the same code (more than one thread).

A thread is tied to an application process, which is another kind of flow of execution


but constrained by the operating system. Just like threads, the same application code
can run in several distinct processes (e.g. start two Netscape instances) but they are
constrained from directly interfering with one another by the OS. However, threads
can directly interfere with each other within the same application instance (shared
memory space), hence the need for synchronization.

How do I create a new thread and have it start running?


Location: http://www.jguru.com/faq/view.jsp?EID=41903
Created: Apr 28, 2000 Modified: 2000-04-30 10:50:09.639
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
Creating a thread involves creating a new Thread and invoking its start()
method. Calling start() causes the run() method of the Thread subclass or the
Runnable object passed to the Thread constructor to execute.

Thread t1 = new Thread() {


public void run() {
for (int i=0; i<100; i++) {
System.out.println("Tastes Great");
}
}
};

Runnable r = new Runnable() {


public void run() {
for (int i=0; i<100; i++) {
System.out.println("Less Filling");
}
}
};
Thread t2 = new Thread(r);

t1.start();
t2.start();
Comments and alternative answers

instantiating an interface
Author: Kumar K (http://www.jguru.com/guru/viewbio.jsp?EID=1206680), Oct 21,
2004
Runnable r = new Runnable() Is this not instantiating a class. Would this not give a
compile error because an interface cannot be instatiated ? I did try compiling the
code. But it did not give an error. Please explain.

How do I get a thread to pause?


Location: http://www.jguru.com/faq/view.jsp?EID=41905
Created: Apr 28, 2000 Modified: 2000-04-30 10:55:57.699
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The static sleep() method of the Thread class will let your thread sleep for a set
number of milliseconds (or nanoseconds). When the thread wakes up, it will be
scheduled to execute in the future. It may not start executing immediately after the
timeout.

try {
Thread.sleep(3000); // 3 seconds
} catch (InterruptedException e) {
System.err.prinlnt("You interrupted me");
}
[

You can have another thread wake up the sleeping thread prematurely by calling
t.interrupt() (where "t" is a pointer to the thread object).

Note that since Thread.sleep is a static method, the following code will not do what
you expect it to:

Thread t = new MyThread();


t.start();
try {
t.sleep(3000);
} catch (InterruptedException e) {
System.err.prinlnt("You interrupted me");
}
It will pause the current thread, meaning the thread executing the shown code, not
the child thread (t/MyThread).
-Alex]
Comments and alternative answers

I don't think the Thread.sleep() method is very ef...


Author: David Rennalls (http://www.jguru.com/guru/viewbio.jsp?EID=214267), Dec
14, 2000
I don't think the Thread.sleep() method is very effective because it doesn't allow you
pause a Thread indefinitely. The section on "What should I use instead of
Thread.suspend.." found at
http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html gives
and example of using wait() and notify() along with a boolean to indicate whether the
thread is suspended (paused) or not. I've found this to be a good way to pause a
thread.

What object does non-static synchronized methods use for locking?


Location: http://www.jguru.com/faq/view.jsp?EID=41907
Created: Apr 28, 2000 Modified: 2000-04-30 10:56:40.387
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Non-static synchronized methods synchronize on the instance (this) of the class.


Comments and alternative answers

the this instance in non-static synchronized methods


Author: Joe Ying (http://www.jguru.com/guru/viewbio.jsp?EID=958383), Jul 21,
2002
It is the object of the class that owns the current method. The implication is that if you
want to lock the object other than the the object class that currently owns this method
you have to use: synchronized (some_obj_name) { //code goes here } instead of:
synchronized method_name() { }
What object does static synchronized methods use for locking?
Location: http://www.jguru.com/faq/view.jsp?EID=41910
Created: Apr 28, 2000 Modified: 2000-04-30 10:57:03.799
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Static synchronized methods synchronize on the class object (this.getClass())


of the class.
Comments and alternative answers

A static method does not have a concept of the this...


Author: mana jain (http://www.jguru.com/guru/viewbio.jsp?EID=317988), Mar 12,
2001
A static method does not have a concept of the this reference.It is not possible to
obtain the object lock of an object that does not exists .Just as there is an object lock
that can be obtained for each instance of a class (object),there is a lock that can be
obtained by for each class is called class lock.

Re: A static method does not have a concept of the this...


Author: Appaji Y (http://www.jguru.com/guru/viewbio.jsp?EID=495687), Sep 12,
2001
Hi, I have a doubt regarding static synchronized. If i create a instnace of class
where i put this static syn.. method, and when clients access , what will happen.Is
many instances of that class will be created or only one instance will be created.
Thanks for earlier reply.

Re[2]: A static method does not have a concept of the this...


Author: susan su (http://www.jguru.com/guru/viewbio.jsp?EID=785513), Mar 6,
2002
Can somebody tell me that how many instances of that class (which contains
static syn methods) will be created? Thanks,

Re[3]: A static method does not have a concept of the this...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar
6, 2002
One and only one (per classloader). That's what makes it static.

How can one thread wait for another thread to die before it continues
execution?
Location: http://www.jguru.com/faq/view.jsp?EID=41913
Created: Apr 28, 2000 Modified: 2000-04-30 10:57:32.565
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The thread's join() method allows you to wait for another thread to finish
execution.

Thread t1 = new Thread(runnable);


t1.start();
// do stuff
...
// wait for t1 to finish
t1.join()

What is the use of start() function in starting a thread? Why we do not use
the run() funtion directly to run the thread?
Location: http://www.jguru.com/faq/view.jsp?EID=41917
Created: Apr 28, 2000 Modified: 2000-04-30 10:58:50.963
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Aniruddh Mishra
(http://www.jguru.com/guru/viewbio.jsp?EID=36169

The start() method tells the Java Virtual Machine that it needs to create a system
specific thread. After creating the system resource, it passes the Runnable object to
it to execute its run() method. Calling the run() method directly has the "Thread"
execute in the same thread as the calling object, not in a separate thread of
execution, as intended.

In other words, calling run() is just like a normal method call. Whereas, calling
start() tells the thread to create the necessary system resources and then execute
the run() method asynchronously.

Comments and alternative answers

Run method invoked by runnable and thread


Author: samit sinha (http://www.jguru.com/guru/viewbio.jsp?EID=1061301), Feb 27,
2003
I dint get you. Can u explain a bit detail about what is difference in calling run()
method by implementing runnable AND calling t.run() by extending thread.

Re: Run method invoked by runnable and thread


Author: Rommel Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1006131),
Sep 2, 2003
Hi, The progam below shows the difference between calling run directly and
through start method. See comments in the code. Run it to see the results. Thanks,
Rommel.
/**
*@author Rommel Sharma
*
*This class shows the difference between calling a run method
directly
*(The same default thread continues to execute i.e the main method
thread)
* and invoking it through the Thread's start() method (the Java
Virtual Machine calls the run method of
* this thread and creates a system specific thread, therefore a
separate thread is created that executes asynchronously)
*
*/
class CallRun
{

public static void main(String atr[])


{
ExecuteRun er1 = new ExecuteRun("Instance 1");
ExecuteRun er2 = new ExecuteRun("Instance 2");
System.out.println("Result of calling run directly\n");
er1.run();
er2.run();

System.out.println("\nResult of calling run through 'start'


method\n");
er1.start();
er2.start();
}
}

/**
* This class extends Thread and has the run method. It also * uses
the sleep and the yield methods of the Thread class.
*/

class ExecuteRun extends Thread


{
public String str;

public ExecuteRun(String str)


{
this.str=str;
}
public void run()
{
for (int i=0; i<2;i++)
{
try
{
System.out.println("Before sleep: "+str);
sleep(2000);
System.out.println("After sleep: "+str);
}
catch(InterruptedException ie)
{
System.out.println("Exception: "+ie);
}
System.out.println("Before yield: "+str);
yield();
System.out.println("After yield: "+str);
}// End of for loop
}//End of run method
}

Where can I find a set of data structures to deal with many of the
concurrent programming concepts?
Location: http://www.jguru.com/faq/view.jsp?EID=41930
Created: Apr 28, 2000 Modified: 2000-04-30 11:00:19.655
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Doug Lea has produced a utility library in conjunction with his Concurrent
Programming in Java that includes many common classes needed to help you
synchronize your data access, like mutex and semaphore.
Comments and alternative answers

See also: Communicating Sequential Processes for ...


Author: Richard Beton (http://www.jguru.com/guru/viewbio.jsp?EID=53882), Sep
14, 2000
See also:

• Communicating Sequential Processes for JavaTM (JCSP)


• Communicating Threads for Java (CTJ)

These two packages have been developed using considerable prior art in secure
multithreaded programming. Therefore,

• They are very reliable (they have both been proven to function correctly, using
formal methods).
• They both operate without imposing an expensive overhead (indeed there may
in future be stunningly fast JVM support for them - I'm looking forward to
that!).

My personal advice is that you should never call wait, notify or notifyAll. These
methods are demonstrably hard to use correctly. Instead use one of the above
packages (or some other that you have good reason to trust).

What is the main difference between a preemptive scheduler and a non-


preemptive scheduler?
Location: http://www.jguru.com/faq/view.jsp?EID=42151
Created: Apr 28, 2000 Modified: 2000-04-30 12:10:12.781
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)

A preemptive scheduler interrupts a thread of execution when its timeslice runs out.
A non-preemptive (or "cooperative") scheduler waits for the thread to yield control.

[Java native thread implementations are usually preemptive; the green-threads


implementation is cooperative but priority-preemptive, which means that when a
high-priority thread becomes runnable, it immediately becomes active. -Alex]

Comments and alternative answers

Cooperative/Preemptive
Author: Eddy Ferguson (http://www.jguru.com/guru/viewbio.jsp?EID=388795), Mar
27, 2001
How can green threads only be switched out if a thread of higher priority becomes
available? Try creating 20 threads of the same priority on the Linux 1.2.2 distribution
running with the '-green' flag. I think you'll see that the threads are switched out even
though they have the same priority.

How does a preemptive scheduler manage a thread's timeslice?


Location: http://www.jguru.com/faq/view.jsp?EID=42175
Created: Apr 28, 2000 Modified: 2000-04-30 12:11:05.266
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)

The lowest level preemptive scheduler (kernel layer) uses the system timer interrupt
and context switching to manage timeslices. When any CPU interrupt occurs, the CPU
makes a note of where it was, and what it was doing (pushes all registers onto the
stack). The CPU then processes the interrupt and returns to what it was previously
doing (pops all registers from the stack). The thread context in this sense, is the
information the CPU needs to start or resume execution in any section of code. The
scheduler is invoked by the timer interrupt routine (it can also be part of the timer
interrupt). The scheduler checks to see if the current timeslice has expired; if so, the
current thread context is stored and the next valid thread context is restored. The
most basic implementation is a stack swap, as each thread has its own stack. When
a thread is created, it gets a new context with an empty stack. The new context
directs the CPU to the thread's run() member at the beginning of its timeslice. A
thread's context is destroyed when the thread returns from the run() member, or its
stop() member is successfully invoked.
Comments and alternative answers

Then how could I get the actual running time of a ...


Author: Shengchao Yu (http://www.jguru.com/guru/viewbio.jsp?EID=110253), Jul
25, 2000
Then how could I get the actual running time of a thread? I mean I want to get the
time that thread owns the CPU!

A preemptive scheduler gives threads no indication...


Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309), Nov
20, 2000
A preemptive scheduler gives threads no indication that they have been interrupted, or
any indication that they are about to be interrupted. There is no means to monitor
scheduling times in Java. A thread could periodically check the current system timer
that is available to Java, but it is only accurate to 1ms (an eon in CPU ticks).

What are the differences between extending the Thread class and
implementing the Runnable interface?
Location: http://www.jguru.com/faq/view.jsp?EID=42423
Created: Apr 29, 2000 Modified: 2000-04-30 12:31:04.962
Author: Dave Chen (http://www.jguru.com/guru/viewbio.jsp?EID=34562) Question
originally posed by Shardul Joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=13401
Extending the Thread class will make your class unable to extend other classes,
because of the single inheritence feature in JAVA. However, this will give you a
simpler code structure. If you implement runnable, you can gain better object-
oriented design and consistency and also avoid the single inheritance problems.
Comments and alternative answers

Another point is that implementing Runnable does not...


Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309), Apr
30, 2000
Another point is that implementing Runnable does not create a Thread object, it only
defines an entry point for threads in your object (it allows you to pass the object to the
Thread(Runnable) constructor).

Re: Another point is that implementing Runnable does not...


Author: raghu veer (http://www.jguru.com/guru/viewbio.jsp?EID=1185343), Jul
20, 2004
rob can u please explain in details with an example as i was confused with this for
a long time

Go with Runnable
Author: Carlton Anderson (http://www.jguru.com/guru/viewbio.jsp?EID=434232),
Jun 5, 2001
If you implement Runnable, you now have a class that can be run several times. A
Thread, on the other hand, can have the start method called only once. If you have a
task that can be performed multiple times in a single application, and that task keeps
track of certain information each time it is executed, go with Runnable.

I have generally heard it said that extending Thread is usually a mistake, and that the
better design is to go with Runnable. I have found that, more often than not, this is
true.

Re: Go with Runnable


Author: Anirban Chatterjee
(http://www.jguru.com/guru/viewbio.jsp?EID=530230), Oct 25, 2001
Hi Carlton , CAn you explain the above with a java program . Using both Thread
and Runnable?

Re[2]: Go with Runnable


Author: Nantu Debnath
(http://www.jguru.com/guru/viewbio.jsp?EID=1230799), Mar 4, 2005
Hii..!! I have a same question.. Can you please explain this with a suitable
example ? Regards, Nantu Debnath

Re: Go with Runnable


Author: vaibhav desai (http://www.jguru.com/guru/viewbio.jsp?EID=1211690),
Mar 9, 2005
i dont agree with carlton... when you invoke start on a thread if you invoke start
again on the same object IllegalThreadStateException will be thrown as the thread
is already running and is not in running state. if you want to run the same code
again in another thread you need to create another thread object by passing the
runnable object as reference and invoking start() on it. this is true for both the
implentations for creating a thread.

Implementing Runnable is preferable if you dont want the overhead of Thread


class, also we cannot extend any other class.

When is a thread created?


Location: http://www.jguru.com/faq/view.jsp?EID=42544
Created: Apr 30, 2000 Modified: 2000-04-30 12:36:24.587
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by s.bala subramaniyam
(http://www.jguru.com/guru/viewbio.jsp?EID=4371

A thread is created by the VM behind the scenes during a call to the start()
method. It begins its life inside the run() method of the thread subclass instance
whose start() method was called.
Comments and alternative answers

Constructors and static methods/blocks


Author: Richard Robinson (http://www.jguru.com/guru/viewbio.jsp?EID=395750),
Apr 12, 2001
So what about constructors? Is it right to think that multithreading of object instances
does NOT begin until the object has been fully constructed? Ie, until after the
constructor has reached its end brace?

Which would explain why one cannot put the "synchronized" keyword on
constructors?

As well, what about static blocks and fields -- are they subject to multithreading and
concurrency issues -- or not?

What are the different uses of the synchronized keyword?


Location: http://www.jguru.com/faq/view.jsp?EID=42569
Created: Apr 30, 2000 Modified: 2001-11-09 07:09:25.964
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Balakrishnan Lakshmanan
(http://www.jguru.com/guru/viewbio.jsp?EID=18281

The keyword synchronized is used to acquire a exclusive monitor lock on an object.


It can be used to mark either a method or a block of code. In both cases, it means to
acquire a lock for the duration of the method or block, and to release the lock at the
end. It also takes a parameter, which names the object whose lock will be acquired.
(The parameter is implicit when marking a method, as shown below.)
synchronized (foo) {
...
}
Acquires a lock on the object instance "foo" at the open brace, and releases the lock
at the close brace.

synchronized (this) {
...
}
Acquires a lock on the current object instance ("this") at the open brace, and
releases the lock at the close brace.

synchronized void bar() {


...
}
Acquires a lock on the current object instance at the open brace, and releases it at
the close brace. This is equivalent (*) to
void bar() {
synchronized (this) {
...
}
}

class Foo {
synchronized static void bar() {
...
}
}

Acquires and releases a lock on the class instance of class Foo. Every class, when
loaded, is given an instance of class Class. That means that no matter who invokes
method Foo.bar(), the lock will be on the static instance, and not on any specific
instance of class Foo.

I know this sounds confusing, but it has the same semantics as any other use of
static: all statics (methods, variables, etc) are essentially global, interact with all
other statics of the same class, and do not interact with non-static instance data.

Whether a method is public or not makes no difference to the semantics of


synchronized.

(* Actually, there is a very small, technical difference between void bar()


{ synchronized (this) { ... } } and synchronized void bar() { ... }: the
VM may be able to very slightly optimize the latter case, since the synchronization is
marked in the method signature and not in code. However, this is not important in
practice.)

See also What does it mean to lock an object?


Comments and alternative answers
This was a very nice, concise description for me. ...
Author: Andrew Siegel (http://www.jguru.com/guru/viewbio.jsp?EID=70978), Jan 24,
2001
This was a very nice, concise description for me. However, for other beginners like
myself, this might be a good place to mention what is meant in Java by a "locked
object". I got the impression that all clients were shut out, rather than just others that
explicitly synchronized on the same object. Maybe this is obvious to some people but
I noticed that popular books (e.g. Harold pp. 169) go to some length to make this very
explicit. I wasn't totally clear until I read that.

Re: This was a very nice, concise description for me. ...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 9,
2001
OK, how about What does it mean to lock an object?

Your wish is my command :-)

Re[2]: This was a very nice, concise description for me. ...
Author: Rajender Avasarala
(http://www.jguru.com/guru/viewbio.jsp?EID=781685), Mar 4, 2002
I have a question and I would like to know if my answer is right i.e, Say, I
have Thread t1 and Thread t2, and both of these threads are accessing the
instance static variable then how do I avoid race condition? My guess: If I
have it as below then may be I can avoid: class A implements Runnable
{ private static global; A() { } public void modify() { synchronized(A.global)
{ ....../// } } public void run() { modify(); } public static void main(String
args[]) { A a = new A(); Thread t1 = new Thread(a); t1.start(); t1.modify(); }
////?

Re[3]: This was a very nice, concise description for me. ...
Author: vaibhav desai
(http://www.jguru.com/guru/viewbio.jsp?EID=1211690), Mar 9, 2005
If two thread are accessing one resource no matter whether it is static or non
static, only solution is to synchronise it as mentioned above. the static
variable should be declared synchronised to prevent two threads from
accessing the same variable at a time.

How can multiple threads be controlled simultanesously?


Location: http://www.jguru.com/faq/view.jsp?EID=42760
Created: Apr 30, 2000 Modified: 2000-05-02 11:57:38.801
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Vijaybabu Srinivasan
(http://www.jguru.com/guru/viewbio.jsp?EID=18984

If you create threads in a ThreadGroup object, they may be controlled


simultaneously with the member functions of said object.
Comments and alternative answers
that's fine, but....
Author: Charlie Huddleston (http://www.jguru.com/guru/viewbio.jsp?EID=1054131),
Feb 5, 2003
How can I invoke specific methods of different threads from the class they were
created in without putting each thread created into an array. Is there a way to call
methods in all instances of a class extending Thread? i.e.
class baseClass {
main method {
while(i < 100){
threadClass b = new threadClass();
b.start();
i++;}
SOME COMMAND HERE to implement Difficult method
in all 100 threads;}}

class threadClass extends Thread {


Difficult method
print "I can't get this to happen";
run()
print "I can get this to happen";
}
sorry for the funky pseudocode but the actual program I'm doing this for is about 500
lines at this point. But the idea is that I don't want to have a huge array of
threadClasses that I have to iterate through every time I want to execute a potentially
memory consuming method in every thread. any help?

Why are the methods wait() and notify() defined in the Object class when
they are used with Threads?
Location: http://www.jguru.com/faq/view.jsp?EID=43568
Created: May 2, 2000 Modified: 2000-05-02 13:27:26.951
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Shardul Joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=13401

The wait() and notify() methods are object-specific. The wait() method suspends
the current thread of execution, and tells the object to keep track of the suspended
thread. The notify() method tells the object to wake up the suspended threads that
it is currently keeping track of. Since wait() and notify() are object specific, they
must be used within code that is synchronized on the object in question.

It is also important to use state variables when using wait() and notify(), as
threads can be woken up by conditions other than notify().

suspend() is similar to wait() but does not add the thread to an object's wait list.

Comments and alternative answers

notify() tells the JVM to wake up one of the suspended...


Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309), May
2, 2000
notify() tells the JVM to wake up one of the suspended threads associated with the
object. In Java, there is no standard as to which thread gets woken up first, but with
most multi-threaded systems the object's "thread wait list" or "thread pool" is a FIFO
(First In First Out). Use notifyAll() to wake up all threads in the object's thread
wait list pool thing.

See also How do wait and notify really work?


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 19, 2000
See also How do wait and notify really work?

The wait() and notify() methods works because these...


Author: mana jain (http://www.jguru.com/guru/viewbio.jsp?EID=317988), Mar 12,
2001
The wait() and notify() methods works because these are methods of the Thread
Object class ,since every object in the Java system inherits directly or indirectly from
the Object class .But if these methods are defined within the Thread class then only
those classes which extend it can use them.

Search Comment On FAQ Entry Why are the methods wait() and notify()
defined in the Object class when they are used with Threads?
Author: venugopal vasireddy (http://www.jguru.com/guru/viewbio.jsp?EID=828472),
Apr 7, 2002
They are for inter thread communication. specially for Producer/Consumer type of
probelms. As threads will wait on object locks. Buy calling wait on object, puts the
owner (thread) to releave the lock; do this when you can't proceed. When you can
proceed, at end notify waiting thread on that object's monitor.

What is a daemon thread? When should I use setDaemon() and why?


Location: http://www.jguru.com/faq/view.jsp?EID=43724
Created: May 2, 2000 Modified: 2001-05-21 12:50:32.523
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by Davide Sanna
(http://www.jguru.com/guru/viewbio.jsp?EID=43252

Use thread.setDaemon(true) to tell the JVM to make the thread a daemon thread.

According to Webster's, a daemon (variant of demon) is an attendant power or spirit.


Daemon threads are typically used to perform services for your application/applet
(such as loading the "fiddley bits"). The core difference between user threads and
daemon threads is that the JVM will only shut down a program when all user threads
have terminated. Daemon threads are terminated by the JVM when there are no
longer any user threads running, including the main thread of execution. Use
daemons as the minions they are.

[In short: daemon threads do not keep the program from quitting; user threads keep
the program from quitting. -Alex]
Comments and alternative answers

can't understand
Author: Ariffin Ahmad (http://www.jguru.com/guru/viewbio.jsp?EID=508512), Oct
2, 2001
sorry... but, i still can't get what u try to say...

How do I properly stop a running thread, now that Thread.stop() has been
deprecated?
Location: http://www.jguru.com/faq/view.jsp?EID=43726
Created: May 2, 2000 Modified: 2000-05-05 17:53:33.199
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Check out
http://java.sun.com/products/jdk/1.2/docs/guide/misc/threadPrimitiveDeprecation.h
tml.
Comments and alternative answers

That's all well and good, but how are we supposed to...
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 5, 2000
That's all well and good, but how are we supposed to stop threads that call code that
we haven't written? For instance, what if a thread is stalled out waiting for input from
a socket that never arrives? How do we tell the socket code to "cleanly" abort?

You can set a timeout on the socket to gain control...


Author: Ingo Proetel (http://www.jguru.com/guru/viewbio.jsp?EID=46144), May 10,
2000
You can set a timeout on the socket to gain control again. And then exit cleanly. And
as in the article above mentioned you could also destroy the socket. Such solutions
basically depend on the application.

See also Is it possible to interrupt a running thr...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 9, 2000
See also Is it possible to interrupt a running thread?

How can I create ThreadGroups in applets running in Netscape 4.7 without


generating security exceptions?
Location: http://www.jguru.com/faq/view.jsp?EID=46746
Created: May 9, 2000 Modified: 2000-09-14 08:26:34.71
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Rob Edmondson
(http://www.jguru.com/guru/viewbio.jsp?EID=35309

Sign your code and enable UniversalThreadGroupAccess.


PrivilegeManager.enablePrivilege("UniversalThreadGroupAcces
s");
For a full list of the targets and what tasks they provide access to see
http://developer.netscape.com/docs/manuals/signedobj/targets/index.htm.

What is the difference between sleep(), wait() and suspend()?


Location: http://www.jguru.com/faq/view.jsp?EID=47127
Created: May 10, 2000 Modified: 2000-05-17 12:35:33.37
Author: Ingo Proetel (http://www.jguru.com/guru/viewbio.jsp?EID=46144) Question
originally posed by Venkata Reddy Vajrala
(http://www.jguru.com/guru/viewbio.jsp?EID=3588

Thread.sleep() sends the current thread into the "Not Runnable" state for some
amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is
currently in a synchronized block or method no other thread can enter this block or
method. If another thread calls t.interrupt() it will wake up the sleeping thread.

Note that sleep is a static method, which means that it always affects the current
thread (the one that is executing the sleep method). A common mistake is to call
t.sleep() where t is a different thread; even then, it is the current thread that will
sleep, not the t thread.

t.suspend() is deprecated. Using it is possible to halt a thread other than the


current thread. A suspended thread keeps all its monitors and since this state is not
interruptable it is deadlock prone.

object.wait() sends the current thread into the "Not Runnable" state, like
sleep(), but with a twist. Wait is called on a object, not a thread; we call this object
the "lock object." Before lock.wait() is called, the current thread must synchronize on
the lock object; wait() then releases this lock, and adds the thread to the "wait list"
associated with the lock. Later, another thread can synchronize on the same lock
object and call lock.notify(). This wakes up the original, waiting thread. Basically,
wait()/notify() is like sleep()/interrupt(), only the active thread does not need a
direct pointer to the sleeping thread, but only to the shared lock object.

[This answer was edited; the original answer was clear but I felt I should expand on
some points; please blame me, not Ingo, for any errors. -Alex]

Comments and alternative answers

I just want to say, that wait releases the lock, while...


Author: Rima Kilany (http://www.jguru.com/guru/viewbio.jsp?EID=263108), Feb 22,
2001
I just want to say, that wait releases the lock, while suspend and sleep don't.

Strange problem of using wait() and sleep() to suspend a single thread.


Author: Carfield Yim (http://www.jguru.com/guru/viewbio.jsp?EID=4648), Dec 4,
2001
I have write a simple mobile agents clients that continuously request a server for
thousands time to do some testing. For testing propose, I need there is a random time
delay between each request. At first I use the following code to do:
synchronized(this)
{
for(int i=0;
i<Integer.MAX_VALUE; i++)
{
String fileName =
"file"+(int)(random.nextGaussian()*100);
print("sending
message"+fileName);

proxy.sendAsyncMessage(new Message("request", fileName));


wait( (long)(
Math.abs(random.nextGaussian()*1000) ) );
}
}

However, the mobile agents hing after ~7000 request. If I change wait() to
Thread.sleep(), seen there is no this problem. (May be I need more testing). Can
anyone tell me what is the problem when using wait()? As there is only one thread of
client, no other thread access it and it don't share common resource with other thread.

What is "starvation" when used in the context of the Java threading model?
Location: http://www.jguru.com/faq/view.jsp?EID=47379
Created: May 10, 2000 Modified: 2000-05-10 15:53:18.344
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Vijaybabu Srinivasan
(http://www.jguru.com/guru/viewbio.jsp?EID=18984

Starvation is when the Java runtime (JVM) doesn't allocate time to a thread to
execute. This may be due to a poor scheduling algorithm (like green Threads under
Solaris, where a for loop from 1 to 1 million doing something CPU intensive wouldn't
yield the CPU under Solaris but would under Windows), poor programming practice
(not returning from the paint() method in an applet), or a hostile attack (like hitting
a host with a denial of service attack where the CPU is busy outside the Java
process).
Comments and alternative answers

Thread starvation can easily arise in a poorly designed...


Author: Richard Beton (http://www.jguru.com/guru/viewbio.jsp?EID=53882), May
23, 2000
Thread starvation can easily arise in a poorly designed threaded program. Java can be
prone to this because of the way 'notify' works. A good illustration of thread starvation
is Peter Welch's "wot no chickens?"
(http://wotug.ukc.ac.uk/parallel/groups/wotug/java/discussion/3.html).

Useful follow-up can be found at the JCSP page. Using CSP in your design, you can
reason about and prevent thread starvation.

A more common reason for starvation is poor thread...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 26,
2000
A more common reason for starvation is poor thread priority strategies. If one thread
has a high priority, is very busy, and never blocks, then all threads with a lower
priority will starve.

To avoid thread starvation, a useful (if somewhat counter-intuitive) rule of thumb is:
give threads with a lot to do (e.g. calculator threads) low priorities; and give threads
with a little to do (e.g. IO-bound threads) high priorities. That way the high-priority
threads wake up, do their thing, and go back to sleep, allowing the low-priority
threads time to grind through their tasks. Using the Java IO libraries, this blocking
and waking happens automatically, so all you have to do is set the priority for your
threads at the outset.

Thread calculator;
Thread loader;
public void startThreads() {
calculator = new CalculatorThread();
calculator.setPriority(Thread.NORM_PRIORITY-1);
loader = new LoaderThread( getInputStreamFromSomewhere() );
loader.setPriority( Thread.NORM_PRIORITY+1 );
calculator.start();
loader.start();
}

What is the difference between a lightweight and a heavyweight process?


Location: http://www.jguru.com/faq/view.jsp?EID=53657
Created: May 22, 2000 Modified: 2000-08-04 12:28:36.316
Author: Nick Maiorana (http://www.jguru.com/guru/viewbio.jsp?EID=1432) Question
originally posed by bhaskar ramaraju
(http://www.jguru.com/guru/viewbio.jsp?EID=30638

[Short answer: threads are lightweight, programs (aka processes or tasks) are
heavyweight. -Alex]

Lightweight and heavyweight processes refer the mechanics of a multi-processing


system.

In a lightweight process, threads are used to divvy up the workload. Here you would
see one process executing in the OS (for this application or service.) This process
would posess 1 or more threads. Each of the threads in this process shares the same
address space. Because threads share their address space, communication between
the threads is simple and efficient. Each thread could be compared to a process in a
heavyweight scenario.

In a heavyweight process, new processes are created to perform the work in parallel.
Here (for the same application or service), you would see multiple processes
running. Each heavyweight process contains its own address space. Communication
between these processes would involve additional communications mechanisms such
as sockets or pipes.

The benefits of a lightweight process come from the conservation of resources. Since
threads use the same code section, data section and OS resources, less overall
resources are used. The drawback is now you have to ensure your system is thread-
safe. You have to make sure the threads don't step on each other. Fortunately, Java
provides the necessary tools to allow you to do this.

See also:

• What is the difference between a thread and a process?

Is there any way to communicate between two classes within an application


using InputStreams and OutputStreams?
Location: http://www.jguru.com/faq/view.jsp?EID=54012
Created: May 22, 2000 Modified: 2000-05-23 18:28:32.671
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sean Wiechman
(http://www.jguru.com/guru/viewbio.jsp?EID=53867

The PipedInputStream/PipedReader and PipedOutputStream/PipedWriter streams


provide synchronized I/O across threads, from within one class or multiple classes.

The following example demonstrates their usage and was taken from my Mastering
Java 2 book:

import java.io.*;

public class PipeTest {


public static void main (String args[]) {
new OilRefinery();
try { // delay arrival
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
}
new SuperTanker();
}

// This class consists of a Thread that can accept


"pipline" hook-ups
// via the "clickClunk" method. Clients have to find us
though from
// our Thread name "ThePipeTerminal"
static class OilRefinery extends Thread {
static final int EOF = -1;
boolean alone = true;
// Can't connect piped until "clickClunk"
PipedReader inPipe;
PipedWriter outPipe;

public OilRefinery() {
start(); // Start the thread
}

public synchronized void run() {


int ch;
// Open for business
setName ("ThePipeTerminal");
System.out.println ("Processing plant operational and
on-line");
while (alone) {
try {
wait(); // Non-busy wait for connection
} catch (InterruptedException ohLeaveMeAlone) {
}
}
System.out.println ("Client arrived");
// At this point, a client has connected up to the
pipes
// so process the flow of oil
try {
while ((ch = inPipe.read()) != EOF) {
// add some value to raw input...
outPipe.write (Character.toUpperCase((char)ch));
}
} catch (IOException pipeMalfunction) {
}
try {
outPipe.close(); // signal client "The show's
over!"
} catch (IOException ignored) {
}
alone = true;
System.out.println ("Processing plant shutting
down.");
}
// This is the method clients have to call to connect
up to
// the processing plant
public synchronized boolean clickClunk (PipedWriter
clientOutputPipe,
PipedReader
clientInputPipe) {
System.out.println ("Client arrives to hook-up its
pipes");
try {
inPipe = new PipedReader (clientOutputPipe);
outPipe = new PipedWriter (clientInputPipe);
} catch (IOException connectionFailed) {
System.err.println ("Hook up failed");
return false;
}
System.out.println ("Hook-up successful");
alone = false;
notify();
return true;
}
} // End of class OilRefinery

// This class implements a processing plant client, say a


// supertanker that arrives at the plant to unload its
// crude oil and load up with refined oil
static class SuperTanker {
OilRefinery pipeTerminal = null;
PipedReader returnPipe = new PipedReader();
PipedWriter crudePipe = new PipedWriter();

public SuperTanker() {
pipeTerminal = (OilRefinery) findThread
("ThePipeTerminal");
if (pipeTerminal == null) {
System.err.println ("Snow blizzards prevent
rendezvous");
System.exit (100);
} else {
if (pipeTerminal.clickClunk (crudePipe,
returnPipe)) {
haveOilProcessed();
} else {
System.err.println ("Failed to connect to
processing plant");
}
try {
crudePipe.close();
} catch (IOException brokenValves) {
System.err.println ("Couldn't close valves!");
}
}
}
// Send data (oil) to processing plant, which refines
data and
// sends it back via second pipe stream
public void haveOilProcessed() {
String oilToBeRefined = "Crude Oil";

try {
crudePipe.write (oilToBeRefined);
crudePipe.close();

// Get back refined oil


int ch;
while ((ch = returnPipe.read()) != -1) {
System.out.print ((char)ch);
}
System.out.println();
} catch (IOException oilFlowFailure) {
System.err.println ("Pipe malfunction");
}
}

// This generic method locates the refinery thread


// Note that threads may start/end while checking
public Thread findThread (String target) {
int SAFETY_MARGIN = 10;
// Find master ThreadGroup which all others descend
ThreadGroup rootGroup =
Thread.currentThread().getThreadGroup();
while (rootGroup.getParent() != null) {
rootGroup = rootGroup.getParent();
}
Thread threadList[] =
new Thread [rootGroup.activeGroupCount() +
SAFETY_MARGIN];
int count = rootGroup.enumerate (threadList);
Thread aThread;
for (int i=0;i<count;i++) {
aThread = threadList[i];
if (aThread == null)
continue;
if (aThread.getName().equals (target)) {
return aThread;
}
}
return null;
}
} // End of class SuperTanker
} // End of class PipeTest
Comments and alternative answers

I have found it immensely more practical to share ...


Author: Bret Hansen (http://www.jguru.com/guru/viewbio.jsp?EID=27595), May 28,
2000
I have found it immensely more practical to share objects rather than serializing data
between threads. For they share the same memory space. It is easier to code and you
will get better performance. If I was to extrapolate from the examples that I have seen
of PipedReader/PipeWriter and PipeInputStream/PipedOutputStream, I would be
serializing collections and classes that were composed of many other objects just to
hand it to another thread. Serialization also complicates the scenario if there are
multiple threads sending data to a single thread. I find the following a better way of
implementing inter-thread communication:
import java.io.*;
import java.util.*;

// class with main entry point. Creates the refinery and tanker(s).
public class Pipeline
{
public static void main (String args[])
{
OilRefinery.create();

// sleep a bit for dramatic purposes


try { Thread.sleep(500); } catch (InterruptedException e) { }
new SuperTanker("Tanker #1");

// sleep a bit for dramatic purposes


try { Thread.sleep(500); } catch (InterruptedException e) { }
new SuperTanker("Tanker #2");

// sleep for a while and then shutdown


try { Thread.sleep(5000); } catch (InterruptedException e)
{ }
OilRefinery.getRefinery().refine( new Request( "shutdown"
) );
}
}

class Request
{
String message;
Requestor requestor;

Request( String message )


{
this( message, null );
}

Request( String message, Requestor requestor )


{
this.message = message;
this.requestor = requestor;
}
}

interface Requestor
{
void response( String responseMessage );
}

// This is the refinery


class OilRefinery
extends Thread
{
private static OilRefinery cRefinery = null;

private LinkedList mConnectQue;


private boolean keepRefining;

private OilRefinery()
{
mConnectQue = new LinkedList();
keepRefining = true;

// This class is a self starting thread


start();
}

public static OilRefinery create()


{
if ( cRefinery == null )
{
cRefinery = new OilRefinery();
}

return cRefinery;
}

public static OilRefinery getRefinery()


{
return create();
}

public void refine( Request request )


{
synchronized ( mConnectQue )
{
mConnectQue.add( request );
mConnectQue.notify();
}
}

public void run()


{
// Open for business
System.out.println ("Refinery is now operational");
while (keepRefining)
{
Request request;

synchronized ( mConnectQue )
{
while ( mConnectQue.size() == 0 )
{
try
{
mConnectQue.wait();
}
catch ( InterruptedException e )
{
}
}

request = (Request) mConnectQue.removeFirst();


}

processRequest( request );
processRequest( request );
}

System.out.println ("Processing plant shutting down.");


}

private void processRequest( Request request )


{
System.out.println ("Client request arrived -> '" +
request.message + "'");

if ( request.message.equalsIgnoreCase("shutdown") )
{
keepRefining = false;
return;
}

if ( request.requestor != null)
{
String responseMessage = request.message.toUpperCase();

request.requestor.response( responseMessage );
}
}
}

// This class is a SuperTanker


// supertanker that arrives at the plant to unload its
// crude oil and load up with refined oil
class SuperTanker extends Thread
implements Requestor
{
static final int TankFulls = 5;
String name;

public SuperTanker(String name)


{
this.name = name;
setDaemon( true );
start();
}

public void run()


{
OilRefinery refinery = OilRefinery.getRefinery();

for (int i=0; i<TankFulls; i++)


{
String message = "Oil from " + name + " tank #" + i;
System.out.println( "Sending message to refinery of " +
message );
refinery.refine( new Request( message, this ) );

try { Thread.sleep(500); } catch (InterruptedException e)


{ }
}
}

public void response( String responseMessage )


{
System.out.println( "Received refined response of " +
responseMessage );
}
}

Re: I have found it immensely more practical to share ...


Author: Mahesh Kondwilkar
(http://www.jguru.com/guru/viewbio.jsp?EID=957437), Oct 20, 2002
Actually, as an aside, the PipedReader/Writer mechanism works very well in some
applns, for example when you want to create tons of XML data AND also apply
some XSLTs on them... you could pipe out your XML to xslt applier threads as the
xml is created... a huge saving of space...

Are there any good mailing lists to discuss multi-threading design issues?
Location: http://www.jguru.com/faq/view.jsp?EID=54283
Created: May 23, 2000 Modified: 2000-05-26 16:23:38.557
Author: Richard Beton (http://www.jguru.com/guru/viewbio.jsp?EID=53882)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

I am on the Java-Threads mailing list, hosted at University of Kent at Canterbury


(java-threads@ukc.ac.uk). This is a fairly quiet list but the quality of advice is
typically very good. Broadly, the stance taken is that of simplifying thread
programming by using the CSP model (using either JCSP or CJT libraries). This
approach does well for hiding some of the tricky details of thread synchronisation
whilst not costing a big performance hit. It draws on the lessons learned in the '80s
with the Occam programming language.

See http://wotug.ukc.ac.uk/list.shtml for more info.

What should you do such that an RMI server program can accept multiple
clients and actually parallelize their execution?
Location: http://www.jguru.com/faq/view.jsp?EID=55767
Created: May 24, 2000 Modified: 2000-05-26 16:26:38.772
Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381) Question
originally posed by Massimiliano Bigatti
(http://www.jguru.com/guru/viewbio.jsp?EID=39645

Well first theres nothing you can do explicitly for this. This IS the way it works.
Multiple client calls to the same object are NOT queued up but concurrent method
invocations on an RMI object are automatically executed in separate threads as
necessary. Serial invocations from the same client are processed in the same thread
as an optimization.

According to the rmi specs


> "A method dispatched by the RMI runtime to a
> remote object implementation (a server) may or may not execute in a
> separate thread. Some calls originating from the same client virtual
> machine will execute in the same thread; some will execute in different
> threads. Calls originating from different client virtual machines will
> execute in different threads. Other than this last case of different
> client virtual machines, the RMI runtime makes no guarantees with
> respect to mapping remote object invocations to threads. "

What this means is that if you are maintaining state in the object between method
calls or need syncronization, then the remote method must be synchronized in the
interface, or it should use synchronizing in its implementation with
synchronize(object){code...}

It also means that that this method will be executed with the lock acquired for the
implementation object (not the stub or skeleton). In this case, even though the
invocations from the two clients are executed in separate threads, the execution of
the method will indeed be mutually exclusive because of the lock on the
implementation object.

[In other words, the remote object must be thread-safe. -Alex]

Comments and alternative answers

I think that if RMI calls from the same JVM are packed...
Author: jerry chin (http://www.jguru.com/guru/viewbio.jsp?EID=60541), Jun 7, 2000
I think that if RMI calls from the same JVM are packed into one thread, it can not be
thread-safe. Because client may have multiple threads in one JVM, and in each thread
it can call remote methods. In such a condition, the call sequence from different
thread is not determined when they are put to one thread. If these calls change some
status of server, then the result returned to each thread is not determined too.

"Serial invocations from the same client are ...


Author: Ashwin Desai (http://www.jguru.com/guru/viewbio.jsp?EID=98195), Jul 7,
2000
"Serial invocations from the same client are processed in the same thread as an
optimization. " Is this true for only Suns VM or does it hold good for all VMs? for
e.g.

• a client making 3 calls to the server every 5 secs


• a client making 3 calls to the server every 1 min.

In the above 2 cases, the client makes method invocations on the server serially, but at
different intervals aof time. Does the RMI runtime still use the same thread for both
cases?

This behavior is unspecified so it may change at any...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 9, 2000
This behavior is unspecified so it may change at any time, Sun VM or not. Read the
spec (esp. the part quoted in the answer). The safest thing is to just synchronize on
sensitive code blocks, making your object thread-safe. Do *not* try to use
ThreadLocal or anything else like that.

According to Section 3.2 on RMI specs (latest) pag...


Author: Rahul Matta (http://www.jguru.com/guru/viewbio.jsp?EID=2457), Sep 24,
2000
According to Section 3.2 on RMI specs (latest) page:

http://java.sun.com/products/jdk/1.2/docs/guide/rmi/spec/rmiTOC.doc.html

"A method dispatched by the RMI runtime to a remote object implementation may or
may not execute in a separate thread. The RMI runtime makes no guarantees with
respect to mapping remote object invocations to threads. Since remote method
invocation on the same remote object may execute concurrently, a remote object
implementation needs to make sure its implementation is thread-safe."

What I understand from this is - even different client requests could be on same thread
.. serializing all the requests in effect .. correct me if I am wrong..

But, according to the old specs on:

http://java.sun.com/products/jdk/1.1/docs/guide/rmi/spec/rmiTOC.doc.html

"A method dispatched by the RMI runtime to a remote object implementation (a


server) may or may not execute in a separate thread. Some calls originating from the
same client virtual machine will execute in the same thread; some will execute in
different threads. Calls originating from different client virtual machines will execute
in different threads. Other than this last case of different client virtual machines, the
RMI runtime makes no guarantees with respect to mapping remote object invocations
to threads. "
This is what I like :) Since, it solves my purpose of multi-threads for different clients.
In fact this is more precise as it talks about different VM clients and same VM clients.

Can some one verify or confirm what exactly happens in the latest RMI for clients on
different VMs????

Thanks,
-Rahul
P.S. If possible send a cc of reply to me at rahul@matta.net

How can I wake a thread that is blocked on a call to InputStream.read()?


Location: http://www.jguru.com/faq/view.jsp?EID=59535
Created: May 29, 2000 Modified: 2001-08-18 17:24:12.659
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Tim Murphy
(http://www.jguru.com/guru/viewbio.jsp?EID=57829

(...or any other IO method that wraps read(), like BufferedReader.readLine(). Calling
thread.interrupt() does nothing.)

You can't. That's the way it's supposed to work.

One workaround is to use a non-blocking input stream. Such a stream would call
in.available() to check for the number of bytes that can currently be read without
blocking. If the number is zero, or is less than the size of the data you're expecting,
then you can go on with your business in the rest of the program. One disadvantage
to this technique is that you must poll for input; one big advantage to the standard
block-on-read threads is that they process data as soon as it is availalble.

See Purpletech Code for source code to


com.purpletech.io.NonBlockingInputStream.

See the new (Java 1.4) java.nio.channels package for non-blocking I/O
support.

How do I detect end of stream in a non-blocking manner when reading a


stream through URL/URLConnection, if available() reports nothing to read
on end of stream?
Location: http://www.jguru.com/faq/view.jsp?EID=72378
Created: Jun 11, 2000 Modified: 2002-03-25 10:37:55.456
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by ceri jerome
(http://www.jguru.com/guru/viewbio.jsp?EID=67121
In the fully general case, you can't (since the client can just keep sending you data).
Given that Java doesn't have asynchronous I/O (yet), you need to design your
system to take into account the potentially blocking nature of the I/O. Also, if you do
the I/O in a separate thread then you also have to deal with the issue of properly
and safely being able to stop your thread if the I/O fails.

In terms of doing URL stuff, I suggest that you look at the HTTPClient package.

In terms of threading, you should definitely look at Doug Lea's util.concurrent


package. Also, of course, check out the jGuru Threads FAQ for more information
about threads.

Java 1.4 supports non-blocking I/O now.

What happens to multithreading in java if the operating system does not


support it?
Location: http://www.jguru.com/faq/view.jsp?EID=74406
Created: Jun 17, 2000 Modified: 2000-06-17 12:29:15.218
Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588)
Question originally posed by Anand Naik
(http://www.jguru.com/guru/viewbio.jsp?EID=44857

In this case, the Java Virtual Machine will typically simulate the threading model,
although it's up to the JVM vendor how they support it. ["Green threads" is the name
of the standard thread-simulation algorithm, used by most VMs, including Sun's on
platforms without native thread support. -Alex]

How can I synchronize access to my service object so that multiple clients


may have read-only access, but a client that needs to write gets exclusive
access?
Location: http://www.jguru.com/faq/view.jsp?EID=89158
Created: Jun 27, 2000 Modified: 2000-06-27 21:44:52.434
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)

Jini 1.1 includes a utility class called com.sun.jini.thread.ReadersWriter which


implements reader-writer locks. You may use this class as a barrier - surrounding all
critical sections in your accessor code by readLock()/readUnlock() and all critical
sections in your mutator code by writeLock()/writeUnlock().

This pattern, "Readers and Writers", is used in the common situation where you need
to prevent simultaneous reads and writes but want to allow multiple simultaneous
reads. Straight synchronization of the accessor and mutator methods would not allow
this - it would exclude multiple read methods from executing concurrently, creating a
thread-safe object but drastically decreasing the object's liveness.

What is the meaning of calling a method or object "thread-safe?"


Location: http://www.jguru.com/faq/view.jsp?EID=94626
Created: Jul 3, 2000 Modified: 2000-07-03 14:45:59.577
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by RadhaKrishna Yenugula
(http://www.jguru.com/guru/viewbio.jsp?EID=76338
Basically, calling a method "thread-safe" means that even if multiple threads try to
access it simultaneously, nothing bad happens. Here "bad" usually means that due to
race conditions, or deadlock, or other pitfalls, the object's state gets corrupted, or its
methods produce unreliable results. A method usually acheives thread-safety by
protecting access to shared resources. This usually translates to using the Java
synchronized keyword to protect blocks of code that access instance variables, or
other shared variables.

For an object to be thread-safe, it must be possible for multiple threads to


simultaneously access the same method, or multiple methods, in that object. Usually
this is acheived by assuring that each method is thread-safe, but this doesn't always
suffice, since methods can call each other in strange ways, leading to deadlock and
other weirdness.

It is very difficult to prove that an object is thread-safe. The main rule of thumb for
making thread-safe objects is, "Make all the instance variables private, and all
the public accessor methods synchronized." However, this is sometimes difficult
to achieve in practice, due to exigencies of performance, architecture, or
implementation.

Accurate multithreaded programming is a true art, and very difficult to master. Read
"Java Threads" by Oaks and Wong, and "Concurrent Programming in Java" by Lea,
for inspiration in your quest to become a thread-safe programmer.

Comments and alternative answers

See Designing for Thread Safety: When and How to Use...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 14, 2000
See Designing for Thread Safety: When and How to Use Synchronization, Immutable
Objects, and Thread-Safe Wrappers by Bill Venners for an excellent discussion of
thread safety with good examples.

What is Apartment Threading, and how does it apply to Java?


Location: http://www.jguru.com/faq/view.jsp?EID=94381
Created: Jul 3, 2000 Modified: 2000-07-03 14:52:37.187
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sudipto sarkar
(http://www.jguru.com/guru/viewbio.jsp?EID=80921

Apartment threading is a threading model used by Microsoft with COM/ActiveX


objects. You can read about it in Microsoft's technical note at
http://support.microsoft.com/support/kb/articles/q150/7/77.asp.

It has nothing to do with Java.

Is it possible to interrupt a running thread? InterruptedException is only


thrown if the thread is interrupted while in the sleep state and calling
interrupt() on a running thread has no effect.
Location: http://www.jguru.com/faq/view.jsp?EID=98022
Created: Jul 7, 2000 Modified: 2000-08-11 13:06:47.106
Author: Larry Widing (http://www.jguru.com/guru/viewbio.jsp?EID=96408) Question
originally posed by Marcus Edwards
(http://www.jguru.com/guru/viewbio.jsp?EID=35910

[More info from the questioner:

Consider a long running task that is not loop based. How can you "cancel" the task
before it reaches the end of the run() method and without having to check a boolean
active flag on each line of run()?

Consider:

public void run() {


try {
// long-running, non-repetitive task
}
catch(InterruptedException e) {
// handle the interruption or cancel
}
}

As intuitive as this seems, the InterruptedException is only thrown if the thread is


interrupted while in the sleep state and calling interrupt() on a running thread has no
effect. I'd like a way to interrupt a running thread.]

It is best to not rely on this feature, as it does not always work, even if the thread is
in a sleep state. I have found that several versions of Netscape completely ignore
Thread.interrupt(). For this reason, the only truly effective means to stop a running
thread is to use a combination of locks and state flags.

I know this is not an ideal answer, but there really is not one available for this issue.
Use something along the lines of:

class Test extends Thread


{
boolean stopThis = false;
public void run()
{
while (!getStopThis())
{
// some operations

// insert the following at various points


// in the thread processing.
if (getStopThis())
break;
}
}
public boolean getStopThis()
{
return stopThis;
}

public void stopThisNow()


{
stopThis = true;
}
}

You will need to balance the number of times you call getStopThis(), as synchronized
calls can quickly become a major performance bottleneck. Therefore, in a situation
like this it becomes important to balance performance with responsiveness to a
request to stop the thread. [Note: the accessor methods do not need to be
synchronized, since boolean set/get are guaranteed to be atomic. This removes the
performance problems, but still leads to more complicated code, and you may still
end up waiting quite a while between the "stopThisNow()" call and the time when the
thread actually stops.]

I usually put such calls before anything that might perform some kind of I/O
(updating the display, writing to a file, reading from a file, etc).

See also How do I properly stop a running thread, now that Thread.stop() has been
deprecated?.

Comments and alternative answers

The Threading FAQ mentions that "Java native ...


Author: Marcus Edwards (http://www.jguru.com/guru/viewbio.jsp?EID=35910), Jul
10, 2000
The Threading FAQ mentions that "Java native thread implementations are usually
preemptive". See http://www.jguru.com/jguru/faq/view.jsp?EID=42151

In a pre-emptive, multi-tasking environment surely we should be able to set some


low-level property, the thread priority maybe, of the thread/task that can prevent the
scheduler from selecting our thread for activation again?

In a non-preemptive (co-operative), multi-tasking environment we don't have this


little luxury and are dependant on good programming practice.

From what I'm reading in this response and others I've sought on the 'net, it would
appear that it is almost impossible to pre-empt a thread. Am I correct in this?

An alternative solution to the problem would be do design "Runnable" atomic units


for the task and use a queue to process each unit in turn. This would allow the macro
process to be interrupted between execution of atomic units.

First, calling interrupt() on a thread that is not...


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Aug 8,
2000

First, calling interrupt() on a thread that is not sleeping does cause the next call
to sleep() by the thread to immediately throw an InterruptedException,
assuming the thread's interrupted flag has not been cleared.

Second, the reason some versions of Netscape don't throw an


InterruptedException is that some versions of Netscape are using a JDK 1.0.2
JVM. The interrupt mechanism was never completed for JDK 1.0.2, and hence in
JDK 1.0.2 Thread.sleep() never actually throws the
InterruptedException it is declared as throwing.

Third, in the second example, no synchronization is needed for the


getStopThis() and stopThisNow() methods. Reading or writing a boolean
field is inherently atomic and does not need to be protected by synchronization. A
better implementation of this technique is to declare stopThis as volatile and
just test it directly. [Fixed. But I prefer keeping it as an accessor method, on purely
aesthetic principles. -Alex]

Fourth, the while(getStopThis()) loop in the second example is wrong...it


should be while(!getStopThis()). [Fixed. -Alex]

The code in the answer is still not fixed.


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Oct 6,
2001
The third issue I made above has only been partially fixed in the code given for
the answer. (The comment from Alex states that the code has been fixed.) To make
the code correct the stopThis boolean field must be declared as volatile. This
is necessary to prevent the compiler or the processor from optimizing the code or
the processor from optimizing the execution to postpone the setting of stopThis.

Basically anytime one thread depends on another thread changing the value of a
field, in the abscence of synchronization the field must be declared as volatile.

How can I actually, really deallocate a Thread to release the memory?


Setting thread = null does not work!
Location: http://www.jguru.com/faq/view.jsp?EID=98080
Created: Jul 7, 2000 Modified: 2000-07-09 06:15:50.501
Author: Larry Widing (http://www.jguru.com/guru/viewbio.jsp?EID=96408) Question
originally posed by quartex 4quartex
(http://www.jguru.com/guru/viewbio.jsp?EID=58997

Using thread = null will not release a running thread. In order to release the memory
associated with a thread, you need to make sure that all of the following are done:

• Make sure that the thread's start() method has been called.
• Make sure that the thread has stopped executing.
• Clear any references to that Thread object (thread = null;).

This is the best you can do to ensure the release of memory for a Thread. You have
to call start() on the thread because several JVMs have a bug where they will not
release all the thread's memory if the thread is not started.

Comments and alternative answers

That sounds okay, but is there any way to inspect the...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 9, 2000
That sounds okay, but is there any way to inspect the VM (maybe through a thread
dump) and find out if it's really been GC'd? It seems like the above procedure doesn't
always work.

Sorry, but I tried the 3 steps before to send this...


Author: quartex 4quartex (http://www.jguru.com/guru/viewbio.jsp?EID=58997), Jul
19, 2000
Sorry, but I tried the 3 steps before to send this message and It doesn't work in NT and
Solaris enviroment with 1.2 and 1.3. The thread is death but not deallocated.... I'm
sure on this because I use JProfiler and It shows me all death Thread (and the relative
memory allocation..)

Once the references to an object have been cleaned...


Author: Cyril Bouteille (http://www.jguru.com/guru/viewbio.jsp?EID=271746), Jan
8, 2001
Once the references to an object have been cleaned up, the object becomes eligible for
GC but will not actually be GCed until the GC decides to run.

Thread deallocation and thread names


Author: mark robbins (http://www.jguru.com/guru/viewbio.jsp?EID=69035), May 31,
2001
My software needs a thread per element it manages & for convience each thread is
named with the name of that element e.g. Element1, Element2 My problem comes
when I start & stop a thread. (I let the thread die natuarally using a while(no Exit)
type loop. If I need to create a new thread for that object then the JVM complains that
the thread is already dead. Is there a way of clearing the thread details from the JVM
memory? I do have a potential work around but I don't really want to write it if I can
avoid it. I have done the three actions listed above (i.e. remove references, ensure
thread started and exited, set thread = null) but seem to have hit a problem.

How do wait and notify really work?


Location: http://www.jguru.com/faq/view.jsp?EID=98786
Created: Jul 9, 2000 Modified: 2000-07-09 06:12:19.215
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Summary:

1. consumer grabs lock ( synchronized (lock) )


2. consumer calls lock.wait(), releasing monitor lock (!!)
3. producer produces resource
4. producer grabs lock ( synchronized (lock) )
5. producer calls lock.notify()
6. consumer moves from idle to runnable state, waiting to grab lock
7. producer releases lock
8. consumer reaquires lock
9. consumer returns from lock.wait()
10. consumer consumes resource (still holding lock)
11. consumer releases lock

"Condition synchronization" is the technical name for delaying the execution of a


thread until a condition is satisfied. Normally, this condition signifies the completion
of another task, or that the object state is now valid again and it is safe to proceed.
Normally the thread doing the waiting is called the consumer, and the thread being
waited for is the producer.

Conditional delays would be easy to specify, but inefficient to implement as:

await(condition) statement;
Java chooses a simpler mechanism where the programmer must loop according to
the condition around a wait:

while ( !condition ) do wait();

Before calling wait() the consumer thread must acquire a lock on some object; it
then calls the wait() method of that lock object itself. This is hidden from view if the
lock object is the current object; in that case, we recommend that the programmer
explicitly use this.wait() to clarify that the lock is taken out on the current object.

We use a while-loop instead of an if-statement because there is no way to restrict a


notifyAll() to a particular condition. This thread may wake up even though a
different condition has changed. Also, after waking, a thread still may find the
condition unsatisfied because another thread had awakened ahead of it.

To awaken a waiting thread, another thread must acquire the same lock object
(using synchronized (lock)), and call notify() or notifyAll() on that lock. The
other thread then becomes runnable, and the next time it is awakened, it gets a
chance to grab the lock and return from the wait state. (However, this does not
happen immediately; the producer still holds the lock until the synchronized block
ends.)

Use of wait() and notify() is often confusing because programmers often do not have
a separate lock object. Instead, they either use the producer thread object, or the
resource object itself, as the lock object. This can be cleared up if you remember that
there are three players in this game: the producer thread, the consumer thread, and
the lock object.

For example, consider the simple problem of reading information from a blocking
queue where you want read operations to block waiting for information. Assume the
existence of a superclass Queue containing the add(), remove(), and isEmpty()
methods.

class BlockingQueue extends Queue {


public synchronized Object remove() {
// wait until there is something to read
while (this.isEmpty())
this.wait();
// we have the lock and state we're seeking
return super.remove();
}
public synchronized void add(Object o) {
super.add(o);
// tell waiting threads to wake up
this.notifyAll();
}
}

Notice that only one read can occur simultaneously because remove() is
synchronized.
Because the read operation is destructive (removes an element), it is proper that
only one simultaneous read occurs. Oftentimes, reads do not have side effects and
there is no theoretical reason to restrict access to a single simultaneous read. The
"readers and writers" problem is well known and is solved by having an object
control access to the database so that the read/write methods do not have to be
synchronized.

Comments and alternative answers

The example above can be improved somewhat if the...


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Jul 31,
2000

The example above can be improved somewhat if the assumption is made that there is
a one-to-one correspondence between add() and remove(). That is to say that
after each add(), exactly one remove() can occur. In this case, the more efficient
notify() can be used in place of notifyAll(). To ensure encapsulation is not
violated, a private captive object should be used for the lock. (Otherwise, if some
other code calls wait() on the queue, that thread might get the notify() call.)

The resulting class looks like:

class BlockingQueue extends Queue {
    private final Object lock = new Object();

    public Object remove() {
        synchronized (lock) {
            // wait until there is something to 
read
            while (this.isEmpty()) 
                lock.wait();
            // we have the lock and state we're 
seeking
            return super.remove();
        }
    }

    public void add(Object o) {
        synchronized (lock) {
            super.add(o);
            // tell waiting threads to wake up
            lock.notify();
        }
    }
}

How do I schedule a task to run at a certain time?


Location: http://www.jguru.com/faq/view.jsp?EID=99037
Created: Jul 9, 2000 Modified: 2000-07-10 23:40:47.057
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Use the schedule() method of the java.util.Timer class:

long now = System.currentTimeMillis();


Date whenToRun = new Date(now+millisecondsInFuture);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
// job code here
}
};
timer.schedule(task, whenToRun);
Comments and alternative answers

As of JDK1.2.2 there is no java.util.Timer class. There...


Author: Visesh S. V. (http://www.jguru.com/guru/viewbio.jsp?EID=36836), Jan 4,
2001
As of JDK1.2.2 there is no java.util.Timer class. There is a javax.swing.Timer class
which does not have a schedule method. [That's right; Timer was added to JDK 1.3.
-Alex]

Re: As of JDK1.2.2 there is no java.util.Timer class. There...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), May 21,
2001
That's right; Timer was added to JDK 1.3. See
http://www.jguru.com/faq/view.jsp?EID=99038 for advice on duplicating Timer's
functionality inside JDK 1.1 or 1.2.

How do I schedule a task to run repeatedly?


Location: http://www.jguru.com/faq/view.jsp?EID=99038
Created: Jul 9, 2000 Modified: 2000-07-10 23:41:26.619
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Use the scheduleAtFixedRate() method of the java.util.Timer class:

int initialDelay = 30000; // start after 30 seconds


int period = 5000; // repeat every 5 seconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
// job code here
}
};
timer.scheduleAtFixedRate(task, initialDelay, period);
Comments and alternative answers

I tried to use this code in an application with jdk...


Author: nicolas fillat (http://www.jguru.com/guru/viewbio.jsp?EID=55634), Aug 8,
2000
I tried to use this code in an application with jdk 1.1.8 but java.util.Timer does not
exist in this release. Which jdk includes it ?

Re: I tried to use this code in an application with jdk...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 6,
2002
JDK 1.2 (also known as Java 2 J2SDK 1.2)

The java.util.Timer class is new for Java 1.3. However,...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 9,
2000
The java.util.Timer class is new for Java 1.3. However, the functionality can be
duplicated in other versions of Java by writing the code yourself. Its only a new part
of the class library, not requiring any native code to implement. If you don't want to
write the code yourself, you can grab the ClockDaemon from Doug Lea's
util.concurrent package.

Has anyone managed to get the timer.scheduleAtFixedRate...


Author: Asante Bremang (http://www.jguru.com/guru/viewbio.jsp?EID=141912), Feb
9, 2001
Has anyone managed to get the timer.scheduleAtFixedRate to work from with in a
servlet, I have tried the following:
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
/**
* Simple demo that uses java.util.Timer to schedule a task to
execute
* once 5 seconds have passed.
*/

public class Repeat extends HttpServlet{


public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException, IOException
{
res.setContentType("text/html");
final PrintWriter out = res.getWriter();
out.println("
Tasks scheduled");
int initialDelay = 1000; // start after 30 seconds
int period = 2000; // repeat every 5 seconds
Timer timer = new Timer();
out.println("
Timer set");

TimerTask task = new TimerTask();


timer.scheduleAtFixedRate(new TimerTask ()
{
public void run()
{
out.println("
Task Run");
}
}, initialDelay, period);
}//end doGet
}
but it doesn't repeat the task.

Please help
Asante

Re: Has anyone managed to get the timer.scheduleAtFixedRate...


Author: Murray Brandon (http://www.jguru.com/guru/viewbio.jsp?EID=488773),
Sep 2, 2001
Maybe it's because your reference to timer is not static. When the timer variable
goes out of scope, the VM no longer has a reference to the thread and it can be
assumed a candidate for garbage collection, stopping your timer. Try making timer
a static in the servlet - I assume you only want one timer thread.

Re: Has anyone managed to get the timer.scheduleAtFixedRate...


Author: Stefan Hoehn (http://www.jguru.com/guru/viewbio.jsp?EID=527662),
Oct 25, 2001
I am noticing that you are starting the timer in the servlet which is probably a
thread, isn't it? I am wondering if it is allowed to create threads in a servlet engine
or application server?

Re[2]: Has anyone managed to get the timer.scheduleAtFixedRate...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 6,
2002
Yes, see Can I spawn a background thread from my servlet?

Application Servers
Author: davor hamilton (http://www.jguru.com/guru/viewbio.jsp?EID=785435),
Mar 6, 2002
i may be a simple html-er so i may be wrong, but my impression of servlets is that
they are born of a user request, deal with the request and then they die. if you want
any more done then you should send another request back to the servlet. dav

Re: Application Servers


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 6,
2002
No, sometimes you want things to keep happening on the server, even if the
user can't immediately see them.

Re[2]: Application Servers


Author: rajesh tiwari
(http://www.jguru.com/guru/viewbio.jsp?EID=268316), May 15, 2002
Try running this program it works, It's probably you are using in servlet so
you are facing the problem .
Jesh
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/ public class TestTime {
public static void main(String[] args) throws Exception {
TestTime t = new TestTime();
t.execute();
} private void execute() throws Exception {
System.out.println(" Tasks scheduled");
int initialDelay = 1000; // start after 30 seconds
int period = 2000; // repeat every 5 seconds
Timer timer = new Timer();
System.out.println(" Timer set");

timer.scheduleAtFixedRate(new TimerTask ()
{
public void run()
{
System.out.println("Task Run");
}
}, initialDelay, period);
}
}

Re: Has anyone managed to get the timer.scheduleAtFixedRate...


Author: Kathleen Kühmel (http://www.jguru.com/guru/viewbio.jsp?EID=395129),
Sep 22, 2003
I am using timer.scheduleAtFixeRate() in a Servlet to perform a task once a
day.
It works very well. I put the timer-code in the init-Method of the Servlet!

Kathleen

Check out JCronTab


Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Sep 4,
2003
Also check out JCronTab

What is a thread dump, how do I obtain one, and how do I read it?
Location: http://www.jguru.com/faq/view.jsp?EID=101138
Created: Jul 13, 2000 Modified: 2000-07-18 03:31:27.598
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

There is a very good article at JavaSoft regarding thread dumps and strack traces:
http://developer.java.sun.com/developer/technicalArticles/Programming/Stacktrace/i
ndex.html
Comments and alternative answers

See also this FAQ


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 17, 2000
See also this FAQ

What is the keyword volatile used for? What sort of situations should I use
volatile when developing a multi-threaded application?
Location: http://www.jguru.com/faq/view.jsp?EID=101876
Created: Jul 13, 2000 Modified: 2000-07-18 03:21:13.209
Author: Shashi Bhusan Thakur
(http://www.jguru.com/guru/viewbio.jsp?EID=101864) Question originally posed by
Paul Done (http://www.jguru.com/guru/viewbio.jsp?EID=94469

Volatile modifiers tells the compiler that the variable can be changed unexpectedly by
other part of programme. When you have nore than one thread and you expect any
thread can change the variable you should use volatile. This will tell the compiler to
check for the master copy of this variable. Mostly used for boolean flags.

[Would the compiler produce incorrect code if it *weren't* marked volatile? What
kind of optimizations can it perform if it knows it's volatile? -Alex]

Comments and alternative answers

I'm guessing that this means that member variables...


Author: Paul Done (http://www.jguru.com/guru/viewbio.jsp?EID=94469), Jul 18,
2000

I'm guessing that this means that member variables of a class could potentially be
'cached' in an area created specifically for each thread which uses a method of that
class. Is it only primitives which can be optimised in this way or can object references
(and objects themeselves) also be optimised in a similar manner?

Does this mean that all member variables belonging to 'multi-threadable' classes,
should be volatile, to be sure that all the classes' methods are thread safe. In the real
world java I have seen so far, I have never come accross a single usage of volatile, so
does this mean that the code is not thread safe or am I completely off the ball? :)

I am struggling to understand when I should and should not use volatile in a multi-
threaded application to (i) ensure that it is thread safe, (ii) promote maximum
optimisation by enbling 'thread-caching' of variables, and (iii) avoid the over-caution
of making everything volatile.

Use volatile to prevent the compiler from moving or...


Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Jul 31,
2000

Use volatile to prevent the compiler from moving or removing reads/writes to the
field through optimization. This typically takes the form of register variables being
used for object fields, but can also actually involve removing the code entirely.
Consider for example the following:

    class X implements Runnable {
        boolean flag = true;
        public void run () {
            while (flag)
                ;
            doSomething();
        }
    }

The compiler can see that the loop does not modify flag and does not call any
methods that might modify flag. The compiler can optimize this loop using code
motion to move the test out of the loop:
        public void run () {
            if (flag)
                while (true)
                    ;
            doSomething();
        }

This clearly has a different effect if the assumption is made by the programmer that
another thread would set flag to false. The loop is now infinite. (Note that polling
like this is not how to signal a thread in Java--use wait()/notify().)

However, if the loop makes any calls to methods (other than private or final methods
in the same class which the compiler can analyze statically) the compiler shouldn't
make any assumptions about the field not being modified.

So the only code that typically needs volatile is code that depends on another
thread changing a field during the execution of a method and having the new value
available. Most of the time, the issue is code that depends on other threads not
changing field values, which is why you see a lot more used of synchronized than
volatile.

Using volatile to force atomic treatment of double and long


Author: Kirill Fakhroutdinov (http://www.jguru.com/guru/viewbio.jsp?EID=501201),
Aug 4, 2003
Another reason to use volatile is defined in Java Language Specs, 17.4 Nonatomic
Treatment of double and long:

"If a double or long variable is not declared volatile, then ... they are treated as if they
were two variables of 32 bits each... Consequently, if two threads concurrently assign
distinct values to the same shared non-volatile double or long variable, a subsequent
use of that variable may obtain a value that is not equal to either of the assigned
values, but some implementation-dependent mixture of the two values."
"Meanwhile, programmers are cautioned always to explicitly synchronize access to
shared double and long variables."

So shared double and long fields should be either declared as volatile or the access to
the whole object should be synchronized.

What causes ThreadDeath to happen? I've noticed that Thread.sleep()


invokes them somehow. But why? How to avoid them?
Location: http://www.jguru.com/faq/view.jsp?EID=111175
Created: Jul 25, 2000 Modified: 2000-07-27 08:10:58.559
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Villu Ruusmann
(http://www.jguru.com/guru/viewbio.jsp?EID=60872

ThreadDeath is a special Java error that is caught by the runtime system to free
system resources used by a thread. You can't stop / avoid them. In fact, if you catch
them and don't rethrow them, your JVM won't continue to run well for long.

The runtime throws them to signal the 'death' of a thread, usually because the run()
method finished or because an unchecked interrupt was thrown.

How can I control which waiting thread is notified when I call notify()?
Location: http://www.jguru.com/faq/view.jsp?EID=111923
Created: Jul 26, 2000 Modified: 2000-07-27 05:32:49.134
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is no way to control which thread is notified when you call notify(). Neither
thread priorities nor order of entering wait() determine what is notified first.

[Any pattern you may notice is platform-specific and should not be relied upon.
-Alex]

Comments and alternative answers

Re: How can I control which waiting thread is notified when I call notify()
Author: Kishore Pamu (http://www.jguru.com/guru/viewbio.jsp?EID=1062589), Mar
3, 2003
Just to follow upon the answer, Why can't we call notify() on a particular thread? I
think we can't guarantee that notified thread will start running but sure we can notify.
Depending on the its priorty it may run or not. Please correct me. thanks

How much overhead is associated with management of a ThreadLocal object


? What is the overhead associated with -- the get() method on the object or
with the thread change ?
Location: http://www.jguru.com/faq/view.jsp?EID=113620
Created: Jul 29, 2000 Modified: 2000-07-29 05:26:13.256
Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602) Question
originally posed by Tom Moog (http://www.jguru.com/guru/viewbio.jsp?EID=57779

A ThreadLocal is implemented using a synchronized WeakHashMap with the Thread 


object as the key.

The time overhead for calling ThreadLocal.get() is essentially the synchronization


overhead (with potential for blocking other threads attempting to access the same
ThreadLocal) plus the WeakHashMap.get() overhead. A WeakHashMap is
implemented using a HashMap and the HashMap documentation describes the
performance characteristics of its methods.
The space overhead for a ThreadLocal can be divided into two categories: per
ThreadLocal overhead and per Thread overhead. The following probably tells you
more than you need or want to know regarding the size overhead for a thread local,
but since you asked...

When a ThreadLocal is instantiated, it creates the underlying synchronized


WeakHashMap with an initial capacity of 53. The synchronized WeakHashMap is a
wrapper Map class--which has five reference fields, including a mutex lock--wrapped
around a WeakHashMap. The WeakHashMap -- which has five reference fields -- in turn
creates a HashMap with the same capacity and a ReferenceQueue to keep track of
any GC'ed hash entries. The ReferenceQueue needs an object to use as a mutex lock
and a Reference field to hold the head of the queue. The HashMap--which has six
reference, three int and a float field--allocates an array of 53 initially null hash
entries. So assuming a 32-bit reference type on a 32-bit processor and a resulting 4-
byte overhead per object, instantiating a ThreadLocal should total:

ThreadLocal 4
synchronized wrapper Map 4
5 references 20
mutex lock object 4 + native mutex
lock
WeakHashMap 4
5 references 20
ReferenceQueue 4
mutex lock object 4 + native mutex
lock
2 references 8
HashMap 4
6 references 24
3 ints, 1 float 16
entry[53] 220
= 336 bytes + 2 native
mutex locks

The initial capacity of 53 means that the WeakHashMap will not need to be rehashed
to a larger size until 38 Threads have stored a value in the ThreadLocal. So the
39th Thread (assuming none have been GC'ed) will increase the per-ThreadLocal 
overhead. Each of the first 38 threads that access a value in the ThreadLocal will
have an entry added to the hash. ThreadLocal wraps each value before inserting it
in the hash so that the wrapper's hashCode() and equals() methods are used
instead of the value's. To be inserted in the weak hash the wrapper needs a WeakKey 
reference and a hash entry. The WeakKey has a reference and an int and the hash
entry contains three references and an int. So for each thread that accesses the
ThreadLocal, an additional:

Value wrapper 4
value reference 4
WeakKey 4
1 int 4
key reference 4
Hash entry 4
3 references 12
1 int 4
= 40 bytes

There is some additional overhead as threads are garbage collected in terms of both
space and time, but it's probably fairly inconsequential unless there are lots of short-
lived threads accessing the ThreadLocal.

Comments and alternative answers

New Java Version


Author: Terry Laurenzo (http://www.jguru.com/guru/viewbio.jsp?EID=706411), Apr
3, 2002
The above information sounds correct for java 1.2. In the 1.3 VM, however,
ThreadLocal is implemented to use a package private Map on the Thread class. This
means that it can be unsynchronized. Version 1.3 still has a relatively slow
Thread.currentThread() method, so it is not a lot faster than 1.2 in the uncontended
case, but can be significantly faster when there is high contention for ThreadLocals
because of the lack of synchronization.
I had some ThreadLocal dependent code that ran just fine on multi-processor 1.3
systems. I tried integrating it into a WebSphere 3.5 app(which uses Java 1.2) and
immediately noticed that the same amount of processing took 2-3 times longer when
the ThreadLocal features were enabled.
Java 1.3 fixed a lot of ThreadLocal problems. Java 1.4 makes it even better, but I don't
have any benchmarks.

What is the historical context of Java's thread model? For example, what's a
monitor?
Location: http://www.jguru.com/faq/view.jsp?EID=114574
Created: Jul 30, 2000 Modified: 2000-07-31 02:10:17.231
Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1)

Java programmers sometimes hear that Java's mutual exclusion mechanism is based
upon monitors. Here, I give the historical context for Java's thread model and define
monitor.

In the mid-1960's, E. Dijkstra invented the notion of a semaphore for implementing


mutual exclusion and signaling events and defined P and V operations to specify
critical sections. Unfortunately, semaphores are very low-level elements and
programs written with them are hard to read as both condition synchronization and
mutual exclusion are specified with the same mechanism. In the early 1970's, Tony
Hoare defined monitors, which provided a structured approach to exclusion and
condition synchronization. Monitors were eventually included in Concurrent Pascal,
Modula, and Mesa (at Xerox PARC) [And91]. A number of the PARC researchers that
worked on the Cedar/Mesa project now work at JavaSoft. Naturally, the Java thread
synchronization mechanism, which is monitor-based, evolved from Cedar/Mesa.

A monitor is chunk of data that can only be accessed through a set of routines. This
type of encapsulation is expressed as an object in today's terminology, although
monitors were designed like modules rather than instances of a class. A monitor's
access routines are guaranteed to execute in a mutually exclusive manner. Java
relaxes this constraint slightly to allow a class' methods to be explicitly specified as
synchronized, which always execute to completion.

Monitors use condition variables plus wait and signal statements to provide condition
synchronization. An accessor routine waits on a condition variable until awakened by
another thread executing a signal statement on that variable. Java has a simpler,
more efficient, condition synchronization scheme. A thread executes a wait() in a
method of some object and blocks until awakened. A call to notifyAll() awakens all
threads waiting on a signal for that object--there is no way to specify that only
certain threads are to be awakened (a call to notify() wakes up a single waiting
thread).

One can say that a monitor access routine acquires a lock on that monitor, which it
releases upon returning from that method. In this way, mutual exclusion is implicitly
achieved. Only synchronized Java methods acquire a lock on an object. A call to
wait() releases the lock, but will reacquire it as it is awakened by a notifyAll().
notifyAll() does not yield execution nor release its hold on an object's lock. The only
way to release a lock is by waiting or returning from a synchronized method.

As a final detail, note that some operations are atomic and, hence, do not require
synchronization of any kind. In Java, only assignments to primitives except long and
double are considered atomic.

[And91] Concurrent Programming: Principles and Practice by Gregory Andrews,


Addison-Wesley, Menlo Park, CA, 1991.

How does one read a thread dump? (Especially the first line, '"47"
(TID:0x1780818, sys_thread_t:0x9b4780, state:CW, native ID:0xd4)
prio=5', and the Monitor Cache Dump.)
Location: http://www.jguru.com/faq/view.jsp?EID=116556
Created: Aug 1, 2000 Modified: 2000-08-04 04:07:32.271
Author: Joel Nylund (http://www.jguru.com/guru/viewbio.jsp?EID=116551) Question
originally posed by Richard Friedman
(http://www.jguru.com/guru/viewbio.jsp?EID=85295

This article has the answers to all of your questions.


http://developer.java.sun.com/developer/technicalArticles/Programming/Stacktrace/i
ndex.html

-Joel

What is the difference between a thread and a process?


Location: http://www.jguru.com/faq/view.jsp?EID=119610
Created: Aug 4, 2000 Modified: 2000-08-04 12:27:38.965
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Deepak Kalra
(http://www.jguru.com/guru/viewbio.jsp?EID=99188

A process is an OS-level task or service. A thread runs "inside" a process and may be
virtual or simulated. Generally speaking, threads share resources like memory,
where processes each have their own separate memory area, and need to take more
elaborate steps to share resources.

Another name for thread is "lightweight process" to distinguish it from the


"heavyweight" system processes.

See also What is the difference between a lightweight and a heavyweight process?

How do you write a Thread-Safe Singleton?


Location: http://www.jguru.com/faq/view.jsp?EID=124425
Created: Aug 10, 2000 Modified: 2000-08-18 13:25:01.565
Author: John Kroubalkian (http://www.jguru.com/guru/viewbio.jsp?EID=1461)

I have written plenty of non-thread-safe Singletons but it wasn't until recently when
I tracked it down that I realized that thread-safety could be a big problem.

The problem is that in the typical Singleton implementation (at least the ones I've
seen) there is the ability to create multiple versions of the single instance...I know,
"But How?".

Well, in the getInstance() call the instance is checked for null, and then
immediately constructed if it is null, and then the instance is returned.

The problem is that the thread (Ta) making the call could swap-out immediately after
checking for a null. A subsequent thread (Tb) could then make a call to get the
instance and construct an instance of the Singleton. When the original thread (Ta) is
then swapped back in, it would construct and return a completely separate object.
BAD KITTY!

The following code snippet shows an example of a thread-safe Singleton.

package com.jgk.patterns.singleton;

public class JGKSingleton {

/* Here is the instance of the Singleton */


private static JGKSingleton instance_;

/* Need the following object to synchronize */


/* a block */
private static Object syncObject_;

/* Prevent direct access to the constructor


private JGKSingleton() {
super();
}
public static JGKSingleton getInstance() {

/* in a non-thread-safe version of a Singleton */


/* the following line could be executed, and the */
/* thread could be immediately swapped out */
if (instance_ == null) {

synchronized(syncObject_) {

if (instance_ == null) {
instance_ = new JGKSingleton();
}

}
return instance_;
}
}
NOTE: The 2nd check for if (instance_ == null) is needed to avoid making
another unnecessary construct.

Don't let this byte you! ;-)

Comments and alternative answers

Double-checked locking may fail


Author: John Dale (http://www.jguru.com/guru/viewbio.jsp?EID=241781), Oct 12,
2001
Even this is not reliable. See The "Double-Checked Locking is Broken" Declaration at
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

for analysis and alternatives.

Re: Double-checked locking may fail


Author: Paolo Crisafulli (http://www.jguru.com/guru/viewbio.jsp?EID=1187510),
Jul 21, 2004
What if the test is done with a boolean ?
if (!hasInstance_) {
synchronized(syncObject_) {
if (!hasInstance_) {
instance_ = new JGKSingleton();
hasInstance_ = true;
}
}
}

Not very elegant I guess, but shouldn't it be thread-safe ?


Re[2]: Double-checked locking may fail
Author: Paolo Crisafulli
(http://www.jguru.com/guru/viewbio.jsp?EID=1187510), Jul 21, 2004
Sorry, I just came across this article :

http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-double-p1.html

So the answer to my previous question seems to be no.

synchronize the whole method


Author: scot mcphee (http://www.jguru.com/guru/viewbio.jsp?EID=924673), Jun 23,
2002
Just make the method synchronised; i.e public static synchronized Singleton
getInstance() { // etc } Won't work distributed (eg J2EE) contexts though - remember,
it's on a per-JVM basis.

Re: synchronize the whole method


Author: Sascha Goldsmith
(http://www.jguru.com/guru/viewbio.jsp?EID=1097050), Jun 25, 2003
If you do not want a race condition with a null check, then simply initialize the
singleton in a static initializer and make it final. If an exception is thrown in the
static initializer, the singleton will never be available and should therefore be re-
mapped to a RuntimeException. Making the singleton read-only ensures that it will
be thread-safe, albeit with more limited functionality.
class Foo {

// Made final so singleton will be read-only


static final private Foo singleton;

// Static initializer
static {
try {
// Perform initialization here
}
catch (Throwable e) {
throw new RuntimeException(e.getMessage());
}
}

// Private constructor (per singleton pattern)


private Foo() {

// Returns instance of the singleton


static public Foo getInstance() {

return singleton;
}
}
Clustered singleton
Author: Cameron Purdy (http://www.jguru.com/guru/viewbio.jsp?EID=1261840), Sep
10, 2005
See this article for a suggestion of how to do a singleton in a cluster:
http://www.tangosol.net/forums/thread.jspa?forumID=6&threadID=82&messageID=140

Another article on why double-checked locking doesn't always work.


Author: Elijah Cornell (http://www.jguru.com/guru/viewbio.jsp?EID=968433), Jul
29, 2002
http://www-106.ibm.com/developerworks/java/library/j-dcl.html?dwzone=java

Re: Another article on why double-checked locking doesn't always work.


Author: Ashish Kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=132372),
Feb 10, 2003
Hi,
I would think to make the declration of the class as static like below
public class MyClass
{
private static MyClass instance ;
public static getInstance()
{
return instance;
}
}
This will create the instance as soon as the class is created and u will have only
one instance
Ashish

Re[2]: Another article on why double-checked locking doesn't always


work.
Author: Sriram Gopalan (http://www.jguru.com/guru/viewbio.jsp?EID=23852),
May 8, 2003
Your solution is correct. Your technique is known as an eager-initialized
singleton, while the more common technique is lazy-initialized. A couple of
points to note, however.

1. If the singleton initialization is heavy (in terms of time and/or other


resources) and it is used infrequently, then this may not be the best
solution, since the penalty is incurred at class load time, rather than the
first invocation of getInstance().
2. This cannot be used if the constructor throws any named exceptions. If
the constructor throws any runtime exception, it cannot be processed
either.

Re[3]: Another article on why double-checked locking doesn't always


work.
Author: Rajinikanth Sambasivan
(http://www.jguru.com/guru/viewbio.jsp?EID=1120443), Oct 8, 2003
Just one more point on not to make the singleton as a staic member... we
cant create the object if the constructor takes arguments..

What is the difference between threads and interrupts ?


Location: http://www.jguru.com/faq/view.jsp?EID=127180
Created: Aug 15, 2000 Modified: 2000-08-16 00:22:44.672
Author: Rob Edmondson (http://www.jguru.com/guru/viewbio.jsp?EID=35309)
Question originally posed by prisca zerlina
(http://www.jguru.com/guru/viewbio.jsp?EID=110347

A thread is a CPU's state of execution as it processes a set of instructions (also


referred to as a task). An interrupt is a condition that causes the CPU to store the
state of its current thread of execution to begin a more important task, or to begin or
resume the next task in a list of tasks. An interrupt handler is the set of CPU
instructions associated with any given interrupt (a PC has several types of
interrupts).

The confusing part is the fact that the thread of execution in an interrupt handler is
often referred to as an interrupt.

In short, a thread is a task and an interrupt is a signal used to queue a more


important task.

When and why is IllegalMonitorStateException thrown?


Location: http://www.jguru.com/faq/view.jsp?EID=128732
Created: Aug 16, 2000 Modified: 2000-08-16 22:14:57.553
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by shiva prasad
(http://www.jguru.com/guru/viewbio.jsp?EID=107760

According to the JavaDoc, IllegalMonitorStateException is thrown "to indicate that a


thread has attempted to wait on an object's monitor or to notify other threads
waiting on an object's monitor without owning the specified monitor."

As explained in How do wait and notify really work? , in order to call foo.wait()
or foo.notify(), the calling thread must own a lock on object foo. This exception
is thrown if you call it without a preceding synchronized (foo) {.

Is there a way in Java to check whether an object is locked (i.e. some


thread has it) in a non-blocking fashion? Is there an atomic operation that
would get the lock if it's available and bail immediately otherwise? Is there
a way to detect that a specific thread is waiting for a lock and interrupt it
out of that state?
Location: http://www.jguru.com/faq/view.jsp?EID=130261
Created: Aug 18, 2000 Modified: 2000-08-18 20:10:27.221
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Dima Rekesh
(http://www.jguru.com/guru/viewbio.jsp?EID=128456

No, no, and no. :-)

If you want more sophisticated control over concurrency in your application, you can
implement your own Lock class, built on top of the synchronized keyword. Such a
class can implement timeouts, back-off strategies, and the like. The O'Reilly Threads
book by Oaks and Wong has an example of doing this. Unfortunately, this would only
work for your own classes, not for classes you call that use the standard Java
mechanisms.

Comments and alternative answers

Yes it possible. you can make use of the wait() and...


Author: karuppanan rameshkumar
(http://www.jguru.com/guru/viewbio.jsp?EID=102591), Aug 19, 2000
Yes it possible. you can make use of the wait() and notify() method of the thread class
which may help you. Please try this and tell me.

[I don't think wait-notify will do this. Wait-notify requires more work, and is more for
thread-to-thread communication, moderated by a lock, than for lock manipulation per
se. See http://www.jguru.com/jguru/faq/view.jsp?EID=98786. -Alex]

You may also find Doug Lea's Concurrency library u...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 19,
2000
You may also find Doug Lea's Concurrency library useful.

What is deadlock? How can I eliminate it?


Location: http://www.jguru.com/faq/view.jsp?EID=132683
Created: Aug 23, 2000 Modified: 2000-08-24 16:40:50.322
Author: Stephen Leonard (http://www.jguru.com/guru/viewbio.jsp?EID=124606)
Question originally posed by Ravi kancharla
(http://www.jguru.com/guru/viewbio.jsp?EID=130192

A simple deadlock situation is one in which a two threads are waiting. Each thread
waiting for a resource which is held by the other waiting thread. [In Java, this
resource is usually the object lock obtained by the synchronized keyword.]

This deadlock situation can range from the above two thread situation to any number
of threads waiting in a circular fashion.
Many solutions to this well known problem have been defined over the years
including the large range of solutions to "The Dining Philosophers" problem.

Hope this can point you in the right direction.

Stephen ...

Comments and alternative answers

For an example, let's take a simple bank application....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 24, 2000
For an example, let's take a simple bank application. Consider the following:

class Account {
private int id;
private int balance;

public Account(int id) {


this.id = id;
}

public synchronized void deposit(int amount) {


this.balance += amount;
}

public synchronized void withdraw(int amount) {


this.balance -= amount;
}

public static void transfer(Account from, Account to,


int amount) {
synchronized (from) {
synchronized (to) {
from.withdraw(amount);
to.deposit(amount);
}
}
}
Imagine that there are two concurrent accesses to transfer, one doing transfer(a1, a2),
and one doing transfer(a2, a1). If the first thread swaps out after locking a1 but before
locking a2, then the second thread locks a2, we have deadlock. The second thread will
block on a1 (since the first thread has it already), and the first thread will block on a2
(since the second thread has it already).

Unfortunately, there is no universal solution. Some solutions include...

• Ordered lock acquisition. Change transfer() to


• public static void transfer(Account from, Account
to, int amount) {
• Account first;
• Account second;
• if (a1.id < a2.id) {
• first = a1; second = a2;
• }
• else {
• first = a2; second = a1;
• }
• synchronized (first) {
• synchronized (second) {
• from.withdraw(amount);
• to.deposit(amount);
• }
• }
• }

This type of solution will work for any number of locks, assuming that there's
some way to consistently order them. In this case, we know that each object
has an immutable id variable; since it's an int, it's got built-in ordering.

• Encapsulation (“forcing directionality”) Design your program so the only


access to a thread-unsafe object is through a thread-safe object.

• Spawn new threads to handle each part of the transaction. If each thread only
locks one object at a time there can be no deadlock.

• Check and back off If you can test to see if another thread has a lock you
want, you can "back off" instead of locking it, allowing it to complete its
transaction before trying again. This can't be done with normal Java locks, but
you can try to write your own lock object to satisfy them.

• Timeout If you write your own lock object, it can automatically return from
the "lock" method if a certain amount of time elapses.

• Minimize or remove synchronization If there's no locks, there's no deadlock!

These solutions must be applied to your particular needs; sometimes it will be


impossible to use one or more of them. See Doug Lea's Concurrent Programming in
Java for more details.

Deadlock is one of four particular hazards facing ...


Author: Richard Beton (http://www.jguru.com/guru/viewbio.jsp?EID=53882), Sep
14, 2000
Deadlock is one of four particular hazards facing designers of multi-threaded
programs. The four hazards are
Deadlock
A state where threads compete for resources, waiting for each other in a
permanent state of stalemate.
Livelock
Similar to deadlock except the threads have got trapped into endless thrashing.
Race
Deficient locking of shared resources is one of the causes of races. Races
cause unpredictable results and may cause quite incorrect behaviour. However,
races sometimes don't show up until the JVM, computer or other thing
changes so as to affect the timing of the program execution.
Starvation
Starvation is when a thread that is not blocked never gets scheduled because
of unfair behaviour of other threads and the way they communicate. Have a
look at the Starving Philosophers example.
All four conditions cannot be eliminated merely by testing. Testing may indicate the
presence of a deadlock, but it cannot be relied upon to indicate freedom from
deadlock. This must happen by good design.

A clear model that aids good design is CSP (invented by Tony Hoare, who also
invented monitors). CSP is actually a mathematical algebra. Recent theoretical work
has proven that CSP can be used completely reliably in Java (aside from unknown
bugs in JVMs, of course). Doug Lea's book describes JCSP, one of the two libraries
through which this is achieved. Using JCSP (or CTJ, the other library), it is possible
to design Java programs of any complexity that are provably free from deadlock,
livelock, race or starvation.

Is there a limit to the number of threads that can be spawned in a program?


Location: http://www.jguru.com/faq/view.jsp?EID=138545
Created: Aug 30, 2000 Modified: 2000-08-30 13:44:16.302
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Yateen Shaha
(http://www.jguru.com/guru/viewbio.jsp?EID=126096

There is no technical limit. There are theoretical limits that a platform can support. If
you look at the Volano report, you'll see some limitations that they ran across.

What threads are initialized when you start an application? (I heard six.
What do they do?)
Location: http://www.jguru.com/faq/view.jsp?EID=141878
Created: Sep 5, 2000 Modified: 2000-09-06 13:49:05.509
Author: Paul Done (http://www.jguru.com/guru/viewbio.jsp?EID=94469) Question
originally posed by saraswathi devi
(http://www.jguru.com/guru/viewbio.jsp?EID=125969

Theres an easy way to list the threads running in a JVM, just write the following
class, compile and run from the command line....
public class ThreadDisplayer
{
public static void main( String[] args )
{
ThreadGroup topGroup =
Thread.currentThread().getThreadGroup().getParent();
topGroup.list();
}
}

For the JVM I was running (shows java version "1.2.2" Classic VM (build JDK-
1.2.2_006, native threads, symcjit), when I run java -version), I got the following
ouput....

java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Signal dispatcher,5,system]
Thread[Reference Handler,10,system]
Thread[Finalizer,8,system]
java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Thread[SymcJIT-LazyCompilation-0,3,main]
Thread[SymcJIT-LazyCompilation-PA,10,main]

This shows thread groups (name and priority) and threads (name, priority and
parent group name). For my JVM there seems to be 3 system threads. I'm guessing
that the Signal thread is handling O.S. event notification, Reference Handler is
handling object reference counts and Finalizer is handling garbage collection.
However this may not be totally correct 'cos I was always under the impression that
the g.c. thread had a low priority by default.

The Main thread will be the one that calls the main() method of your java program
and the other two threads seem to be there to handle JIT compilation.

I don't know where the java spec stipulates which threads must exist by default, or
whether the threads created are purely up to the JVM vendor. Certainly the
prescence of the two JIT threads suggests the latter.

Comments and alternative answers

Note that the AWT also spawns a thread the first time...
Author: Tomcat User (http://www.jguru.com/guru/viewbio.jsp?EID=127159), Sep 6,
2000
Note that the AWT also spawns a thread the first time you create a component. See
What exactly is the "Event Dispatch" thread (aka "AWT" Thread)? .

Thanx for giving nice info Mr.Paul, When i have en...


Author: satya maddipati (http://www.jguru.com/guru/viewbio.jsp?EID=237605), Nov
20, 2000
Thanx for giving nice info Mr.Paul, When i have enhanced the code like this,
import java.awt.Frame;
public class ThreadDisplayer extends Frame
{
public static void main( String[] args )
{
Frame f = new ThreadDisplayer();
f.setSize(300,300);
f.setVisible(true);
Thread.currentThread().getThreadGroup().getParent().list();
}
}
I got the following output :
java.lang.ThreadGroup[name=system,maxpri=10]

Thread[Signal dispatcher,5,system]
Thread[Reference Handler,10,system]
Thread[Finalizer,8,system]

java.lang.ThreadGroup[name=main,maxpri=10]

Thread[main,5,main] Thread[SymcJIT-LazyCompilation-0,1,main]
Thread[SymcJIT-LazyCompilation-PA,10,main] Thread[AWT-
EventQueue-0,6,main]
Thread[SunToolkit.PostEventQueue-0,5,main]
Thread[AWT-Windows,5,main]

What is the mechanism of Thread Priority & Thread Scheduler? How do


Threads with various priority levels behave in time-sliced and non-time-
sliced environments?
Location: http://www.jguru.com/faq/view.jsp?EID=200362
Created: Sep 7, 2000 Modified: 2000-09-08 12:40:25.407
Author: Ron Kurr (http://www.jguru.com/guru/viewbio.jsp?EID=132270) Question
originally posed by Jayapalan Senthilkumar
(http://www.jguru.com/guru/viewbio.jsp?EID=125299

Mapping of Java's 10 thread priorities to the underlying OS is platform dependent.


For example, NT has 7 priorities which needs to get mapped to Java's 10 -- and you
don't really know what Java priority maps to what NT priority. NT also "priority
boosts" threads on occassion, which temporarily adjusts a thread's priority without
you actually knowing about it. You might consider not relying on anything other than
Thread.MAX_PRIORITY, Thread.MIN_PRIORITY and Thread.NORM_PRIORITY for your
scheduling needs.

To answer your second question, I think you are referring to green threads and
native threads. Green Threads is the cooperative thread model where the JVM
handles the scheduling of threads. Native Threads is the preemptive threading model
which use the OS to schedule threads. In the Green Thread model, threads only give
up control if they call yield(), sleep() or make a blocking IO call. Under the Native
Thread model, you never know when your thread is going to be interrupted and must
code accordingly, using synchronized statements. Unless you target your code to a
particular platform, you need to code such that it behaves in a cooperative as well as
a preemptive environment.
Comments and alternative answers

Correction
Author: Eddy Ferguson (http://www.jguru.com/guru/viewbio.jsp?EID=388795), Mar
27, 2001
Green threads are not cooperative. They are simply a user level thread package that
are still scheduled and time-sliced.

What is InterruptedException? Why do we need to catch it when calling


Thread.sleep()?
Location: http://www.jguru.com/faq/view.jsp?EID=202575
Created: Sep 11, 2000 Modified: 2000-09-11 10:59:57.439
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Thomas SMETS
(http://www.jguru.com/guru/viewbio.jsp?EID=20729

InterruptedException is thrown if another thread calls interrupt() on the sleeping


thread while it is asleep. If sleep() is setting an alarm clock before bed, interrupt() is
a midnight phone call.

This means that you can safely ignore the exception (with
catch (InterruptedException e) {}) since in general, only code that you write
will ever call interrupt. Since you didn't write it, you know it won't happen. :-)

InterruptedException was not implemented in Java 1.0; however, it is definitely


available now.

The exception will also get thrown if the "interrupted" flag is set in the thread, which
happens if another thread calls interrupt even before the original thread sleeps.

See also Is it possible to interrupt a running thread? for interesting details.

Does the main thread get terminated after returning from main(), even after
spawning one or more threads?
Location: http://www.jguru.com/faq/view.jsp?EID=208546
Created: Sep 17, 2000 Modified: 2000-09-17 21:28:47.123
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Kevin Chien
(http://www.jguru.com/guru/viewbio.jsp?EID=13392

Yes. You can determine this by running the following program and doing a thread
dump:
public class mainthread extends Thread
{
public static void main(String[] args)
{
mainthread t1 = new mainthread();
mainthread t2 = new mainthread();
t1.start();
t2.start();
}

public void run()


{
while(true)
{
// do something
}
}
}
You will notice there is no thread named "main" (since by the time you press CTRL-
BREAK or CTRL-\ it has exited).
Comments and alternative answers

The following program may be useful... import ja...


Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537), Sep
18, 2000
The following program may be useful...

import java.awt.*;
public class X
{
public static void main(String[] args)
{

final Thread thread =


Thread.currentThread();
new Thread(
new Runnable() {
public void run()
{

System.out.println("Now wait for " + thread + " to


finish.");

try {
// wait for
'thread' to finish

thread.join();

System.out.println("" + thread + " finished.");


} catch (Exception
e) {

System.out.println(e);
}
}
}
).start();

}
}

When exactly is the AWT thread started?


Location: http://www.jguru.com/faq/view.jsp?EID=209463
Created: Sep 18, 2000 Modified: 2001-05-07 09:01:57.617
Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537)
Question originally posed by Rahul Mahindrakar
(http://www.jguru.com/guru/viewbio.jsp?EID=136198

Anytime the java.awt.Toolkit instance is (directly or indirectly) created. The direct


way to create it is by calling-

Toolkit.getDefaultToolkit();

Indrect way is by creating any AWT object.

Here is a sample program to play with -

import java.awt.*;
public class X
{
static Frame f;

public static void main(String[] args)


{
//Toolkit.getDefaultToolkit();
f = new Frame();
System.out.println("...");
}
}

See also: What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?
Comments and alternative answers

I tend to disagree. Only when the show method of a...


Author: Rahul Mahindrakar (http://www.jguru.com/guru/viewbio.jsp?EID=93986), Sep 22, 2000
I tend to disagree. Only when the show method of a frame is called is the awt thread created. Check
out the code below. The number of threads is increased to 6 only after the show() method is invoked,
not before.
import java.awt.*;
public class X
{
static Frame f;

public static void main(String[] args)


{
Thread.currentThread().getThreadGroup().list();
System.out.println("...");
//Toolkit.getDefaultToolkit();
f = new Frame();
Thread.currentThread().getThreadGroup().list();
System.out.println("...");
f.show();
Thread.currentThread().getThreadGroup().list();

System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println("...");
}
}

The thread is created after you create the AWT object....


Author: veera iruku (http://www.jguru.com/guru/viewbio.jsp?EID=217047), Sep 29,
2000

The thread is created after you create the AWT object. May be it's a version problem.
I ran the above program, I got the following output.

java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Before frame ... 1
java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Thread[AWT-EventQueue-0,6,main]
Thread[SunToolkit.PostEventQueue-0,5,main]
Thread[AWT-Windows,5,main]
After frame ... 4
java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Thread[AWT-EventQueue-0,6,main]
Thread[SunToolkit.PostEventQueue-0,5,main]
Thread[AWT-Windows,5,main]
After show ... 4

Same Result on Linux : java -version &nbsp;&nbsp;&...


Author: Thomas SMETS (http://www.jguru.com/guru/viewbio.jsp?EID=20729), Oct
4, 2000
Same Result on Linux :
java -version
java version "1.2.2"
Classic VM (build 1.2.2-L, green threads, nojit)

When AWT Thread is started.


Author: Ethan Leet (http://www.jguru.com/guru/viewbio.jsp?EID=393121), Apr 2,
2001
Does any one now when in creation of an object like JFrame, the thread is started.
Where in the actual code is the call to Toolkit.getDefaultToolkit( ). Which object
makes the call, JFrame, Frame, Window, Conatainer, or Component? Does any one
have any information that it just happens magically. Thank you.

Re: When AWT Thread is started.


Author: Zoltan Luspai (http://www.jguru.com/guru/viewbio.jsp?EID=538098),
Nov 3, 2001
I've found that the awt-thread can be started by this code:
EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
See my post about "How do we stop the AWT thread?"

What is the difference between multithreading and multitasking? What


about multiprogramming? Multiprocessing?
Location: http://www.jguru.com/faq/view.jsp?EID=211169
Created: Sep 20, 2000 Modified: 2001-10-02 09:42:51.16
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

Multitasking is running multiple "heavyweight" processes (tasks) by a single OS.

Multithreading is running multiple "lightweight" processes (threads of execution) in


a single process / task / program. See What is the difference between a lightweight
and a heavyweight process? for more detail on lightweight vs. heavyweight
processes.

Multiprogramming is essentially a synonym for multitasking (though multitasking


connotes sharing more resources than just the CPU, and is the more popular term).

Multiprocessing involves using multiple CPUs, either in the same (SMP) or different
(MPP) host boxes, to run a program. See whatis.com for a good definition.

Most Java implementations will split threads among different processors if they're
running on an SMP box.

Comments and alternative answers

MultiProgramming and MultiTasking is similar means...


Author: ramasubbu narayanan
(http://www.jguru.com/guru/viewbio.jsp?EID=227536), Oct 12, 2000
MultiProgramming and MultiTasking is similar means several Programs running at
Different Process areas (Memory locations). So communication between two process
is difficult ie., by marshalling...

MultiThreading runs in the Same Address Space and can communicate easily and it's
light weight.

Re: MultiProgramming and MultiTasking is similar means...


Author: Simon Ablett (http://www.jguru.com/guru/viewbio.jsp?EID=431607), Sep
5, 2001
Multithreading is a specialised subset of multitasking. If I remember from college,
multitasking does not necessarily mean seperate programs. Rather it refers to
seperate processes each running concurrently. This could refer to a multithreaded
process.

Re: MultiProgramming and MultiTasking is similar means...


Author: vysyaraju Ajay Raju
(http://www.jguru.com/guru/viewbio.jsp?EID=1159309), Apr 1, 2004

Multiprogramming is a method of running several different programs in a


computer apparently at the same time.

Usually on a mainframe - the computer has a number of programs loaded into


memory and the operating system switches quickly between them, processing a
little bit of each one in turn. The high speed of the processor makes it seem like
more than one program is being run at the same time.

On a PC it is usually called multitasking.

Re[2]: MultiProgramming and MultiTasking is similar means...


Author: Karthik Ramachandran
(http://www.jguru.com/guru/viewbio.jsp?EID=1198813), Sep 13, 2004
Multitasking and multiprogramming have nothing to do with whether its i on a
PC or mainframe. Infact they both are the same. The difference is that
multiprogramming is a term that was used before the introduction of virtual
memory. Before there was virtual memory, programs resided in memory
entirely or not. Hence it was called multiprogramming. With the advent of
Virtual memory, programs could reside in parts . Hence at any time there could
be different parts of many programs in the memory. Henc since these parts
were not really programs, they began to be called as tasks and hence
multitasking.
How does JavaMail handle thread management? Looks like by default, most
of the threads created by JavaMail while fetching the messages from a
Store/Folder object are not being released automatically. Do I need to
explicitely invoke any method so that these threads get released?
Location: http://www.jguru.com/faq/view.jsp?EID=214263
Created: Sep 23, 2000 Modified: 2000-09-23 21:47:33.747
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Shashidhar Mudigonda
(http://www.jguru.com/guru/viewbio.jsp?EID=100253

Closing the Folder, Store, or Transport should cause the thread to terminate itself
after delivering any pending events to listeners.

Why is Thread.run() declared public? Shouldn't it be declared protected, as


only the Thread superclass can invoke it?
Location: http://www.jguru.com/faq/view.jsp?EID=221632
Created: Oct 3, 2000 Modified: 2000-10-03 10:55:07.708
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Jim Nelson
(http://www.jguru.com/guru/viewbio.jsp?EID=213405

One reason is that Thread implements Runnable, which requires that run() be
public. This is an unfortunate consequence of the definition of Java interfaces.

It is also not clear whether you would want to prohibit other classes from calling a
Thread's run() method in a synchronous manner -- as it is, they have the option of
calling either run() or start() depending on their needs.

But you're right, it feels wrong. :-)

Comments and alternative answers

First of all i do agree that interfaces method has...


Author: aashish sharma (http://www.jguru.com/guru/viewbio.jsp?EID=244152), Nov
3, 2000
First of all i do agree that interfaces method has to be public as they are supposed to
be the "interface" to the outer world. Thus it's quite natural that the run method has to
be public.

Calling run directly, as can be done, what will you achieve ? Definitely not the
multithreading you might want to achieve. So I guess you might like to feel right, but
give more thought and you will find that you are actually wrong.

"synchronous" *means* "non-multithr...


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 4, 2000
"synchronous" *means* "non-multithreaded." It may be weird, but it's possibly useful
to be able to call a method either synchronously (run) or asynchronously (start)
depending on your needs at the moment. But I don't recommend it; there are cleaner
ways to accomplish that.

How can I determine if a wait(timeout) timed out or was notify()'ed? I'm


thinking of the case where multiple threads are waiting and notifyAll() is
NOT used.
Location: http://www.jguru.com/faq/view.jsp?EID=229397
Created: Oct 16, 2000 Modified: 2000-10-24 10:21:19.257
Author: Jim Nelson (http://www.jguru.com/guru/viewbio.jsp?EID=213405) Question
originally posed by Jim Nelson
(http://www.jguru.com/guru/viewbio.jsp?EID=213405

According to Allen Holub's article on IBM.com, there is no way to be sure that a


wait(timeout) timed out rather than was notify'd. He suggests a simple change: that
wait return a boolean value indicating if it timed out.

This excellent article mentions several other changes he'd like to see in Java's
threading model and is a good read for anyone doing heavy Java threaded
programming.

Comments and alternative answers

While it is true that wait() does not return a value...


Author: Edward Harned (http://www.jguru.com/guru/viewbio.jsp?EID=240325), Nov
2, 2000

While it is true that wait() does not return a value as to time-out or notify(), your
application threads may communicate with each other.

We have an RMI Server that uses application threads. The RMI Connection thread
creates an int[]:
int[] postit = new int[1];
postit[0] = 0;
and passes the reference to this int[] to the application thread:
wakeAppl(postit, ... other stuff);

When the application thread finishes its work, it "posts" the indicator,
passed_postit[0] = 1;
and issues a notifyAll().

Now the RMI Connection thread may check the postit[0] for a 0-timed-out, 1-notify.

When I am using wait(timeout) I am getting Unexpected...


Author: Sreelal Chandrasenan
(http://www.jguru.com/guru/viewbio.jsp?EID=323036), Feb 13, 2001
When I am using wait(timeout) I am getting Unexpected System Error. This happens
whenever a timeout occurs. I am using jdk1.2.2. As from the above discussion it looks
like it does not happen. Please comment

What's wrong with Java threads?


Location: http://www.jguru.com/faq/view.jsp?EID=229728
Created: Oct 16, 2000 Modified: 2000-10-24 08:31:02.906
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Allen Holub has an interesting survey of some of the problems with threads, and his
proposed solutions, at If I were king.

How can I determine if a wait(timeout) timed out or was notify()'ed? I'm


thinking of the case where multiple threads are waiting and notifyAll() is
NOT used.
Location: http://www.jguru.com/faq/view.jsp?EID=232439
Created: Oct 19, 2000 Modified: 2000-10-20 10:04:05.217
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jim Nelson
(http://www.jguru.com/guru/viewbio.jsp?EID=213405

There is no way to determine if wait() returned because of a notify or a timeout.

For info on this and other limitations of threads, see If I were king: A proposal for
fixing the Java programming language's threading problems by Allen Holub, over at
IBM's developerWorks.

Comments and alternative answers

there are two ways of determining this


Author: Andrey Karachoun (http://www.jguru.com/guru/viewbio.jsp?EID=1016349),
Nov 5, 2002
First of all you can use empty wait() method without specifying timeout in params,
to make sure that it returned only due to notify() or interrupt() calls.

The better approach is when your notifying or interrupting thread will also set some
boolean flag to indicate that the event you were expecting really happened. I can
recommend writing code like this (note that getter and setter methods for the flag
should be synchronized):
public void run()
{
..
while(isTerminating() == false)
try
{
synchronized(this)
{
wait();
}
}
catch(InterruptedException ie)
{
// current thread is interrupted, but we are not sure
that isTerminating() is true here
}
// we are sure that isTerminating() is true here
// current thread will be terminated here
}

If an exception is thrown inside a synchronized block will the lock on the


object that was synchronized be automatically released?
Location: http://www.jguru.com/faq/view.jsp?EID=245377
Created: Nov 4, 2000 Modified: 2000-11-04 18:59:38.403
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Dane Foster
(http://www.jguru.com/guru/viewbio.jsp?EID=228595

It depends on whether the exception escapes (passes through) the synchronized


block or not. Consider the following example.

try {
synchronized (o) {
try {
doSomething();
}
catch (A) {
a();
}
}
}
catch (B) {
b();
}

If doSomething() throws an exception of type A, it will be caught by the inner try


block, and the lock on o will still be active during method a(). However, if
doSomething() throws an exception of type B, it will be caught by the inner try block
-- on its way out of the series of nested stack frames -- and the lock will be released
before method b() is invoked.

How does Linux handle Java thread priorities?


Location: http://www.jguru.com/faq/view.jsp?EID=247295
Created: Nov 6, 2000 Modified: 2000-11-07 09:02:12.57
Author: Nathan Meyers (http://www.jguru.com/guru/viewbio.jsp?EID=138686)
Question originally posed by Satheesh Santhanagopalan
(http://www.jguru.com/guru/viewbio.jsp?EID=233010
The Linux JDK ignores Java thread priorities. While Linux does offer programs a
certain amount of control over task priority, that control can only be fully exercised
by the super-user. So the JDK does not try to use any Linux-supplied task priority
mechanisms.

Like many aspects of threading, Java thread priorities are a suggestion, not a
requirement. If they were a requirement, Java would not be usable in many
environments that do not match its threading model. If your application depends on
thread priorities for proper behavior, it isn't portable.

Comments and alternative answers

LINUX: Is there no way to handle thread priorities in a correct way ?!?


Author: Günther Zwetti (http://www.jguru.com/guru/viewbio.jsp?EID=993979), Sep
4, 2002
Refering to many articles, one question arises: Is there any way to ensure thread
priorities to take effect running on a linux platform ? As I know, Windows accepts
your priority suggest, but with linux I got the following: By running an application
using 2 threads (both threads are running an endless loop and the 1st for example
sleeps 100ms after each cyle and the second sleeps 10000ms after each cycle) one
problem arises: Regardless to the priorities given to both threads, I can not ensure a
cycle-time of 100ms for the first thread if the second one has to work for more than
100ms. By running the same application on Windows I only have to run the 100ms
thread on a higher priority than the other thread and everything does well. (which
means that the high prior thread is enabled to interrupt the execution of the low prior
thread and therefore permanently executes its own statements every 100ms). Is there
any way to ensure correct handling of thread priorities running on a linux system or
are there any linux distributions, JDKs ... being able to act this way ?

How can I find out how many threads are running in the JVM?
Location: http://www.jguru.com/faq/view.jsp?EID=268705
Created: Dec 4, 2000 Modified: 2000-12-20 10:22:08.429
Author: Fredrik Appelberg (http://www.jguru.com/guru/viewbio.jsp?EID=243342)
Question originally posed by Naveen Ajjampur
(http://www.jguru.com/guru/viewbio.jsp?EID=127318

I believe you can call getParent() recursively on the current ThreadGroup


(System.currentThread().getThreadGroup()) until you find the toplevel ThreadGroup.
Then call enumerate to get an array with all threads. This seems pretty wasteful,
though, and I'm sure there is a better way to do it.
Comments and alternative answers

See also this forum thread


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 27, 2001
how many threads are running in current JVM?

See also this other forum thread


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Dec 28, 2002
How to get a thread list of my process?

I have a static method where I pass some parameters and it does db


manipulations, returning some resultset. Do I need to synchronize this
method to make it thread safe? It does not use any other variables. It only
uses local variables passed as method parameters.
Location: http://www.jguru.com/faq/view.jsp?EID=268706
Created: Dec 4, 2000 Modified: 2000-12-07 20:49:30.106
Author: Fredrik Appelberg (http://www.jguru.com/guru/viewbio.jsp?EID=243342)
Question originally posed by Masood Nasir
(http://www.jguru.com/guru/viewbio.jsp?EID=236142

[No, not if you make a new java.sql.Statement for each request / thread. JDBC
drivers are supposed to be multithreaded -- although early versions of some drivers
were buggy in this regard. -Alex]

You could get into trouble if two threads are using the same Connection at the same
time (at least I had this problem with an Oracle database), espececially if
autocommit is turned off and both thread try to perform several operations before
calling commit(). Also, if one thread is looping through a ResultSet and another
thread makes a query using the same Statement (or PreparedStatement), the first
ResultSet gets screwed up.

Does Java keep a count of the number of notifys for a given object? That is,
if notify() is called three times on on object A, then will three waits at a
later time proceed immediately? Also, if there are three waits on A then at a
later point three notifies on A will resume all of three of them?
Location: http://www.jguru.com/faq/view.jsp?EID=288062
Created: Dec 28, 2000 Modified: 2001-01-04 05:40:10.953
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by David Rees
(http://www.jguru.com/guru/viewbio.jsp?EID=128499

1. No, Java does not store notifys. That means that if notify is called on a
synchronization object with no objects waiting, it is simply discarded.
2. The waiting objects however are kept on a pool, so if we have three objects
there and three notifys occur, each (previously) waiting object can proceed,
as soon as it recaptures the lock on the synchronization object (recall that
both wait and notify must be called with lock possession).

How can I create a pool of threads for use in my program?


Location: http://www.jguru.com/faq/view.jsp?EID=291195
Created: Jan 2, 2001 Modified: 2001-01-04 05:41:25.063
Author: Paul Faccenda (http://www.jguru.com/guru/viewbio.jsp?EID=291179)
Question originally posed by Kartik V
(http://www.jguru.com/guru/viewbio.jsp?EID=267177

Implement a producer-consumer workqueue model. The pooled consumer (worker)


threads take work requests from a synchronized queue and producer threads put
items on the queue. If the producer class thread needs to synchronize on completion
of the request, the request will need to contain a condition variable that the worker
thread signals when the task is completed; otherwise it's just a give-and-go.

This is a simple explanation to a fairly complex problem.

[Anyone have any pointers to existing Thread Pool libraries? -Alex]

Comments and alternative answers

Tomcat has a simple Thread Pool in its org.apache....


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 4, 2001
Tomcat has a simple Thread Pool in its org.apache.tomcat.util package. Download the
source from http://jakarta.apache.org and take a look.

Also, you could "cheat" and use a servlet engine or app server. If you implement your
class as a servlet, then the server will use its thread pool to process simultaneous
requests to the servlet. This is, obviously, a hack (if your app is not really a servlet)
and should be used cautiously.

I have implemented a thread pooller for an ActionL...


Author: Francois Nadeau (http://www.jguru.com/guru/viewbio.jsp?EID=305008), Jan
26, 2001

I have implemented a thread pooller for an ActionListener. This may not be exactly
what you need but the source is open to any one so you are welcome to it. It can be
found on my site or can be dowloaded at :

http://cni.elitecities.com/_/fnadeau/utility.jar

The classes which you should look at is :

utility.thread.UtilitySupervisor
and
utility.thread.UtilityThread

In this design the user does not need to worry about creating a Runnable or Thread
class. I hope this help's you.

Doug Lea, in his industrial-strength util.concurrent...


Author: Alec Noronha (http://www.jguru.com/guru/viewbio.jsp?EID=302525), Jan
29, 2001

Doug Lea, in his industrial-strength util.concurrent package includes a


PooledExecutor class.

From the JavaDoc:

"A tunable, extensible thread pool class. The main supported public method is
execute(Runnable command), which can be called instead of directly creating threads
to execute commands.

Thread pools can be useful for several, usually intertwined reasons:

• To bound resource use. A limit can be placed on the maximum number of


simultaneously executing threads.
• To manage concurrency levels. A targeted number of threads can be allowed to
execute simultaneously.
• To manage a set of threads performing related tasks.
• To minimize overhead, by reusing previously constructed Thread objects
rather than creating new ones. (Note however that pools are hardly ever cure-
alls for performance problems associated with thread construction, especially
on JVMs that themselves internally pool or recycle threads.)

..."

Example (from the presentation):

class WebService {
public static void main( String[] args) {
PooledExecutor pool = new PooledExecutor( new BoundedBuffer( 10),
20);
pool. createThreads( 4);
try {
ServerSocket socket = new ServerSocket( 9999);
for (;;) {
final Socket connection = socket. accept();
pool. execute( new Runnable() {
public void run() {
new Handler(). process( connection);
}
});
}
}catch(Exception e){ } // die
}
}
class Handler{
void process(Socket s);
}

This package implements what is described in his outstanding book Concurrent


Programming in Java: Design Principles and Patterns 2nd edition, Addison Wesley.

I believe any serious Java threads programmer must go through this package (and the
book for sure).

URL: http://gee.cs.oswego.edu/dl/cpj/index.html

Re: Doug Lea, in his industrial-strength util.concurrent...


Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295), Aug 30,
2001
This may be way too late (for comments) but in most thread pool class that I have
seen, it has some deficiencies:-

1) It is not friendly to the gc manager. It keeps recreating the runnable. Even in


Doug Lea's WebService example, it keeps creating a Handler.

2) There is no way to recreate another worker (or thread). Example, if the thread
dies or blocks (or hangs), then we will lose a worker forever.

I am very keen to see a better class pool design. I would be most thankful if
someone can point me to the right direction.

Re: Doug Lea, in his industrial-strength util.concurrent...


Author: dave tam (http://www.jguru.com/guru/viewbio.jsp?EID=79557), Feb 26,
2002
You said that some JVM do pool thread internal. do u have any ideas which of
them do? i am currently working on Solaris and i dont think you can improve on
pooled thread. the JVM i am using is 1.2.2_5a

How do I implement a timeout using Java threads? Specifically, I want to


connect to one of two servers. If the first one fails after a certain amount of
time, I want to try the second one. How do I interrupt the first connection
attempt?
Location: http://www.jguru.com/faq/view.jsp?EID=305013
Created: Jan 17, 2001 Modified: 2001-01-19 14:20:30.155
Author: Francois Nadeau (http://www.jguru.com/guru/viewbio.jsp?EID=305008)
Question originally posed by Jack Leung
(http://www.jguru.com/guru/viewbio.jsp?EID=13166

Here's how I would do it. I would have 2 Threads. The first one would try to
compunicate to the server. The second one would keep track of the time spent
communicating. inside the run methode of the one calling onto an other server place
a try catch code to catch an InterruptedException exception. In the catch make the
needed changes, ie. give a need server address and restart.
public void run() {
while( !connected )
try {
connectToServer() ;
}catch( InterruptedException ie ) {
//set a different server name
}
}
Comments and alternative answers

Watch out with interrupt() method! With most of JVM,...


Author: David Amar (http://www.jguru.com/guru/viewbio.jsp?EID=331070), Feb 16,
2001
Watch out with interrupt() method! With most of JVM, interrupt() cannot interupt a
I/O blocked thread with endless connection time-out. If you want to be sure to
terminate blocked thread, close I/O resources to provoke IOException. Then try with
a different server.

David.

My Source: Java Threads (O' Reilly)

In my main thread I create and start a new Thread(B). From within the run
method of Thread B I invoke a public method of my Main class. This method
is currently getting executed in Thread B instead I want that method to get
executed in Thread Main. Is this possible?
Location: http://www.jguru.com/faq/view.jsp?EID=314501
Created: Jan 28, 2001 Modified: 2001-01-29 07:46:15.911
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Mahalingam Srikanth
(http://www.jguru.com/guru/viewbio.jsp?EID=288035

Since the method is called by the created thread, it is run by the created thread. In
order for the method to be executed in the main thread, you must setup some
signalling mechanism to tell the main thread to execute the method. JMS is probably
overkill, but you can easily do a wait/notify between the two.
Comments and alternative answers

Continuing from my previous query,this is the read...


Author: shreepriya gopalan (http://www.jguru.com/guru/viewbio.jsp?EID=324189),
Feb 12, 2001
Continuing from my previous query,this is the read method i'm using:

case SerialPortEvent.DATA_AVAILABLE:
// If there is data available on serial
port,
// read it in in chunks <=20 bytes
//
byte[] readBuffer = new byte[16];

try {
while (in.available()>0) {

int numBytes =
in.read(readBuffer);

System.out.print(new
String(readBuffer));

}
catch (IOException e) {
// Terminate handling this event on
read error
}

break;

How does SunOS 5.6(solaris) handle Java threads on multiple CPUs?


Location: http://www.jguru.com/faq/view.jsp?EID=330539
Created: Feb 15, 2001 Modified: 2001-02-16 15:04:36.98
Author: Luis F. Canals Samaniego
(http://www.jguru.com/guru/viewbio.jsp?EID=66172) Question originally posed by
turaj khorram (http://www.jguru.com/guru/viewbio.jsp?EID=230188

Take a look at the Sun's white paper at


http://www.sun.com/software/solaris/java/wp-java/ , specifially
http://www.sun.com/software/solaris/java/wp-java/4.html#many-to-many

As Solaris has many-to-many threading model/two level threading model,


can you tell me how the user thread is mapped to a LWPs exactly? What is
the algorithm that is is being followed? Is there any limit (that these many
no of threads can only be mapped to one LWP & vice versa)?
Location: http://www.jguru.com/faq/view.jsp?EID=347470
Created: Mar 8, 2001 Modified: 2001-03-12 11:38:55.151
Author: Niyi Gbodimowo (http://www.jguru.com/guru/viewbio.jsp?EID=327885)
Question originally posed by Amol Joshi
(http://www.jguru.com/guru/viewbio.jsp?EID=253248

The algorithm that is used is based on a combination of Solaris' doors IPC model and
a simpler signals protocol. When you start a program that is linked with the thread
library libpthread.so, the thread library automatically starts a background process -
the dynamiclwps() or dynamic LWP scheduler which maps available LWPs to unbound
user threads. It runs a tight loop and blocks on signotifywait(). Additionally, a small
number of LWPs are shared between the kernel and the thread library. This is the
doors thread pool.

As long as there are free LWPs, the unbound user threads are bound to a LWP. If a
user thread blocks on some condition variable e.g I/O read, a LWP from the door
thread pool will be dispatched to run any available user threads. If there are none,
the LWP will wait on a timed (def. 5 minutes) condition variable before
terminating/returning to the door thread pool. If the door thread pool is empty, the
the kernel generates a SIGWAITING signal to the dynamiclwps().On receipt of a
SIGWAITING signal, the dynamiclwps thread will create a new LWP.

As you can see, new LWP pool is replenished when kernel threads move to a SLEEP
state and thread resources are conserved by cleaning up unused LWPs. Of course,
you can use pthread_create(...) to create your threads such that they are mapped to
LWPs immediately or you can use thr_create() to make full use of many-to-many
thread mappings. If on the other hand, you wish to explicitly set the number of LWPs
you want created, you can use thr_setconcurrency(n) where n is an integer that
hints on the number of LWPs to create in the thread pool.

I hope that that was not too obscure!

Is there anything special that needs to be done in order to get the JVM to
work efficiently with multiple CPUs on a Windows NT (4.0) machine?
Location: http://www.jguru.com/faq/view.jsp?EID=347482
Created: Mar 8, 2001 Modified: 2001-03-12 11:34:12.251
Author: Niyi Gbodimowo (http://www.jguru.com/guru/viewbio.jsp?EID=327885)
Question originally posed by Steven Bryant
(http://www.jguru.com/guru/viewbio.jsp?EID=136889

[We are currently using the standard VM that comes with the Java 2 JDK. When we
run the VM on a multi-processor (e.g., 2 cpus), Windows NT-based, computer, we
notice that one CPU hovers around 20% utlization, while the other is at 100%. We
believe that one of the CPUs is being used by the Windows kernal and the other is for
everything else - in our case the JVM and a WebLogic Application Server.]

Strange problem. I know of many people includng myself that run the standard
Java2 JVM on Windows NT/2000 with multiple processors with no such problem.

Since the Win32 JVM uses native threads by default and I know of no way that green
threads may be accidentally used, the only advice I can give is to check the CPU
affinity of your JVM process. You can check this by right clicking on the process in
Task Manager and selecting "Set Affinity..."

If (as I guess) you have already explored this option, then download the latest JVM
1.3 with the Hotspot server implementation. This JVM is targeted towards large-scale
server deployments and will do a better job at mapping your native threads to
multiple processors.

Why does Java prohibit the use of "synchronized" on a constructor?


Location: http://www.jguru.com/faq/view.jsp?EID=416171
Created: May 6, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Richard Robinson
(http://www.jguru.com/guru/viewbio.jsp?EID=395750

[I'm unclear about constructors in general, and how they relate to multithreading in
particular. Common advice is to make member variables (instance and static) private
and synchronize public methods in a class. As well, and in particular, to synchronize
getter/setter methods.

Java prohibits the using of "synchronized" on a constructor. So I'm guessing that


when an object is first created, ie. constructed, that there is ONE and ONLY ONE
thread that does the construction?

If this is right, then what happens after the first object is created and another object
in the same calling object tries to construct the object again. If the to-be-constructed
object has several instance variables and the constructor sets them... Even if the
setter methods are synchronized, isn't there a concurrency issue at work between
when the constructor sets the one value and the subsequent call to set the next
one?]

You can't construct an object more than once. You can construct a different instance
of the same class. But the scenario you describe is impossible. So stop worrying :-)

To be specific: the constructor is called *during* the call to new. Before that call
returns, there is *no* pointer (handle) to that object. So no other thread can ever
call a method on that instance. Once the constructor returns with a valid pointer,
then other threads may conceivably call methods on it.

In fact, at the moment the constructor is called, the object has not been created yet
-- which means there is no lock to synchronize on. That's why it's prohibited.

Note that you may still need to synchronize access to the static data members of a
class when called inside a constructor.

Comments and alternative answers

I Disagree
Author: Kevin Riff (http://www.jguru.com/guru/viewbio.jsp?EID=2057), Jun 20,
2001
There is an instance of the object on the stack when the constructor is invoked. If you
examine the byte codes produced by the compiler you'll see that there is always a new
instruction to create the object followed by an invokespecial instruction to invoke
the constructor. So when the constructor is invoked there is already an (uninitialized)
object on the stack.

The Java Language spec says (section 8.8.3) "There is no practical need for a
constructor to be synchronized, because it would lock the object under construction,
which is normally not made available to other threads until all constructors for the
object have completed their work." But I've read several books which explain how
modern CPUs can reorder the instructions in the class file in such a way that the
uninitialized object becomes visible to other threads. I suspect that synchronizing the
constructor would prevent that, but I'd need a PhD to prove it.

There is no prohibition against using a synchronized block within a constructor.


However, the requirement that the super-class constructor is in the first line of code
effectively ensures that one cannot acquire the lock before the super-class constructor
is invoked. This may be intentional on the part of the language designers, but I don't
see the purpose of it.

How can I discover the current process ID from Java?


Location: http://www.jguru.com/faq/view.jsp?EID=416212
Created: May 6, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Benjamin Rosenbaum
(http://www.jguru.com/guru/viewbio.jsp?EID=409351

[When analyzing logs that our Java servlet creates, it would be nice to be able to
determine the process id of the underlying Java process that was running at the
time. In most operating systems every thread has an associated process with a
unique id. Is there no way to get this information from Java?]

Yes, there is no way to get this information from Java (without JNI).

Comments and alternative answers

Way to get a PID


Author: Brian Agnew (http://www.jguru.com/guru/viewbio.jsp?EID=421255), May
14, 2001
The easiest way I've found to get the process id (under a Unix/Linux platform) is to
spawn off a short Perl script. It looks like:

perl -e 'print getppid()."\n";'

Use Runtime.exec() to do this and capture the standard out. The Perl script prints out
the parent process id, which is (of course) the JVM process id.

Note: you only have to do this once, so you don't invoke multiple Perl shells :-)

Re: Way to get a PID


Author: itai sadan (http://www.jguru.com/guru/viewbio.jsp?EID=435734), Jun 8,
2001
Is there a way to get the Thread ID that's running a java applet in Netscape 6?

Re: Way to get a PID


Author: Vikas Bali (http://www.jguru.com/guru/viewbio.jsp?EID=1216227), Dec
14, 2004
But how would we get this using Java only if I dont wanna to use perl.

Re[2]: Way to get a PID


Author: Eric van Bezooijen
(http://www.jguru.com/guru/viewbio.jsp?EID=1228739), Feb 22, 2005
Assuming you are on UNIX, you can read the PPID (parent process ID) with
the following bit of bourne shell script:

/bin/ps -f | /bin/awk '{print $2,$3}' | /bin/grep "^$$" | /bin/awk '{print $2}'

So, use Runtime.exec () to launch a shell process with the arguments:

/bin/sh
-c
"/bin/ps -f | /bin/awk '{print $2,$3}' | /bin/grep \"^$$\" | /bin/awk '{print $2}'"

Read the standard output and that should get you java's process ID.

Re[3]: Way to get a PID


Author: Xiaohui Liu
(http://www.jguru.com/guru/viewbio.jsp?EID=1243868), May 12, 2005
I just use "grep " to get the PID buy I am wondering if there's any API go
get the PID (e.g all current running processes or a particular process)

What is the difference between "Green Threads" and "Native Threads" ?


Location: http://www.jguru.com/faq/view.jsp?EID=416246
Created: May 6, 2001
Author: Alessandro A. Garbagnati
(http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by
neelapareddy padmakar (http://www.jguru.com/guru/viewbio.jsp?EID=387943

"Green Threads" are the default threads that are provided in the JDK, while the
"Native Threads" are the one provided by the native Operating System.

Normally "Native Threads" provide better performance bacause are controlled by the
kernel of the system, allowing the JVM to better use the resources offered by the
system itself.

For example, in a multiprocessor system "Green Threads" will never be able to use
Solaris or Linux or Windows specified kernel calls to optimize the use of the
processors.
Comments and alternative answers

Additional Information on Green Threads


Author: Omar Khan (http://www.jguru.com/guru/viewbio.jsp?EID=232689), May 7,
2001
John Brewer, Jera Design, provided this:
"Green threads appear to be an artifact of the original Green Project, which was trying
to design a hand-held computer based on the Sparc chip. So the original Java (the
called "Oak") VM was written to run directly on the Sparc, without Solaris/SunOS.
Because of that, they had to roll their own thread support. The project to transform
Oak into Java had very limited resources initially, they only did the bare minimum to
port the language to desktop computers (as anyone who ever used the 1.0 AWT can
attest). So they kept Green threads in the Solaris version because it worked, kind of.
The Green threads implementation used all kinds of tricks to make sure that I/O never
blocked the single native thread. When these tricks failed, the VM would hang until
the I/O request completed. BTW, it turns out that a one-to-one mapping of VM to
native threads isn't optimal either, because native threads tend to have quite a bit of
overhead. The current production release of the Solaris VM uses multiple native
threads, with each native thread servicing a number of VM threads. John Brewer Jera
Design"

See also The Mail Archive

Additional information on Green Threads


Author: Omar Khan (http://www.jguru.com/guru/viewbio.jsp?EID=232689), May 7,
2001
See also
What is the difference between "green" threads and "native" threads?

Is there any method by which I can join() to a group of threads instead of a


single one?
Location: http://www.jguru.com/faq/view.jsp?EID=416251
Created: May 6, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by sanjay acharya
(http://www.jguru.com/guru/viewbio.jsp?EID=405409

Yes. Just join to each one in turn. That way, when the loop exits, you know that all
the threads have exited -- whether it was the first thread or the seventh thread that
took the longest, all threads will be waited for. Remember, join() on a thread that's
already exited takes no time.

Iterator i = myThreads.iterator();
while (i.hasNext()) {
((Thread)i.next()).join();
}
Comments and alternative answers

Threads
Author: Robert Höglund Wanlert
(http://www.jguru.com/guru/viewbio.jsp?EID=62558), May 7, 2001
I recommend that you subclass ThreadGroup and then create one (or more) join-
methods in that class.
When the join method is called just iterate and join the threads in the threadgroup.
public class ExtendedThreadGroup extends ThreadGroup{
public ExtendedThreadGroup(String aName){
super(aName);
}
public ExtendedThreadGroup(String aName, ThreadGroup aThreadGroup){
super(aName,aThreadGroup);
}

public void join() {


try {
Thread threads[] = new Thread[activeCount()];
enumerate(threads);
for (int i = 0; i < threads.length; i++)
threads[i].join();
} catch (InterruptedException e) {
;
}
}
}
Thats IT ;)

Re: Threads
Author: Paul M (http://www.jguru.com/guru/viewbio.jsp?EID=468364), Aug 4,
2001
I am not convinced that the method Robert describes is particularly safe for
general use. The join() method here involves enumerating the set of active
Threads and then going through these one by one until they have all stopped - but
what if new Threads are added to this ThreadGroup while the for loop is still
running? New Threads could even be added to the ThreadGroup by the Threads
running within it. Thus, the method could return even when the ThreadGroup still
has active Threads. But granted, the above method is fine if you are only
interested in monitoring a group of Threads when you are sure that the number of
Threads will not change.

Why do I have to call System.exit() from my main method?


Location: http://www.jguru.com/faq/view.jsp?EID=416855
Created: May 7, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by gaurav aggarwal
(http://www.jguru.com/guru/viewbio.jsp?EID=402916

Unfortunately, certain system threads are started as regular threads, not daemon
threads. One example is the AWT thread. That means that if your app opens a
window, then even if that window is closed, the AWT thread continues, so your app
will never quit on its own.

There are many cases where a Java program will quit on its own when main() exits,
but there are also many sneaky cases where a thread is launched without your
knowledge by a library routine. Database Connection Pools are notorious for doing
this.

A warning: Make sure you only call System.exit() when you're really really sure all
background threads have stopped processing. Otherwise the threads will be stopped
prematurely, and may leave things in a bad state (for instance, if they're halfway
through writing a file).

How do I pass a variable into a thread that can be accessed from the run()
method?
Location: http://www.jguru.com/faq/view.jsp?EID=425562
Created: May 21, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Namrata Rai
(http://www.jguru.com/guru/viewbio.jsp?EID=418726

Create a subclass of Thread with a custom instance variable and initialize it in the
constructor. (This is basic object-oriented programming design, BTW.)

For instance, to pass in a PrintWriter from the doGet method of a Servlet:

public MyThread extends Thread {


private PrintWriter myWriter;
public MyThread(PrintWriter writer)
{
myWriter = writer;
}
public void run()
{
...
myWriter.print(...);
...
}
}

public void doGet(...)


{
...
MyThread mt = new MyThread(response.getWriter());
mt.start();
mt.join();
...
}
This is a very dangerous technique, however, since the doGet() method may return
before the thread finishes. So watch out. That's why you need the join() call -- it
waits until the thread is finished.
Comments and alternative answers

Re : How do I pass a variable into a thread that can be accessed from the run()
method?
Author: Venugopal V.V. (http://www.jguru.com/guru/viewbio.jsp?EID=467584), Aug
6, 2001

Hi Alex..I have a situation where i need to run the bean as a seperate thread. The bean
method requires 6 parameters. And the above solution you gave can be applied there?
I don't need any PrintWriter or i don't need to deal with any request or response
objects. I have all the 6 parameters ready with me.

I just need how to call the bean method using the above method you gave.. I have
written in the following way. May be you can check on this and pour in your
suggestions..

*** code
public class MyThread extends Thread{

// the variables passed from the A.jsp


private String stD;
private String endD;
private int uId;
private int aId;
private int orgId;
private int empId;

public MyThread(String s,String e,int u,int a,int o,int e){


Bean a = new Bean();
stD = s;
endD = e;
uId = u;
aId = a;
orgId = o;
empId = e;
}
public void run(){
a.methodInBean (stD,endD,uId,aId,orgId,empId);

} // end of run()

} // end of MyThread()

*** end of code


a.methodInBean takes all the 6 parameters and finish its task. This is what i want.
Will the above code suffice what i wanted? Let me know if you have any comments..

- Venu
Great Help
Author: abhay sahai (http://www.jguru.com/guru/viewbio.jsp?EID=940140), Jul 18,
2002
Really I was looking to such help where I can start a new bean context with each
thread and this gives me enough guidence. Thanks again

Are there any good tutorials on Java Threads?


Location: http://www.jguru.com/faq/view.jsp?EID=425565
Created: May 21, 2001
Author: Ibrahim Levent (http://www.jguru.com/guru/viewbio.jsp?EID=131172)
Question originally posed by Chetna Bhatt
(http://www.jguru.com/guru/viewbio.jsp?EID=39095

Bruce Eckel's Java book(Thinking in Java) can be downloaded freely from his site :
http://www.bruceeckel.com This book's thread section may be helpful for you.

How can I find out how much CPU is taken by each JVM thread ?
Location: http://www.jguru.com/faq/view.jsp?EID=425569
Created: May 21, 2001
Author: Kevin Riff (http://www.jguru.com/guru/viewbio.jsp?EID=2057) Question
originally posed by Ofer Shaked
(http://www.jguru.com/guru/viewbio.jsp?EID=62619

Java Tip 92 at JavaWorld describes how to use the JVM Profiling Interface to get
accurate timing information on a per-thread basis. The technique requires a small
amount of native code, but it will work regardless of how the JVM maps Java threads
to native processes.

What is the difference between sleep and yield?


Location: http://www.jguru.com/faq/view.jsp?EID=425624
Created: May 21, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Kim Hynek
(http://www.jguru.com/guru/viewbio.jsp?EID=421207

yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices.
Usually the JVM uses this call to activate another thread of the same thread priority.
In a good preemptive multithreading environment, yield() is a no-op. However, it is
important in a cooperative multithreading environment, since without yield(), one
thread can eat up all of the CPU.

sleep(x) tells the JVM Thread Scheduler to actively put this thread to sleep and not
run it again until at least x milliseconds have elapsed.

Neither sleep() nor yield() change anything about the status of synchronization locks.
If your thread has a lock, and you call sleep(1000), then at least a second will elapse
before your thread wakes up. When it wakes up it may decide to release the lock --
or it may hold on to it longer.

See also
• What is the main difference between a preemptive scheduler and a non-
preemptive scheduler?
• How does a preemptive scheduler manage a thread's timeslice?
• What is the difference between "green" threads and "native" threads?
• What is the mechanism of Thread Priority & Thread Scheduler? How do
Threads with various priority levels behave in time-sliced and non-time-sliced
environments?

If an event handler throws an exception which it does not itself catch, there
is a crash in the current EventQueue DispatchThread. It is impractical to put
a try-catch around every possible event handler in the application. Is it
somehow possible to catch exceptions within the EventQueue's
DispatchThread and execute some code?
Location: http://www.jguru.com/faq/view.jsp?EID=427279
Created: May 23, 2001 Modified: 2005-08-03 19:01:27.016
Author: Peter Gadjokov (http://www.jguru.com/guru/viewbio.jsp?EID=208220)
Question originally posed by Patrick Stephens
(http://www.jguru.com/guru/viewbio.jsp?EID=390138

Quoted below is the is the documentation of the private method handleException of


java.awt.EventDispatchThread. It's not a long-term solution but it does work.

Handles an exception thrown in the event-dispatch thread.

If the system property "sun.awt.exception.handler" is defined, then when this


method is invoked it will attempt to do the following:

1. Load the class named by the value of that property, using the current thread's
context class loader,
2. Instantiate that class using its zero-argument constructor,
3. Find the resulting handler object's public void handle method, which should
take a single argument of type Throwable, and
4. Invoke the handler's handle method, passing it the thrown argument that was
passed to this method.

If any of the first three steps fail then this method will return false and all following
invocations of this method will return false immediately. An exception thrown by the
handler object's handle will be caught, and will cause this method to return false. If
the handler's handle method is successfully invoked, then this method will return
true. This method will never throw any sort of exception.

Note: This method is a temporary hack to work around the absence of a real API that
provides the ability to replace the event-dispatch thread. The magic
"sun.awt.exception.handler" property will be removed in a future release.

Where can I learn (more) about the Java programming language syntax and
semantics?
Location: http://www.jguru.com/faq/view.jsp?EID=431198
Created: May 30, 2001 Modified: 2001-06-16 16:03:37.746
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)
Check out the jGuru JavaLanguage FAQ.

Where can I learn (more) about Java on the Linux platform?


Location: http://www.jguru.com/faq/view.jsp?EID=431235
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Linux FAQ.

Where can I learn (more) about Java on the Apple Mac platform?
Location: http://www.jguru.com/faq/view.jsp?EID=431236
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Java on Mac FAQ.

Where can I learn (more) about Java networking capabilities?


Location: http://www.jguru.com/faq/view.jsp?EID=431237
Created: May 30, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Networking FAQ.

Where can I learn (more) about Java development tools?


Location: http://www.jguru.com/faq/view.jsp?EID=431253
Created: May 30, 2001 Modified: 2001-06-16 16:02:22.999
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Tools FAQ.

Comments and alternative answers

Documentation location and a modest comment.


Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357),
May 31, 2001
As you may have fugired it out the forums you have chosen to send your question to
is specialized to specific topics. Please respect that and do not send any question to all
the forums.

The information you are looking for may be found at:


http://java.sun.com/docs/books/tutorial/.
Good Luck!

Where can I learn (more) about Java's support for transaction processing?
Location: http://www.jguru.com/faq/view.jsp?EID=431948
Created: May 31, 2001
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Transactions FAQ.


Is there some way to implement multi-tasking in Java (like "fork()" on
UNIX)?
Location: http://www.jguru.com/faq/view.jsp?EID=440411
Created: Jun 17, 2001
Author: Finlay McWalter (http://www.jguru.com/guru/viewbio.jsp?EID=13911)
Question originally posed by Motor Qian
(http://www.jguru.com/guru/viewbio.jsp?EID=397581

There isn't anything very portable, but (if you're willing to provide an implementation
for each of your target platforms) you can either:

• Have the host OS execute a new JVM (typically by calling Runtime.exec())


and pass it the name of the classfile you want to "fork" to.
• Use JNI (from C code) to create a new JVM

Neither of these is as good as fork, as the new subprogram doesn't inherit any of the
state of its parent.

If you can possibly help it, try to avoid the need for this functionality in the first
place, by using a Java application framework like JES (Java Embedded Server). This
limits a few of the things you might like to do (mostly security and classloader stuff)
but allows multiple programs to coexist in the same JVM. This has the additional
benefit that it's much more efficient than a true fork - you still have only one JVM
instance and only one OS process, which is much lighter weight than creating
multiple processes each running a JVM.

[See also What is the difference between multithreading and multitasking? ]

Comments and alternative answers

you still need to consider IPC!


Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295), Aug 12, 2001
Even though you can exec multiple Jvms, you still have issues like
1) synchronisation to a shared resources (there is not equivalent like global semaphore
or a mutex)
2) ipc (interprocess communication) between the various jvms. You need to consider
using CORBA or RMI or pure sockets
3) others like housekeeping, monitoring, etc.

In short, java is not strong in this multi-tasking area. As the previous reader
suggested, why don't you consider the EJB architecture (which solves a lot of the
above issues) in the first place? I would be interested to hear your opinion. :-)

If an object is referenced by a local variable -- is it safe from concurrency


issues?
Location: http://www.jguru.com/faq/view.jsp?EID=440412
Created: Jun 17, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Richard Robinson
(http://www.jguru.com/guru/viewbio.jsp?EID=395750

No. The local variable only holds a pointer to an object; if other threads can also
point to this object, then it needs to be made thread-safe.

See also How do I ensure that my servlet is thread-safe?

I am looking for a monitoring tool that will give me the status of the threads
inside Weblogic? We are running Weblogic Server 5.1.0 service pack 8 on
HPUX 11 servers in our production environment. Weblogic is the web front
end with an LDAP piece for user verification. At times, Weblogic hangs up
and does not recover. My theory is that it is a problem with threads. So, I
am looking for a monitoring tool that will give me the status of the threads
inside Weblogic. The program would need to be able to display the status in
a graph and be able to store the results so that I can look at past history for
patterns, etc. The JDK version we are using is 1.2.2.07 and we have a
HotSpot Virtual Machine. The monitoring tool would need to run on my
desktop (Windows NT) and connect to the Unix servers to monitor them. I
have tried unnsuccessfully Sitraka's software, JProbe Threadalyzer and the
Glance Utility is not robust enough. Please let me know if you know of a
program that fits the above description.
Location: http://www.jguru.com/faq/view.jsp?EID=440414
Created: Jun 17, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Paul Breheny
(http://www.jguru.com/guru/viewbio.jsp?EID=321267

I never seen nothing more marvelous with Java Thread (also within Weblogic) than
Numega's JCheck. It's unbelievable!
Comments and alternative answers

Monitoring Tool for WLS


Author: Amit Chawla (http://www.jguru.com/guru/viewbio.jsp?EID=47642), Jun 17,
2001
You could also try Mercury Interactive's Astra LoadTest 5.0 for BEA's Webogic

How can I synchronize across two different classes?


Location: http://www.jguru.com/faq/view.jsp?EID=440416
Created: Jun 17, 2001 Modified: 2005-08-03 18:49:58.927
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Artur de Sousa Rocha
(http://www.jguru.com/guru/viewbio.jsp?EID=70489

The solution is to use a different monitor.

When you make a method synchronized, you are specifying that the currently
running thread should obtain a monitor (lock) on the object which has the method. If
you call another synchronized method on the same object, then everything's fine:
you don't lose the lock, and other threads can't interfere.
The problem arises when you want to prevent other threads from interfering when
calling methods across multiple objects. The solution is to get the VM to obtain a lock
on a different object, and retain that lock until you are finished performing all of your
methods, etc.

Instead of declaring a method synchronized:

public synchronized void myMethod(){


.
.
.
}

Declare it non-synchronized, but use a synchronized block inside of your code:

public void myMethod(){


synchronized(this){
.
.
.
}
}

The execution of these two methods is identical, except that the first one is a bit
more efficient. However, you still haven't solved the problem, because you're still
locking this. You need another object to lock. Let me set up a longer example:

public Driver{
public static void main(String[] args){
Test1 t1 = new Test1();
Test2 t2 = new Test2();

t1.doSomething();
t2.doSomething();
}
}

Let's say that you want to synchronize the calls to t1 and t2. It would be nice to do
something like this:

synchronized(t1, t2){
...
}

Unfortunately, Java doesn't allow that kind of thing. Here's the part you've been
waiting for:

public Driver{
private static Object lock = new Object();

public static void main(String[] args){


Test1 t1 = new Test1();
Test2 t2 = new Test2();
synchronized(lock){
t1.doSomething();
t2.doSomething();
}
}
}

That's it! You've used an "impartial" object as the lock. You just have to make sure
that other methods that want to use these methods like this are similarly
synchronized, AND using the same lock object. You might want to create a singleton
lock or something and always synchronize on that.

Another solution would be to create a static method in a class that was synchronized,
and have that method make all the other method calls for you. It's basically the
same thing as I have just explained: the "impartial" lock object is just the class that
contains the static method, in this case.

Good luck,

-chris

When returning from a wait(long), can I tell whether my object was


signaled or the wait timed out?
Location: http://www.jguru.com/faq/view.jsp?EID=440458
Created: Jun 17, 2001 Modified: 2005-08-03 18:35:08.348
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Zohar Melamed
(http://www.jguru.com/guru/viewbio.jsp?EID=428429

There is a pretty standard way to check for this type of thing. You'll have to re-check
your condition after the call to wait(timeout) returns:
public synchronized boolean acquire(long waitfor){
if(count == 0){
wait(waitfor);

if(count == 0)
return false;
count--;
}
return(true);
}

Most developers usually put the wait(timeout) in a while loop, since your thread
could be woken up by a notifyAll(), and another thread might have beaten you to the
synchronization lock. In that case, you'll want to start waiting, again.

You should check out Doug Lea's Concurrent Programming in Java. It has lots of
examples of guarded semaphores and locks and other stuff, all set in threaded
environments.

Good luck,
-chris
Comments and alternative answers

Repair
Author: rami cohen (http://www.jguru.com/guru/viewbio.jsp?EID=712643), Jan 8,
2002
public synchronized boolean acquire(long waitfor){
if(count == 0){
wait(waitfor);
if(count == 0)
return false;
}
count--;
return(true);
}

How do I stop a daemon thread gracefully when the server shuts down?
Location: http://www.jguru.com/faq/view.jsp?EID=448700
Created: Jul 2, 2001
Author: karthik Natarajan (http://www.jguru.com/guru/viewbio.jsp?EID=446853)
Question originally posed by Smita Bansal
(http://www.jguru.com/guru/viewbio.jsp?EID=446826

[ I have writeen a servlet which performs a task repeatedly after every fifteen
minutes. I have used the run method and sleep for the same purpose. This servlet
once started wiil go on executing the run method indefinitely . Obviously since the
servlet will not be reloaded again and again the thread will not be spawned again and
again. But when we close the servlet runner the servlet will end abruptly. How do I
ensure that the thread is terminated properly when the servlet runner is shutdown.]

Instead of performing a sleep, you can perform a timed wait. (i.e) Instead of
Thread.sleep(900000) use wait(900000).

For a graceful exit, you can interrupt the thread when you close the application.
Handle the interrupted exception provided in wait. Also you can use isInterrupted to
check if the thread is interrupted.

How can i check the status of a java Thread using JVMDI? (for deadlocks
etc.)
Location: http://www.jguru.com/faq/view.jsp?EID=463920
Created: Jul 28, 2001 Modified: 2005-08-03 18:24:19.955
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

// ThreadTool.java
class ThreadTool {
public static final int THREAD_STATUS_UNKNOWN = -1;
public static final int THREAD_STATUS_ZOMBIE = 0;
public static final int THREAD_STATUS_RUNNING = 1;
public static final int THREAD_STATUS_SLEEPING = 2;
public static final int THREAD_STATUS_MONITOR = 3;
public static final int THREAD_STATUS_WAIT = 4;
public static final int SUSPEND_STATUS_SUSPENDED = 1;
public static final int SUSPEND_STATUS_BREAK = 2;

public static native int getThreadStatus (Thread t);

static {
System.loadLibrary ("ThreadTool");
}
}

/* DO NOT EDIT THIS FILE - it is machine generated */


#include <jni.h>
/* Header for class ThreadTool */

#ifndef _Included_ThreadTool
#define _Included_ThreadTool
#ifdef __cplusplus
extern "C" {
#endif
#undef ThreadTool_THREAD_STATUS_UNKNOWN
#define ThreadTool_THREAD_STATUS_UNKNOWN -1L
#undef ThreadTool_THREAD_STATUS_ZOMBIE
#define ThreadTool_THREAD_STATUS_ZOMBIE 0L
#undef ThreadTool_THREAD_STATUS_RUNNING
#define ThreadTool_THREAD_STATUS_RUNNING 1L
#undef ThreadTool_THREAD_STATUS_SLEEPING
#define ThreadTool_THREAD_STATUS_SLEEPING 2L
#undef ThreadTool_THREAD_STATUS_MONITOR
#define ThreadTool_THREAD_STATUS_MONITOR 3L
#undef ThreadTool_THREAD_STATUS_WAIT
#define ThreadTool_THREAD_STATUS_WAIT 4L
#undef ThreadTool_SUSPEND_STATUS_SUSPENDED
#define ThreadTool_SUSPEND_STATUS_SUSPENDED 1L
#undef ThreadTool_SUSPEND_STATUS_BREAK
#define ThreadTool_SUSPEND_STATUS_BREAK 2L
/*
* Class: ThreadTool
* Method: getThreadStatus
* Signature: (Ljava/lang/Thread;)I
*/
JNIEXPORT jint JNICALL Java_ThreadTool_getThreadStatus
(JNIEnv *, jclass, jobject);

#ifdef __cplusplus
}
#endif
#endif

/* ThreadTool.c */
#include <jni.h>
#include "ThreadTool.h"
#include <jvmdi.h>

JNIEXPORT jint JNICALL Java_ThreadTool_getThreadStatus


(JNIEnv *env, jclass clazz, jobject thread)
{
jint threadStatus;
jint suspendStatus;
jvmdiError error = JVMDI_GetThreadStatus (env, thread, &threadStatus,
&suspendStatus);
return (threadStatus);
}
More information can be found at:
JavaTM Virtual Machine Debug Interface Reference

How do we stop the AWT Thread? Our Swing application will not terminate.
Location: http://www.jguru.com/faq/view.jsp?EID=467061
Created: Aug 2, 2001 Modified: 2005-08-03 22:31:18.154
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by Nicholas Whitehead
(http://www.jguru.com/guru/viewbio.jsp?EID=1260

You need to explicitly call System.exit(exit_value) to exit a Swing application. This is


because the event dispatcher thread is not a Daemon thread, and won't allow the
JVM to shut down when other threads are dead.

-chris
[See also When exactly is the AWT thread started?]
Comments and alternative answers

A solution that will exit when all the windows you want are closed
Author: Zoltan Luspai (http://www.jguru.com/guru/viewbio.jsp?EID=538098), Nov
3, 2001
The idea is to make the awt threads daemon by starting them from a daemon
ThreadGroup so they will inherit the daemon flag from the ThreadGroup.
This must be done at the beginning of the main() routine, before any awt calls are
made, because there is no way to change a running thread's daemon state.
Also I've created a normal (non daemon) 'guard' thread which monitors the windows
you want. This thread will stay alive until you interrupt it, or the all the windows
monitored exiting. This will also keep your app alive, because it runs until there is a
non-daemon thread. Also this ensures that you won't kill any non daemon thread by
calling the system.exit().
You can download the sources from here: sources
run and see the TestDaemonAWTThreads as demo.

How do I exacute a block of code after the first of two threads finishes, no
matter which one finishes first?
Location: http://www.jguru.com/faq/view.jsp?EID=467065
Created: Aug 2, 2001 Modified: 2005-08-03 22:25:12.509
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Andy Sun (http://www.jguru.com/guru/viewbio.jsp?EID=139266

You probably want to use object.notify. Like this:


Object lock = new Object();
Thread t1 = new MyThread(lock);
Thread t2 = new MyThread(lock);
synchronized (lock) {
t1.start();
t2.start();
lock.wait();
}
// only reached after one thread has called lock.notify()
...

class MyThread extends Thread {


Object lock;
public MyThread(Object lock) {
this.lock = lock;
}
public void run() {
doThing();
synchronized (lock) {
lock.notify();
}
}
}

Search this FAQ for more info on wait and notify. (Use the "Search" box in the upper-
right corner.)

Comments and alternative answers

Bug - it might hang!


Author: drit . (http://www.jguru.com/guru/viewbio.jsp?EID=454295), Aug 5, 2001
Consider the following sequence:- 1) main thread starts t1 2) t1 completes and calls
notify() 3) main thread now starts t2 4) t2 completes and calls notify() 5) main thread
now calls wait() and it will wait forever! :-)

Re: Bug - it might hang!


Author: Mathias Neuhaus (http://www.jguru.com/guru/viewbio.jsp?EID=131203),
Aug 6, 2001
Rewrite the main program...
Object lock = new Object();
Thread t1 = new MyThread(lock);
Thread t2 = new MyThread(lock);
synchronized(lock){
t1.start();
t2.start();
lock.wait();
}
Both threads will be started and blocked because lock is held by main. lock.wait
() will (temporarily) release lock and one of the threads will (hopefully :-) be able
to notify the main program.

Re: Bug - it might hang!


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Aug 18,
2001
Oops. My bad.

I'll fix the code now. How embarassing :-)

What is piped I/O used for?


Location: http://www.jguru.com/faq/view.jsp?EID=478975
Created: Aug 17, 2001 Modified: 2001-08-18 17:21:38.816
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sona s (http://www.jguru.com/guru/viewbio.jsp?EID=431321

The piped I/O streams are for inter-thread communication. They manage the
synchronization across thread boundaries of the buffer.

See Is there any way to communicate between two classes... for an example.

Comments and alternative answers

Alternatives
Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685),
Apr 17, 2002
Circular buffers are an alternative to using pipes. I find them easier to use because
you have one object from which you get streams rather than multiple pipes that need
to be connected. You can also control the size of the buffer that is used.

Circular character buffer implementation: (Instead of piped Readers and Writers)


http://ostermiller.org/utils/CircularCharBuffer.html

Circular byte buffer implementation: (Instead of piped InputStreams and


OutputStreams)
http://ostermiller.org/utils/CircularByteBuffer.html

Re: Alternatives
Author: Stephen Ostermiller
(http://www.jguru.com/guru/viewbio.jsp?EID=576685), Aug 8, 2002
Circular Object buffer implementation:
http://ostermiller.org/utils/CircularObjectBuffer.html

Consider using this instead of Readers and Writers when passing Strings around. It
will only pass references to the strings rather than copying the data. It can of course
be used for Objects as well.

How soon after calling start() will the run() method be executed?
Location: http://www.jguru.com/faq/view.jsp?EID=504951
Created: Sep 27, 2001 Modified: 2005-08-03 22:19:46.743
Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382)
Question originally posed by rajesh kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=493143

Your run() method is not guarenteed to run immediately after the Thread.start()
method is called.

The Java Language Specification gives implementations lots of legroom with respect
to the scheduling of threads. Your thread may start immediately, or it may start 5
minutes later.

Any decent implementation will have your thread start as soon as possible under the
scheduling algorithm, so a five minute wait would be unreasonable.

-chris
Comments and alternative answers

Time diff between Thread start()and run()


Author: Pradeep C (http://www.jguru.com/guru/viewbio.jsp?EID=1008402), Oct 6,
2002

I am facing a similar problem.Please take a look at the following code.

ManagedThread extends Thread {

...

public void run() {

System.err.println("Started running....");

.....

Main prog

for (int i = 0; i < 5; i++) {

thread[i] = new ManagedThread();

thread[i].start();

System.err.println("Started thread....");
}

When the program is executed it is found that the statement "Started thread...." gets
printed but the statement "Started running....." is never printed. This happens only on
Linux. Same code runs fine on Solaris. Any idea why Linux behaves crazily.

Thanks,

pradeep

Re: Time diff between Thread start()and run()


Author: crazy_indian k (http://www.jguru.com/guru/viewbio.jsp?EID=1057431),
Feb 17, 2003
Hi pradeep,
I tested your code on rehat linux 8
I ran your code and it worked perfectly
I mean it printed 'Started thread' and 'Started running'
Here is the sample output i got :
Started thread
Started running
Started thread
Started thread
Started thread
Started thread
Started running
Started running
Started running
Started running

In case of images how does thread spawning work? Can I stop the AWT
from creating a thread for the image while loading?
Location: http://www.jguru.com/faq/view.jsp?EID=505417
Created: Sep 27, 2001
Author: Kevin Riff (http://www.jguru.com/guru/viewbio.jsp?EID=2057) Question
originally posed by Siddharth Mehta
(http://www.jguru.com/guru/viewbio.jsp?EID=471397

You seem to think that a new thread is created for each image you download. That's
simply not the case. Most AWT implementations use a small pool of threads (usually
4) for downloading images. The programmer has no control over these threads or
how they're created.
Comments and alternative answers

Maybe there is a bug...


Author: Neil Weber (http://www.jguru.com/guru/viewbio.jsp?EID=10371), Nov 28,
2001
I'm working on an application that displays 20+ images in a JTable. I used
Toolkit.createImage(). My application mushroomed to 90Mb and then failed with an
OutOfMemoryException. I put my own throttle mechanism in place so that only 4
images are loaded at a time. Now the memory consumption never exceeds 22Mb.

Re: Maybe there is a bug...


Author: Neil Weber (http://www.jguru.com/guru/viewbio.jsp?EID=10371), Nov
28, 2001
I forgot to mention that I was using JDK 1.3.1.

Can we fork another process from Java?


Location: http://www.jguru.com/faq/view.jsp?EID=508849
Created: Oct 2, 2001 Modified: 2005-08-03 22:15:21.106
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by servlet koumei
(http://www.jguru.com/guru/viewbio.jsp?EID=508381

Yes. See Is there some way to implement multi-tasking in Java? and also look at the
docs for java.lang.Runtime.exec().

See also What is the difference between multithreading and multitasking (et al.)?

How to stop a thread which is waiting for a client socket connection?


Location: http://www.jguru.com/faq/view.jsp?EID=525419
Created: Oct 19, 2001
Author: Sebastian Guzy (http://www.jguru.com/guru/viewbio.jsp?EID=521625)
Question originally posed by Jeremy Jin
(http://www.jguru.com/guru/viewbio.jsp?EID=493627

[Short answer: you can't stop the thread, but you can close the socket, which causes
accept to return. -Alex]

Hope that I've understood you properly. So I assume, that you've got something
like:

public class MyServer extends Thread {

// ...
private ServerSocket waitingSocket = null;
// ...

public void run() {


// ...

waitingSocket = new ServerSocket( serverSocketPortNumber );

while( yourAlwaysTrueCondition ) {
connectionSocket = waitingSocket.accept();

delegateInteractionWithClient( connectionSocket );

}
// ...
}
}

To be able to stop your server we have to implement:

• possibility to call server for shutting down (shutdown() method)


• end of waiting for incomming client connections (will be an if statement in
your while loop)

It may look like:


public class MyServer extends Thread {

// ...
private ServerSocket waitingSocket = null;
// ...
private boolean shutdownRequested = false;

public void run() {


// ...

waitingSocket = new ServerSocket( serverSocketPortNumber );

while( yourAlwaysTrueCondition ) {

connectionSocket = waitingSocket.accept()

if( shutdownRequested==false ) {
delegateInteractionWithClient( connectionSocket );
}
else {
break;
}

}
// ...
}

public void shutdown() {

shutdownRequested = true;

new Socket(
waitingSocket.getInetAddress(),waitingSocket.getLocalPort()
).close();
}
}

To start shutdown of your server you have to call the shutdown() method. It will set
shutdownRequested flag to true and force the accept() method in your while loop
to return. Since the shutdownRequested is true, the break statement will be
excecuted. And your server is down.
Comments and alternative answers

How to stop a thread which is waiting for a client socket connection?


Author: David Ferrero (http://www.jguru.com/guru/viewbio.jsp?EID=562888), Nov
27, 2001
Another example is an open socket with a thread in a blocking read(). Closing this
socket should cause the thread to throw an IOException however my experience on
Sun's JDK 1.3.1 JVM on Redhat Linux 7.1 did not show this result but it did on
Windows 98/NT.

Re: How to stop a thread which is waiting for a client socket connection?
Author: Steven Cools (http://www.jguru.com/guru/viewbio.jsp?EID=826480), Apr
5, 2002
there's a parameter called SO_TIMEOUT in the ServerSocket class which is
disabled in default. If you enable it by specifying a > 0 milliseconds timeout, an
InterruptedIOException will occur and you can exit the thread. Use this in
combination with a public method stopThread() like in following example:
public class MyServer extends Thread {

// ...
private threadShouldStop = false;
private ServerSocket waitingSocket = null;
// ...

public stopThread(){
threadShouldStop = true;
}

public void run() {


// ...

waitingSocket = new ServerSocket(serverSocketPortNumber );

waitingSocket.setSoTimeout(500); //500 milliseconds

while( !threadShouldStop ) {

try{
connectionSocket = waitingSocket.accept();

delegateInteractionWithClient( connectionSocket );
}
catch(java.io.InterruptedIOException e){
//probably happened after timeout
}

}
// ...
}
}

Re: How to stop a thread which is waiting for a client socket connection?
Author: Kristina michel (http://www.jguru.com/guru/viewbio.jsp?EID=1216411),
Jan 3, 2005
My IP adress is 203.144.72.196 it is can not sent mail to adress
brian.agland@care-cambodia.org

Stopping the client thread


Author: Irene Moser (http://www.jguru.com/guru/viewbio.jsp?EID=1133589), Dec
11, 2003
I have a legacy app on the server side, which may refuse to interact with my client,
which is trying to open a socket. The client thread "hangs" indefinitely. Is there an
elegant way to solve this problem?

chaged in sdk1.4
Author: Juan Murillo (http://www.jguru.com/guru/viewbio.jsp?EID=1149553), Feb
26, 2004
This no longer holds true, according to the javadocs on the Socket.close() if a thread
is blocking on accept when the sockets is closed it will throw and IOException, check
it out.

Do I have to synchronize read-only access to a text file?


Location: http://www.jguru.com/faq/view.jsp?EID=531243
Created: Oct 26, 2001 Modified: 2001-10-27 08:18:32.688
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Tony Fagan
(http://www.jguru.com/guru/viewbio.jsp?EID=226421

My servlet reads the contents of a text file which I access using a File object.

What issues are involved when this file is read concurrently by several different
threads? Do I have to synchronize access to the file, or does it not matter when
access is read-only?

Should not matter if the file is only for reading. Make sure that you close the file
when you are done using it.
Comments and alternative answers

Do I have to synchronize read-only access to a text file?


Author: Serge Borodai (http://www.jguru.com/guru/viewbio.jsp?EID=1135393), Dec
22, 2003
So, I have to synchronize read-only access to a text file?
Is Vector's clone method thread-safe?
Location: http://www.jguru.com/faq/view.jsp?EID=538552
Created: Nov 4, 2001
Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955)
Question originally posed by Huan Li
(http://www.jguru.com/guru/viewbio.jsp?EID=524792

Sure it is, since it is a Vector which is thread-safe.


Comments and alternative answers

One way to test this


Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 4, 2001
One way to check this is to run
javap java.util.Vector
which will say, among other things, the line
public synchronized java.lang.Object clone();
which more-or-less proves that the method is thread-safe.

(It doesn't -really- prove that it's thread-safe, since merely using synchronized
doesn't guarantee thread safety -- the method could call a non-thread-safe shared
object, for instance -- but it's a good indication.)

How do I reset a scheduled task so that it stops and then is rescheduled for
the next cycle?
Location: http://www.jguru.com/faq/view.jsp?EID=542438
Created: Nov 8, 2001
Author: Alex Healey (http://www.jguru.com/guru/viewbio.jsp?EID=539234)
Question originally posed by adi garg
(http://www.jguru.com/guru/viewbio.jsp?EID=227583

I can do it in the following way


class RemindTask extends TimerTask {
public void run() {
System.out.println("run task");
}
}
Timer timer = new Timer();
timer.schedule(new RemindTask(), 15*1000);

// on reset call timer.cancel()


timer.cancel();

// and then again create a new Timer


timer = new Timer();
timer.schedule(new RemindTask(), 15*1000);

But this would mean wastage of thread resources everytime i want to reset.

[That's really not a very big deal, btw. One thread every 15 seconds is paltry.
Perhaps another guru can answer in more detail. -Alex]
Can I somehow reuse the same Timer object? Or do it in a way so that i don't waste
too much of resources?

Answer:

Instead of Timer.cancel() call TimerTask.cancel() on the task object which


means that the thread can be reused. Then you simply schedule the TimerTask later
when you require it.

What does it mean to lock an object?


Location: http://www.jguru.com/faq/view.jsp?EID=543276
Created: Nov 9, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

Every object instance in Java has a little piece of data hanging off of it called a
"monitor lock." This is similar to a semaphore.

When you use the synchronized keyword, the current thread attempts to obtain the
monitor lock for the object in question (either "this" or the object named explicitly).
If the lock is unavailable, because another thread has acquired it, then the current
thread pauses indefinitely. When it wakes up again, it will have acquired the lock,
and will retain it until the end of the code block where synchronized was used.

One confusing part is that the only thing that this lock locks is access to the lock
itself. It does not control access to instance variables or method access in and of
itself. Other threads can reach in and modify variables and call methods. If you want
the lock to control access to variables, then you must explicitly use the synchronized
keyword every single place in your code that accesses them.

A straightforward way to guarantee that no variable access happens without a lock is


by making all your variables private and using synchronized on all your
accessor/mutator methods (getFoo/setFoo).

See also:

• What are the different uses of the synchronized keyword?


• What is the meaning of calling a method or object "thread-safe?"
• What is deadlock? How can I eliminate it?
• Is there a way in Java to check whether an object is locked?

What are the threading options available when using hotspot on solaris?
What are the performance implications? and defaults for various JVM
versions?
Location: http://www.jguru.com/faq/view.jsp?EID=559483
Created: Nov 23, 2001
Author: Davanum Srinivas (http://www.jguru.com/guru/viewbio.jsp?EID=2011)

http://java.sun.com/docs/hotspot/threads/threads.html
What is double-checked locking? Does it work?
Location: http://www.jguru.com/faq/view.jsp?EID=567267
Created: Nov 29, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

Double-checked locking (DCL) is an idiom recommended by a number of Java books


and articles as a way to reduce synchronization overhead when performing lazy
initialization.

The DCL idiom was designed to support lazy initialization, which occurs when a class
defers initialization of an owned object until it is actually needed.

Unfortunately, DCL isn't guaranteed to work under the current Java Memory Model
(JMM).

See the following articles by Brian Goetz (from which this FAQ answer is excerpted):

• Double-checked locking: Clever, but broken


• Can double-checked locking be fixed?
• Can ThreadLocal solve the double-checked locking problem?

Briefly, the following single-checked code is thread-safe:

class SomeClass {
private Resource resource = null;

public synchronized Resource getResource() {


if (resource == null)
resource = new Resource();
return resource;
}
}
but the following double-checked code is faster, but thread-unsafe:

class SomeClass {
private Resource resource = null;

public Resource getResource() {


if (resource == null) {
synchronized {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}
In my (Alex's) humble opinion, the whole debate is misguided and somewhat moot:
you should just trust the JVM to make synchronized as fast as possible, and most of
the time it will work out OK. Furthermore, if the bottleneck in your code is instance
variable initialization, then it's probably *not* instance variable access (and vice
versa), so pick one (lazy initialization or constructor-time initialization) and cross
your fingers :-)
Comments and alternative answers

Very informative !!
Author: Sandeep Shilawat (http://www.jguru.com/guru/viewbio.jsp?EID=1017906),
Nov 11, 2002
I read DCL for the first time. One of my collegue once asked me to implement the
same and he could not explain why do I to do DCL(Double Checked Locking)?
After going through all three articles I was left pondering which of mission critical
application would need Lazy initialisation at the risk of corrupt references. As it can
be clearly seen as a probem due to reordering of instructions by compilers and caches

As indicated in article 3 , ThreadLocal solves the problem to large extent.

That was very helpful.. Thanks

A Humble Note - Each JVM has its own implementaion of Java language
Specification ( JLS ) and hence separate Java Memory Model( JMM ).I realize the
problem in tweakng in to JVMs business so mostly 'leave to JVM' approach would
solve most of the reallife problems. But realization of this problem is essential for
multhreaded applications like Connection libraries, Messaging systems.

Thanks again !

How do I capture an exception stack trace and put it into a string?


Location: http://www.jguru.com/faq/view.jsp?EID=571084
Created: Dec 3, 2001 Modified: 2005-08-03 15:29:06.957
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by l b
(http://www.jguru.com/guru/viewbio.jsp?EID=570593

Here's how to print the trace in a string:


Exception ex = new Exception("something went wrong");
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
System.out.println("stacktrace = " + stacktrace);
HTH.
Luigi
Comments and alternative answers

Acceess to stack traces


Author: Zohar Melamed (http://www.jguru.com/guru/viewbio.jsp?EID=428429), Dec
4, 2001
If you are looking at parsing the string , to interact with the stack trace ( like an IDE
would do ) dont.

JDK 1.4 has a programatic stack trace access mechanism accessed through Throwabe
:

Also introduced in release 1.4 is the getStackTrace() method, which allows


programmatic access to the stack trace information that was previously available only
in text form, via the various forms of the printStackTrace() method.

This information has been added to the serialized representation of this class so
getStackTrace and printStackTrace will operate properly on a throwable that was
obtained by deserialization.

(from the 1.4 api docs) see Java 2 Platform API Specification

Re: Acceess to stack traces


Author: harsh singh (http://www.jguru.com/guru/viewbio.jsp?EID=1194048), Aug
19, 2004
There is an easy way to get over with the problem.Suppose you want to create a
user defined exception then please do the following
public class ExceptionName extends Exception{
public ExceptionName(String name){
super(name);
}
}
and where you want to throw the exception copy the following. code:
public String getName() throws ExceptionName(){
try{
//code block
}catch(Exception e){
e.printStackTrace();
}
In case you want to keep a track of the exception you can store the value of
e.printStackTrace(),and show it as and when you want to.

Is there an example of a chat server (aka Threaded Virtual Meeting Place) ?


Location: http://www.jguru.com/faq/view.jsp?EID=594559
Created: Dec 23, 2001
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question
originally posed by J Mawhinney
(http://www.jguru.com/guru/viewbio.jsp?EID=543264

• My Purple Server is an open-source chat server with applet and command-line


clients.
• Building a Java chat server by Greg Travis
• IRC Bot Dreams
• Is htere a chat servlet out there?
• Is there a Java IRC chat client with source code?
• How can I develop a chat system using RMI?

Thread synchronization seems to work using a queue -- that the waiting


threads will acquire the released lock in first-in, first-out order. Is this
behavior reliable?
Location: http://www.jguru.com/faq/view.jsp?EID=719867
Created: Jan 14, 2002
Author: Terry Laurenzo (http://www.jguru.com/guru/viewbio.jsp?EID=706411)
Question originally posed by Amit Rosner
(http://www.jguru.com/guru/viewbio.jsp?EID=490823

Any ordering that you are observing is not mandated by the spec. It is therefore
subject to change and should not be relied on (even using a multi-processor machine
instead of a single processor one could affect it). I too have observed this "queue-
like" behavior of waiting threads on the Win32 Sun VMs, but I cannot speak for the
others.

Without knowing what you are trying to accomplish that requires this ordering, I
really cannot spell out a solution. There are a number of ways to ensure ordering,
varying from simple(and usually inefficient) to complex.

Comments and alternative answers

Thread Locking Question


Author: shashkant kale (http://www.jguru.com/guru/viewbio.jsp?EID=974439), Aug
2, 2002
Hello friends, I had one major prob. I had 2 thread one is reader and one is writer and
i had vector. Reader thread reads data from Vecor while Writer writes into it. Now i
wnat to put Lock on Vector so taht when readerth reading from vector,Vector wont get
accessed by writer thread and when i realeas the lock from vetor then it can acc. by
any thread again. can u suggest me how to imple. with small example? thanks in
advance sha

Re: Thread Locking Question


Author: U Chavan (http://www.jguru.com/guru/viewbio.jsp?EID=981744), Aug
12, 2002
Hi, Vector itself sychronized. U.Chvan

Re: Thread Locking Question


Author: payal ahuja (http://www.jguru.com/guru/viewbio.jsp?EID=991966), Aug
30, 2002
good

Re: Thread Locking Question


Author: harsh singh (http://www.jguru.com/guru/viewbio.jsp?EID=1194048), Aug
19, 2004
Vector is a legacy class,as such it is synchronized by default.I guess that answer's
you question. Synchronization is the basic problem with the legacy classes.So care
should be taken when to use them and when not to use them.A better option would
be to use an ArrrayList in case you don't need synchronization. Even if you want
to use synchronization I would suggest you should use ArrayList as that will
improve your performance and secondly because it is fail-safe.

Is it possible to wake up a sleeping thread?


Location: http://www.jguru.com/faq/view.jsp?EID=1041540
Created: Dec 28, 2002 Modified: 2005-08-03 15:14:24.549
Author: G M (http://www.jguru.com/guru/viewbio.jsp?EID=802175) Question
originally posed by khurram shahzad
(http://www.jguru.com/guru/viewbio.jsp?EID=1026702

[I have a thread which is sleeping for a long period of time.Another object has the
object of this sleeping thread. In some event , the second object wants to wake up
the sleeping thread before its due time for sleeping is completed. I would call it
"resuming a sleeping thread". Is this possible or allowed in java?]

Call
sleepingThread.interrupt()

[This will generate an InterruptedException. Now you know why you have to catch
InterruptedException every bl**dy time you call Thread.sleep! -Alex]

Comments and alternative answers

Follow this example to achieve this in a clean way


Author: Shiladitya Sircar (http://www.jguru.com/guru/viewbio.jsp?EID=1173860),
Aug 9, 2004
An elegant way to achieve this is via mutex lock and handling the event in that
synchronized block to notify its parent. An event occurs you can notify the owner of
the object who is responsible, in this case it’s the thread object. First create a a
dummy object .. which could be ur thread object in this example I choose a dummy
object
private static final Object objMutex = new Object();
private boolean someStatus = false;
synchronized(objMutex)
{
someStatus = true;
objMutex.notify();
}
/*
place this code in your waiting logic use the boolean as
the flag to notify the object when changed. This would invoke a
notify on that object its waiting on which in ur
case can be a thread.
*/

synchronized (objMutex)
{
if (!someStatus)
{
try
{
objMutex.wait(timeOut);
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}

What happens if two threads perform a get of one hashmap at the same
time?
Location: http://www.jguru.com/faq/view.jsp?EID=1048741
Created: Jan 21, 2003
Author: Muruganantham Mani
(http://www.jguru.com/guru/viewbio.jsp?EID=1041080) Question originally posed
by Enrique Monton (http://www.jguru.com/guru/viewbio.jsp?EID=755656

[I know a HashMap object is not synchronized if not done explicitly, so in a case


where you have to write and read data in a hashmap from different threads you need
to synchronize it (or use another object).
However in my case I am writing to the HashMap (put) only once and it is done at
the beginnig. Once the HashMap is filled I am going to read it from different threads
at the same time. Do I need to synchronize these reads?]

Synchronization needs to be done only when there is a chance of changing the data
from different threads simultaneously. In your case, it is simply going to be a read,
the synchronization is not required. If you need to remove or modify the values in
the hashmap, then you [may] need to synchronize that.

For synchronizing a HashMap, you can use Collections.synchronizedMap(<your


hashmap reference>) which will return a synchronized map for you, which is
thread-safe.

Remember, synchronization will cause a performance problem. So, it needs to be


used carefully, when really required.

Comments and alternative answers

very good one


Author: sudhakar sadasivuni
(http://www.jguru.com/guru/viewbio.jsp?EID=1101359), Jul 14, 2003
This is a famous question for many of job interviews..godd one.
JDK javadoc is not lucid about it.
Author: Kirill Fakhroutdinov (http://www.jguru.com/guru/viewbio.jsp?EID=501201),
Aug 4, 2003
Actually, JDK javadoc is not lucid about it. They said that "implementation is not
synchronized" but gave as an example only structural modification.

But let's say, we have several threads trying to get objects from the same HashMap
using different keys:
... hm.get("21");
... hm.get("10");
... hm.get("44");
at the same time.

If we are sure that get method is implemented as "atomic" operation that approach is
probably OK. But let's say, that get method is implemented to first save the key we
provided as a private field of HashMap internal state and then makes the search. In
this case results could be unpredictable - while looking for the object with the key
"21" we might get back the object corresponding to the key "44".

So to be sure that the get method returns proper value corresponding to the key we
have to be sure that it is NOT modifying internal state of the shared HashMap object
while searching. We can only hope for that as JDK API says nothing about it, just
"implementation is not synchronized".

Re: JDK javadoc is not lucid about it.


Author: Alexandru Leconiuc
(http://www.jguru.com/guru/viewbio.jsp?EID=1118185), Sep 26, 2003
jdk 1.4.1 javadoc for HashMap is quite clear about synchronization issues:

If multiple threads access this map concurrently, and at least one of the threads
modifies the map structurally, it must be synchronized externally. (A structural
modification is any operation that adds or deletes one or more mappings; merely
changing the value associated with a key that an instance already contains is not a
structural modification.)

Re[2]: JDK javadoc is not lucid about it.


Author: Kirill Fakhroutdinov
(http://www.jguru.com/guru/viewbio.jsp?EID=501201), Sep 26, 2003
When they say "implementation is not synchronized" it usually means that all
methods executed on the instance of the object potentially could be not thread-
safe - whether those are getters or setters (with or without internal structural
modifications). For example, even access to a long or double variable is not
thread-safe in Java because it could be treated nonatomic way:
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733

The examples/explanations that JDK is giving further could be expressed merely


as:
- structural modifications of HashMap are not thread-safe;
- other methods including getters and setters are thread-safe but only if there are
no concurrent structural modifications.

Still it is not lucid - at list for me - whether those explanations provided by JDK
should be considered as examples of "implementation is not synchronized" or
clarifications on how exactly "implementation is not synchronized".

How do I configure a default handler for exceptions that happen in my


threads?
Location: http://www.jguru.com/faq/view.jsp?EID=1251276
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The setUncaughtExceptionHandler() method of Thread, introduced in JDK 5.0, allows


you to configure this behavior by letting you attach an implementation of
Thread.UncaughtExceptionHandler. The interface offers a single method:
public interface Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread, Throwable);
}
By attaching a handler to your thread, if an uncaught exception happens (aka
runtime exception), the registered handler will respond.
public class MyHandlerTest {
public static void main(String args[]) throws Exception {
Thread.UncaughtExceptionHandler handler = new SomeHandler();
Thread.currentThread().setUncaughtExceptionHandler(handler);
System.out.println(1 / 0);
}
}

How can I create a daemon thread?


Location: http://www.jguru.com/faq/view.jsp?EID=1251699
Created: Jul 4, 2005
Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The Thread API allows Threads to be created which are at the mercy of their user
threads. This is accomplished simply by passing true to the setDaemon() method and
invoking the method off an instance of the thread wishing to set it's status.
public void setDeamon(boolean b)
The following is a simple program which creates a thread within the context of the
main thread of execution. Since the main thread is a user thread the created thread
will also be a user thread unless it's status is set otherwise. A couple of notes about
the following code. If the created threads status is not set or false is passed to the
setDameon() method then the created thread will fully execute. This is because the
main thread cannot return until all non-daemon threads are finished. Setting the
status to true in our case doesn't give our daemon thread much time to do it's
bussiness since the main method will quickly execute then return thus stopping our
daemon thread dead in it's tracks. We would be lucky to get a print out of one year!.
So what can we do? Either we can put the main thread to sleep for an amount of
time (enough to give our dameon thread time to do it's business) or simply make it a
non-daemon thread by setting it's status to false.

public class UserThread{


public static void main(String[] args){
Thread t = new Thread(new DaemonThread(525.00f, 0.09f));
t.setDaemon(true);
t.start();
try{
Thread.sleep(250); // must give the deamon thread a chance to run!
}catch(InterruptedException ei){ // 250 mills might not be enough!
System.err.println(ei);
}
}
}

class DaemonThread implements Runnable{


private float principal;
private float futureval;
private float rate;
private float i;
public DaemonThread(float principal, float rate){
this.principal= principal;
this.rate = rate;
}

public void run(){


for(int year = 0; year <= 75; year++){
i = (1 + rate);
futureval = principal * (float)Math.pow(i,year);
System.out.print(principal + " compounded after " + year + " years @
" + rate + "% = " + futureval);
System.out.println();
}
}
}

How can I determine if a thread is alive?


Location: http://www.jguru.com/faq/view.jsp?EID=1252561
Created: Jul 9, 2005
Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The thread class provides a method which can be called on an instance of a Thread
to determine if it is currently executing. If isAlive() returns false the thread is either
a new thread that is not currently executing or it is dead.

public boolean isAlive();

The following code creates a thread and executes it by calling it's start() method.
Before the thread is started a test is performed to determine if the thread is
currently executing. Since the thread is new, isAlive() returns false. You will also
notice within the run() method a reference to the current thread is grabbed using the
following method.
static Thread currentThread()
Since isAlive() is called within the run() method isAlive() returns true because the
thread is executing at that time.
public class ThreadTest{
public static void main(String[] args){
T t = new T("T Thread");
threadStatus(t.isAlive(),t.getName());
t.start();
}
public static void threadStatus(boolean isalive, String tname){
String status = isalive ? "is alive" : " is not alive";
System.out.println(tname +""+ status);
}
}

class T extends Thread{


public T(String tname){
super(tname);
}
public void run(){
Thread t = Thread.currentThread();
String tname = t.getName();
boolean isalive = t.isAlive();
for(int i = 0; i < 9; ++i){
System.out.println(tname + " is alive ?" + " : " + isalive);
}
}
}

How can i tell what state a thread is in?


Location: http://www.jguru.com/faq/view.jsp?EID=1253344
Created: Jul 14, 2005
Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive()
returned false the thread was either new or terminated but there was simply no way
to differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in
by using the getState() method which returns an Enum of Thread.States. A thread
can only be in one of the following states at a given point in time.

• NEW A Fresh thread that has not yet started to execute.


• RUNNABLE A thread that is executing in the Java virtual machine.
• BLOCKED A thread that is blocked waiting for a monitor lock.
• WAITING A thread that is wating to be notified by another thread.
• TIMED_WAITING A thread that is wating to be notified by another thread for a
specific amount of time.
• TERMINATED A thread whos run method has ended.

The folowing code prints out all thread states.


public class ThreadStates{
public static void main(String[] args){
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
}
}
}

Below is a simple program, which prints some of the different states that two threads
are in at certain points of a program. The code simply creates two threads. The first
thread creates a file and fills it with the letters of the alphabet. The second thread
opens the same file and reads the contents printing to the console. You will find
along the way we have a placed a method a strategic points to determine exactly
what state the thread is in at that point in time.

import java.io.*;

public class ThTest2{


public static void main(String[] args){
try{
AlphaBlower ab = new AlphaBlower("AlphaBlower");
ThreadState(ab);
ab.start();
ab.join();
ThreadState(ab);

AlphaSucker as = new AlphaSucker("AlphaSucker");


ThreadState(as);
as.start();
as.join();
ThreadState(as);
}catch(InterruptedException ie){
System.out.println(ie);
}
}
public static void ThreadState(Thread t){
Enum e = t.getState();
System.out.println(t.getName() + " is " + e.name());
}
}
class AlphaBlower extends Thread{

private BufferedWriter bw;


public AlphaBlower(String tname){
super(tname);
}
public void run(){
ThTest2.ThreadState(Thread.currentThread());
try{
bw = new BufferedWriter(new FileWriter("C:" + File.separator +
"AlphaHolder.txt"));
}catch(IOException ioe){
System.err.println(ioe);
}
try{
for(int alpha = 97; alpha <= 122; ++alpha){
try{
bw.write(alpha);
}catch(IOException ioe){
System.err.println(ioe);
}
}
}finally{
try{
bw.close();
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
}

class AlphaSucker extends Thread{


private int c;
private BufferedReader br;
public AlphaSucker(String tname){
super(tname);
}
public void run(){
ThTest2.ThreadState(Thread.currentThread());
try{
br = new BufferedReader(new FileReader("C:" + File.separator +
"AlphaHolder.txt"));
}catch(IOException ioe){
System.err.println(ioe);
}
try{
while((c = br.read()) != -1){
System.out.print((char)c);
}
}catch(IOException ioe){
System.err.println(ioe);
}finally{
try{
br.close();
}catch(IOException ioe){System.err.println(ioe);}
}
}
}

What purpose does the TimeUnit class have?


Location: http://www.jguru.com/faq/view.jsp?EID=1255940
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The TimeUnit class allows you to work with time quanities as both an amount and a
unit of measurement. For instance, instead of always working with milliseconds when
you want to put a thread to sleep, via Thread.sleep(3000), you can say
TimeUnit.SECONDS.sleep(3) and you'll sleep for 3 seconds with both. Other methods
require you to pass in both the instance of TimeUnit (one of NANOSECONDS,
MICROSECONDS, MILLISECONDS, or SECONDS), and the quantity of that unit. See
the tryLock() method of the Lock interface for one such usage.

How can I create a thread pool?


Location: http://www.jguru.com/faq/view.jsp?EID=1255942
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Executors class of the java.util.concurrent class offers newCachedThreadPool(),


newCachedThreadPool(ThreadFactory threadFactory), newFixedThreadPool(int
nThreads), newFixedThreadPool(int nThreads, ThreadFactory threadFactory),
newScheduledThreadPool(int corePoolSize), and newScheduledThreadPool(int
corePoolSize, ThreadFactory threadFactory) for creating an ExecutorService to use as
a thread pool. Just give the pool a Runnable object to run with its execute() method.

How can I tell the difference between wait(timeout) timing out and actually
being notified?
Location: http://www.jguru.com/faq/view.jsp?EID=1255944
Created: Jul 31, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can't directly by using wait and notify, but the can use a similar construct with
the Lock interface of the java.util.concurrent.locks package, with its boolean
tryLock(long time, TimeUnit unit) throws
InterruptedException method. true is returned if the lock was acquired and
false if the waiting time elapsed before the lock was acquired.

Is there a way that I can get the number of threads currently executing
within the JVM?
Location: http://www.jguru.com/faq/view.jsp?EID=1256101
Created: Aug 1, 2005
Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

You can use activeCount() for this. activeCount() returns the number of active
threads that are part of the current thread's thread group.

static int activeCount()

What is a Thread identifer and how can I obtain it?


Location: http://www.jguru.com/faq/view.jsp?EID=1262117
Created: Sep 12, 2005
Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

A Threads identifer is a positive unique long value which is generated when a Thread
is created. Using the following method a Threads identifer can be obtained.

public long getId()


Here is a short example.........
class ThreadID{
public static void main(String[] args){
Thread t1 = new Thread("Thread one");
Thread t2 = new Thread("Thread two");
Thread t3 = new Thread("Thread three");
System.out.println(Thread.currentThread().getName()+ "'s" + "
identifier is " + Thread.currentThread().getId());
System.out.println(t1.getName()+ "'s" + " identifier is " +
t1.getId());
System.out.println(t2.getName()+ "'s" + " identifier is " +
t2.getId());
System.out.println(t3.getName()+ "'s" + " identifier is " +
t3.getId());
}
}

You might also like