Oleksandr
Oleksandr

Reputation: 51

Can a Spring MVC app be multithreaded even if its servlets are not?

When you talk about a Spring app being multithreaded, are you necessarily referring to whether the servlets that are defined in that app are multithreaded?

Or can a Spring app be configured to be multithreaded even if the servlets in the app are not multithreaded?

Upvotes: 5

Views: 9401

Answers (4)

Kyle
Kyle

Reputation: 4238

If I understand your question correctly, the servlets (or java beans) themselves will not need to worry about multi-threading. To create multiple threads, you would instantiate multi-threaded steps or parallel steps by doing the following from within your step configuration:

Multi-Threaded Step:

<step id="loading"> <tasklet
task-executor="taskExecutor"
throttle-limit="20">...</tasklet>
</step>

Parallel Step:

<job id="job1">
<split id="split1" task-executor="taskExecutor" next="step4">
    <flow>
        <step id="step1" parent="s1" next="step2"/>
        <step id="step2" parent="s2"/>
    </flow>
    <flow>
        <step id="step3" parent="s3"/>
    </flow>
</split>
<step id="step4" parent="s4"/>

These examples can be found and commented on more in-depth here.

Upvotes: 3

Bozho
Bozho

Reputation: 597046

Single-threaded servlets are no longer supported. They have been deprecated for a long time, so all servlets are multithreaded.

Then, spring does not use servlets (apart from one - the dispatcher). It uses beans, which can be controllers, services and repositories (daos).

These beans are thread-safe (what I suppose you mean by "multithreaded") if they don't hold any data in their fields (apart from their dependencies)

In short - don't store any data in your spring beans. Pass all required data as parameters.

Upvotes: 7

John Vint
John Vint

Reputation: 40256

Spring MVC uses a single dispatching servlet that will invoke defined Controllers. That being said, the Controller's should be stateless with the exclusions of Spring injected beans. Changing the state of one controller through one action can effect another action.

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120178

typical java web applications are multi-threaded in that every request is handled on its own thread. In such applications, you have to be careful when you have objects that maintain state (via modifying a static property, for example), as they can overwrite each other.

When you are talking about servlets, if two requests come in at the same time to the same servlet, the relevant servlet code is being executed twice concurrently. In frameworks like Struts or Spring, which delegate requests to objects, either the same bean instance can be reused, or a new bean instance could be created for each request, depending on how you have your framework configured (i.e. to use prototypes or singletons in the case of Spring)

Upvotes: 4

Related Questions