vignesh
vignesh

Reputation: 568

How can i change the value of a session variable in an arbitrary java class

I have a java servlet that sets a session variable and calls an starts a thread class.I implement is a follows

@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException,IOException
    {

        Integer completePercent = new Integer(10);

        request.getSession().setAttribute("CompletionStatus" , completePercent);

        LogExportingProcess export = new LogExportingProcess();
        export.start();
    }
}

and i have the thread class that performs a long process as follows ;

class LogExportingProcess extends Thread 
{
    public void run()
    {
        //i want to change the value of the percent complete variable in here. 
    }   
}

Now i want to change the value of the completePercent value inside the LogExportingProcess class.How can i achieve it.

Upvotes: 1

Views: 1171

Answers (2)

Michael Akerman
Michael Akerman

Reputation: 329

Integer is not mutable. AtomicInteger would be a nice substitute.

@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
    public void doGet( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException,IOException
    {
        final AtomicInteger completePercent = new AtomicInteger(10);

        request.getSession().setAttribute("CompletionStatus" , completePercent);

        final LogExportingProcess export = new LogExportingProcess( completePercent );
        export.start();
    }
}

class LogExportingProcess extends Thread 
{
    final AtomicInteger completePercent;

    public LogExportingProcess( final AtomicInteger completePercent ) 
    {
       this.completePercent = completePercent;
    }

    public void run()
    {
        completePercent.set( 80 ); //80% complete, substitute with real code
    }   
}

This is preferrable IMHO over holding a reference to the HttpSession object as suggested by Yogesh Badke, since the HttpSession can be garbage collected normally upon timeout, and AtomicInteger increases encapsulation by only sharing a percentage instead of the entire session information.

Upvotes: 0

Yogesh Badke
Yogesh Badke

Reputation: 4587

You will have to pass the Session object while creating LogExportingProcess

class LogExportingProcess extends Thread 
{
    private HttpSession session;

    public LogExportingProcess(HttpSession session) {
       this.session = session;
    }

    public void run()
    {
        session.setAttribute("CompletionStatus" , completePercent);
    }   
}

and one change in ExportLogs class

LogExportingProcess export = new LogExportingProcess(request.getSession());

Upvotes: 1

Related Questions