• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to avoid sharing java Servlet global variable in web application  RSS feed

 
Vic Suyam
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have legacy java servlet web application which has a global user defined class object in the main servlet class. while two requests hit on the same time, the first request values being shared to the second request as well. Please guide me How to handle this scenario and how to avoid this.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66262
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you have discovered servlets should never have read/write instance variables.

Rather, create "scoped variables" on one of the request, session, or application contexts depending upon the needed lifetime of the data. Most often, data only needs to "live" for the duration of a request and so you'd create it on the request. For example: request.setAttribute("someName",someValue)
 
Stephan van Hulst
Saloon Keeper
Posts: 7932
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many MVC frameworks allow you to declare a scope on your injected dependencies. For instance, a data source can be valid for the entire lifetime of an application and it's thread-safe, so in Spring you can annotate it like so:

However, if you want to inject a domain model, it should be request scoped because having only one that's shared between requests will cause concurrency issues, and making your domain model thread-safe will introduce latency issues. Therefore:
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66262
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Except that I doubt anyone's going to port a legacy servlet/JSP project over to Spring just to use an annotation that can be accomplished with a single line of code.
 
Stephan van Hulst
Saloon Keeper
Posts: 7932
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I suppose that's true.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!