devxlogo

Multithreading Applets—the Right Way

Multithreading Applets—the Right Way

The canonical design of multithreaded applets is inherently flawed. You know what I’m talking about: the run method with the repaint/sleep statements embedded in a while(true). Any self-respecting operating systems instructor would fail that design with reckless abandon. Here’s the offensive code:

 public void run() {        while (true) {          repaint();          try {           Thread.sleep(100);          } catch (InterruptedException e) {}        }      } 

Of course, we also have a paint method somewhere, which does all our impressive applet drawing. What’s wrong with this model? The problem is in the sleep statement. Simply speaking, there is no perfect number to put in the sleep statement. The sleep statement is there to hold off calling repaint until we know the VM inside our browser (or appletviewer) completed a call to our paint method. Unfortunately, you can never anticipate how long that will take. That is dependent on the machine, OS, length of the paint method, and what else happens to be going on in the OS at the same time. Even if you found a number that seemed to work well, it may well fail if the OS gets busy with other transient functions, and it may be disastrous when moved to a less powerful machine.

The bottom line is that you are trying to synchronize two threads with that sleep statement. The two threads are your “run” thread and the thread the browser sends in to call your paint. That is synchronization on a “guess” (Dr. Tanenbaum, please forgive us). This is seriously wrong.

How can we solve this problem correctly? In other words, how can I guarantee that only one repaint is called for exactly one paint call? Try this:

 public synchronized void run() {        while (true) {          repaint();          try {           wait();           Thread.sleep(100); // optional          } catch (InterruptedException e) {}        }      }public void paint(Graphics g) {        // drawing        synchronized(this) {          notifyAll();        }    }

What have we done? If you follow the flow you’ll see that we issue a repaint and then wait. The run thread cannot continue until the paint method is done drawing and as its last act, notifies waiting threads. This paradigm guarantees one repaint per paint. We can still put in a sleep to control how much CPU a possibly overzealous applet may take, but it is by no means synchronizing the threads.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist