Some reader favorites:
EJB fundamentals and session beans
Create a scrollable virtual desktop in Swing
Wizard API updated!
Tim Boudreau has released a new version of the Swing Wizard library (version 0.997) that fixes the WizardException bug reported in JavaWorld's recent Open Source Java Project profile. The article's examples have been reworked to test out the new, improved WizardException. Thanks, Tim, for this helpful fix!
Open Source Java Projects: The Wizard API
INDEXHEAD: Glossary of terms
INDEXHEAD: Tips and cautions
These tips and cautions will help you write better programs and save you from agonizing over why the compiler produces error messages.
setPriority(int priority) or yield()? Both methods affect threads similarly. However, setPriority(int priority) offers flexibility, whereas yield() offers simplicity. Also, yield() might immediately reschedule the yielding thread, which accomplishes nothing. I prefer setPriority(int priority), but you must make your own choice.
notify() in the ProdCons2 program because only one thread waits for a condition to occur. In your programs, where more than one thread might simultaneously
wait for the same condition to occur, consider using notifyAll(). That way, no waiting thread waits indefinitely.
wait() or notify() from outside a synchronized context, either call results in an IllegalMonitorStateException.
INDEXHEAD: Miscellaneous notes and thoughts
The source code to the article's ProdCons2 application reveals my use of an if decision statement instead of a loop statement (such as while) to test the writeable condition variable. For example, in ProdCons2's Shared class, you encounter if in the following setSharedChar(char c) method:
synchronized void setSharedChar (char c)
{
if (!writeable)
try
{
wait ();
}
catch (InterruptedException e) {}
this.c = c;
writeable = false;
notify ();
}
Various developers oppose the use of if to test condition variables. Instead, they argue in support of loops. By following their advice, the previous method transforms
into the following method:
synchronized void setSharedChar (char c)
{
while (!writeable)
try
{
wait ();
}
catch (InterruptedException e) {}
this.c = c;
writeable = false;
notify ();
}
Is it better to use if or a loop (such as while)? For ProdCons2, either approach is fine—because I've carefully coded my programs to ensure that a thread sets the appropriate condition
variable (on which another thread waits) prior to waking that thread. For complex programs, where you are uncertain that a
waiting thread's condition variable will be set to an appropriate value prior to waking that thread, you should use a loop.
That way, the just-woken thread can retest its condition variable and wait if that variable contains the wrong value.
INDEXHEAD: Homework
Please complete the following exercise:
Many computer science textbooks introduce the bounded buffer problem—a classic computer science problem that teaches the concept of monitors. According to the bounded buffer problem, a writer thread produces multiple data items stored in a fixed-size memory buffer. When that buffer fills, the writer thread waits. The reader thread notifies the writer thread when the buffer empties. Conversely, the reader thread retrieves data items from the memory buffer. When that buffer empties, the reader thread waits. The writer thread notifies the reader thread when the buffer fills.
The following BB.java source code demonstrates the bounded buffer problem. However, there is a catch. I omitted the source code to the Buffer class. Your job is to complete this program by supplying appropriate code. Make sure to use the wait() and notify() methods:
// BB.java
class BB
{
public static void main (String [] args)
{
Buffer buffer = new Buffer (5); // Buffer holds a maximum of 5 characters
new Writer (buffer).start ();
new Reader (buffer).start ();
}
}
class Buffer
{
// Supply appropriate code in this class
}
class Writer extends Thread
{
private Buffer buffer;
Writer (Buffer buffer)
{
this.buffer = buffer;
}
public void run ()
{
for (int i = 0; i < 26; i++)
buffer.put ((char) ('A' + i));
for (int i = 0; i < 26; i++)
buffer.put ((char) ('a' + i));
for (int i = 0; i < 10; i++)
buffer.put ((char) ('0' + i));
buffer.put ('*'); // Indicate end of data items
}
}
class Reader extends Thread
{
private Buffer buffer;
Reader (Buffer buffer)
{
this.buffer = buffer;
}
public void run ()
{
char c;
while ((c = buffer.get ()) != '*')
System.out.print (c);
System.out.print ('\n');
}
}
Once you finish writing and compiling the code, run the program. You should see the following output:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
INDEXHEAD: Answers to last month's homework
Last month, I asked you two questions and gave you a program to write. My answers appear in red.
No. Each thread has its own private copy of local variables and parameters. That copy exists on the thread's method-call stack.
Synchronization is important because multiple-thread access to critical code sections often results in inconsistencies that produce strange behavior.
run() method. Write a program that demonstrates why you should not synchronize that method.
The following SyncRun source code demonstrates what happens when you synchronize the run() method. If you run this program, you will notice that either thread A or thread B runs to completion before the other thread.
That is due to the running thread holding the lock until it exits run(). As a result, the other thread delays its execution of that method.
// SyncRun.java
class SyncRun implements Runnable
{
public static void main (String [] args)
{
SyncRun sr = new SyncRun ();
Thread t1 = new Thread (sr);
t1.setName ("A");
Thread t2 = new Thread (sr);
t2.setName ("B");
t1.start ();
t2.start ();
}
public synchronized void run ()
{
for (int i = 0; i < 10; i++)
{
System.out.println (Thread.currentThread ().getName ());
try
{
Thread.sleep ((int) (Math.random () * 1000));
}
catch (InterruptedException e)
{
}
}
}
}
Free Download - 5 Minute Product Review. When slow equals Off: Manage the complexity of Web applications - Symphoniq
![]()
Free Download - 5 Minute Product Review. Realize the benefits of real user monitoring in less than an hour. - Symphoniq