Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

6.4. Writing Thread-Safe Actions

Problem

Your Action classes must operate correctly in a multi-threaded environment.

Solution

In your custom Action, never use instance variables to carry per-request state; only use local variables. If you want to have local methods called from the execute() method, pass values to these methods as arguments instead of using instance variables. The Action class in Example 6-3 demonstrates this approach.

Example 6-3. Thread-safe action

package com.oreilly.strutsckbk.ch06;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ThreadSafeAction extends Action {
    
    // This variable is not thread-safe
    private SecurityUtil securityUtil = new SecurityUtil.instance( );

    public ActionForward execute( ActionMapping mapping, 
                                  ActionForm form,
                                  HttpServletRequest request, 
                                  HttpServletResponse response) 
                                  throws Exception {

        // the 'user' variable is thread-safe
        User user = (User) request.getSession( ).getAttribute("user");

        // pass the user to the private method
        doSomething(user);

        // ...

        return mapping.findForward("success");
    }        

    private void doSomething(User user) throws Exception {
        // authenticate the user
        securityUtil.authenticate(user);
    }
}

Discussion

A Struts Action is subject to the same threading issues as a servlet. Internally, Struts maintains and ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page