Threads FAQ From Jguru
Threads FAQ From Jguru
Location: http://www.jguru.com/faq/Threads
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.
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.
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?
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.
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.
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 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.
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.
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..
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
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.
http://www-106.ibm.com/developerworks/java/library/j-threads3.html
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).
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
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).
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.
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:
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.
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.
/**
* This class extends Thread and has the run method. It also * uses
the sleep and the yield methods of the Thread class.
*/
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
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).
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.
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.
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
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
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.
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
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?
synchronized (this) {
...
}
Acquires a lock on the current object instance ("this") at the open brace, and
releases the lock at the close brace.
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.
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?
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.
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.
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.
Use thread.setDaemon(true) to tell the JVM to make the thread a daemon thread.
[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?
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.
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]
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
Useful follow-up can be found at the JCSP page. Using CSP in your design, you can
reason about and prevent thread starvation.
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();
}
[Short answer: threads are lightweight, programs (aka processes or tasks) are
heavyweight. -Alex]
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:
The following example demonstrates their usage and was taken from my Mastering
Java 2 book:
import java.io.*;
public OilRefinery() {
start(); // Start the thread
}
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();
// class with main entry point. Creates the refinery and tanker(s).
public class Pipeline
{
public static void main (String args[])
{
OilRefinery.create();
class Request
{
String message;
Requestor requestor;
interface Requestor
{
void response( String responseMessage );
}
private OilRefinery()
{
mConnectQue = new LinkedList();
keepRefining = true;
return cRefinery;
}
synchronized ( mConnectQue )
{
while ( mConnectQue.size() == 0 )
{
try
{
mConnectQue.wait();
}
catch ( InterruptedException e )
{
}
}
processRequest( request );
processRequest( request );
}
if ( request.message.equalsIgnoreCase("shutdown") )
{
keepRefining = false;
return;
}
if ( request.requestor != null)
{
String responseMessage = request.message.toUpperCase();
request.requestor.response( responseMessage );
}
}
}
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
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.
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.
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.
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?
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..
http://java.sun.com/products/jdk/1.1/docs/guide/rmi/spec/rmiTOC.doc.html
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 [email protected]
(...or any other IO method that wraps read(), like BufferedReader.readLine(). Calling
thread.interrupt() does nothing.)
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 the new (Java 1.4) java.nio.channels package for non-blocking I/O
support.
In terms of doing URL stuff, I suggest that you look at the HTTPClient package.
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]
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.
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.
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:
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:
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?.
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?
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.
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.
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.
Summary:
await(condition) statement;
Java chooses a simpler mechanism where the programmer must loop according to
the condition around a 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.
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.
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.
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.)
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();
}
}
}
Please help
Asante
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
timer.scheduleAtFixedRate(new TimerTask ()
{
public void run()
{
System.out.println("Task Run");
}
}, initialDelay, period);
}
}
Kathleen
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
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]
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 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.
"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.
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]
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
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.
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.
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.
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
-Joel
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.
See also What is the difference between a lightweight and a heavyweight process?
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!
package com.jgk.patterns.singleton;
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.
http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-double-p1.html
// Static initializer
static {
try {
// Perform initialization here
}
catch (Throwable e) {
throw new RuntimeException(e.getMessage());
}
}
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
The confusing part is the fact that the thread of execution in an interrupt handler is
often referred to as an interrupt.
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) {.
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.
[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]
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.
Stephen ...
class Account {
private int id;
private int balance;
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.
• 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.
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.
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.
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)? .
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]
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.
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. :-)
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.
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();
}
import java.awt.*;
public class X
{
public static void main(String[] args)
{
try {
// wait for
'thread' to finish
thread.join();
System.out.println(e);
}
}
}
).start();
}
}
Toolkit.getDefaultToolkit();
import java.awt.*;
public class X
{
static Frame f;
See also: What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?
Comments and alternative answers
System.out.println(Thread.currentThread().getThreadGroup().activeCount());
System.out.println("...");
}
}
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
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.
MultiThreading runs in the Same Address Space and can communicate easily and it's
light weight.
Closing the Folder, Store, or Transport should cause the thread to terminate itself
after delivering any pending events to listeners.
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.
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.
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.
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.
Allen Holub has an interesting survey of some of the problems with threads, and his
proposed solutions, at If I were king.
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.
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
}
try {
synchronized (o) {
try {
doSomething();
}
catch (A) {
a();
}
}
}
catch (B) {
b();
}
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.
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
[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).
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 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
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.
"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.
..."
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);
}
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
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.
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
David.
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
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;
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.
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.
[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.
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.
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.
[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).
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 :-)
/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.
"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
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);
}
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.
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.)
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{
} // end of run()
} // end of MyThread()
- 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
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.
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
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 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)
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)
There isn't anything very portable, but (if you're willing to provide an implementation
for each of your target platforms) you can either:
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.
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. :-)
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.
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
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.
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();
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
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;
static {
System.loadLibrary ("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>
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
-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
Search this FAQ for more info on wait and notify. (Use the "Search" box in the upper-
right corner.)
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.
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.
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
...
System.err.println("Started running....");
.....
Main prog
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
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
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.)?
[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:
// ...
private ServerSocket waitingSocket = null;
// ...
while( yourAlwaysTrueCondition ) {
connectionSocket = waitingSocket.accept();
delegateInteractionWithClient( connectionSocket );
}
// ...
}
}
// ...
private ServerSocket waitingSocket = null;
// ...
private boolean shutdownRequested = false;
while( yourAlwaysTrueCondition ) {
connectionSocket = waitingSocket.accept()
if( shutdownRequested==false ) {
delegateInteractionWithClient( connectionSocket );
}
else {
break;
}
}
// ...
}
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
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;
}
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
[email protected]
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.
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
(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
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:
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.
See also:
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
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):
class SomeClass {
private Resource resource = null;
class SomeClass {
private Resource resource = null;
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
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 !
JDK 1.4 has a programatic stack trace access mechanism accessed through Throwabe
:
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
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.
[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]
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
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.
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".
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.)
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".
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.
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.
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);
}
}
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.
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.*;
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 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.
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.