7/6/10

Destroying threads

Destroy method of thread is not advised to use in our big applications. So what can be the best way to ensure that the thread will stop its process.
Its simple we shall use a flag variable .  Lets see a small example of that...



public class TestServlet extends HttpServlet {


    
    private List<TestThread> threads = new ArrayList<TestThread>();


    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        


        try {
            
            try {
               
               
                TestThread tt = new TestThread();
                tt.setDaemon(true);
                tt.StartExecuting();
               
            } catch (Exception ex) {
                Logger.getLogger(SMSGateWayServlet.class.getName()).log(Level.SEVERE, null, ex);
            }


        } catch (Exception ex) {
            Logger.getLogger(SMSGateWayServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    }


    public void destroy() {
        for (TestThread thread : threads) {
            thread.stopExecuting();
        }
    }


   
}


class TestThread extends Thread {


   
    private boolean keepGoing = true;


    public void stopExecuting() {
        keepGoing = false;
    }
     public void StartExecuting() {
        this.start();
    }




    public void run() {
        try {
            
            try {
            
                if (keepGoing) {
                    while (start) {


                        some process
                    }
                }
            } catch (Exception ex) {
                
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

When the servlet destroy method is called the flag is set to false hence it stops the process by checking if statement.

No comments:

Post a Comment

Popular Posts