Matt
Matt

Reputation: 3677

Is a static builder class thread safe in a Struts ActionServlet?

I've seen the builder pattern recommended in a variety of places, but wasn't sure on thread safety within a Web application using Struts.

I am unclear as to whether the variables of the build static method are shared by, or internal to each thread that invokes the builder code. I have a hunch it's okay, but want to be sure given that the builder code lives inside a Web application and could be invoked by 10s of threads at once.

public static class ExampleBuilder {

    public static Thing build(ActionForm form) {
        String property1 = form.property1;
        String property2 = form.property2;
        String propertyX = form.propertyX;
        ...

        return new Thing(property1, ...);
    }
}

public class ExampleStrutsAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Thing example = ExampleBuilder.build(form)
        return mapping.findForward("success");
    }
}

Upvotes: 1

Views: 312

Answers (2)

AlexR
AlexR

Reputation: 115378

After the code modifications you did I can say that your code is thread-safe anyway because you do not use any member variables into build() method. You can invoke as build() simultaneously from several threads and each thread will use its own method-level variables.

BTW making this class static does not have any sense here. Static modifier in class context is relevant for inner classes only. Inner static class does not have access to instance of outer class. Top level class does not have outer class at all, so it cannot access its instance anyway.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691913

The above build() method only uses local variables, and doesn't access any state that is shared between threads, so it's thread-safe. Local variables are local to each method invocation, and are thus not shared between threads.

The only thread-safety problem you could have is if the form has the scope session (which is a bad practice). In this case, two threads could use the same ActionForm instances. But this is not really a problem of the build() method. Rather a design problem, or a synchronization problem of the execute() method(s) that use this session-scoped ActionForm.

Upvotes: 1

Related Questions