advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 1.9/5 | Rate this item | 31 users have rated this item.
Expertise: Advanced
Language: Java
June 28, 2006
A Safe Way to Stop a Java Thread
The Thread.stop() method is unsafe and thus deprecated. If the thread being stopped was modifying common data, that common data remains in an inconsistent state.

A better way would be to have a variable indicating if the thread should be stopped. Other threads may set the variable to make the thread stop. Then, the thread itself may clean up and stop.

Consider the basic example shown below. The thread MyThread will not leave common data in an inconsistent state. If another thread calls the done() method for MyThread while MyThread is modifying data, MyThread will finish modifying the data cleanly before exiting.


public class MyThread extends Thread {

    private boolean threadDone = false;

    public void done() {
        threadDone = true;
    }

    public void run() {
        while (!threadDone) {
            // work here
            // modify common data
        }
    }

}
Note that this method does not eliminate concern about synchronization.

Kevin Spiteri
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs