• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance variables

 
Jeppe Sommer
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regarding the multi thread issue in the previous discussion I understand that we shouldn't declare istance variables in the servlet.

But what about declaring instance variables in another class, which is called from the servlet? Please see the example below.

If two theads are requesting MyServlet at the same time, are there any risk that thread 2 could overwrite the public instance variables initiated in the class called SessionHandler, when called from the servlet as below?

Please note that a local instance of SessionHandler is created in the servlets doGet method.

Do you see any problems in the code below in an application with many requests?


 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks fine (the principle - I haven't looked at the detail), because the instance of SessionHandler you're creating is local to the doGet method. As long as everything is local to the method then you're safe from threads interacting.


 
Tim Holloway
Saloon Keeper
Pie
Posts: 18108
52
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As long as the SessionHandler is an object created and destroyed within the scope of the doGet() method, there's no problem with SessionHandler and threads, because each thread has its own stack and a unique instance of SessionHandler will reside there. Since the difference between class members and instance members is that instance members are unique to each instance instead of being shared between instances like class members are, there's no conflict.
 
Jeppe Sommer
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim Holloway wrote:As long as the SessionHandler is an object created and destroyed within the scope of the doGet() method, there's no problem with SessionHandler and threads, because each thread has its own stack and a unique instance of SessionHandler will reside there. Since the difference between class members and instance members is that instance members are unique to each instance instead of being shared between instances like class members are, there's no conflict.


So, do we also need to destroy the SessionHandler object manually, something like? If so, why is that?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic