Jtest logo




Contents  Previous  Next  Index

TRS.UWNA


Use 'wait()' and 'notifyAll()' instead of polling loops

Description

This rule flags any polling loop.

Using 'sleep()' as a polling loop is not efficient because polling loops take up processor cycles to execute the multiple 'sleep()' calls; using 'wait()' and 'notifyAll()' does not.

Example

 package TRS;
 public class UWNA {
     void method (Object o) {
         while (true) {
             while (getStatus()) {
                 try {
                     sleep (300);    // violation
                 } catch (Exception e) {}
             }
             synchronized (o) {
             // process data.
             }
         }
     }
     boolean getStatus () {
         return _status;
     }
     private boolean _status;
 }

Repair

Replace "while", and 'sleep()' with 'wait()' and 'notifyAll()'.

 
     void method (Object o) {
         while (true) {
             synchronized (o) {
                 while (getStatus()) {
                     try {
                         o.wait ();
                     } catch (Exception e) {}
                 }
                 // process data.
             }
         }
     }

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp.191 - 194.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft