开发者

How to make jsp spring application thread safe?

I have a jsp 开发者_C百科application (using Spring) that uses a couple of global variables. I need multiple people to be able to use this program concurrently, however. What is the best way to go about making it thread-safe such that each instance of the program is independent of the others?

::EDIT:: Am I okay if I just don't use any singleton objects?


Each request is handled in its own thread. These threads are managed by the servlet container. It is not a good idea to use static global variables in a servlet. All instance variables are common to all threads, therefore it can lead to ambiguous state.

I recommend saving this type information in a scope variable (application,session, request, page, etc).

If you have to use a global variable then you will need to synchronize the access to it to avoid unknown states.


A typical container uses a thread-per-request model, so you have an easily-recognizable boundary built right in. The general rule is to never store any state in any object that is visible to multiple requests (threads) unless that state is effectively immutable. For example, a singleton controller like this

@Controller
@RequestMapping("/schedule")
class MyController {
    private Scheduler scheduler;

    @RequestMapping(method = RequestMethod.POST)
    public void scheduleSomething(Foo foo) {
        scheduler.schedule(foo);
    }
}

is stateful--the schedular field holds state--but the state is initialized at startup and remains constant across all requests/threads. If you had a singleton controller like this, on the other hand:

@Controller
@RequestMapping("/schedule")
class MyController {
    private Scheduler scheduler;
    private Foo foo;

    @RequestMapping(method = RequestMethod.POST)
    public void scheduleSomething(Foo foo) {
        this.foo = foo;
        scheduler.schedule(this.foo);
    }
}

That is absolutely not safe for concurrent access because all requests go to this same controller, and foo will be constantly changing in a non-thread-safe way. Follow this line of reasoning through your entire application, and you'll be safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜