Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance data in Servlet

 
Kalyan avvaru
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was told the best practice is not to have any instance data in a servlet due to concurrency issues. Will this apply to even a read only kind of data? For eg a datasource object at class level.
 
Phani Raju
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
datasource thread-safety depends on the driver you are using, though most of the implementations (oracle, mysql etc) are thread-safe its best to check their doc once. So you can have it as an instance variable, however need to ensure that initialization is done in a thread-safe manner, best if done in the init method.
 
Kalyan avvaru
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks phani...But it had made me to think more. Please enlighten me...i always feel confused with thread issues.
Why the need for thread safe methods in a datasource objects. I thought every time you call a getConnection...you get a new connection.
I was under impression the concurrency issue only matters in resources that are modifiable/writable....where a race condition can occur due to over-writing other threads changes. For objects that are read-only why make sure accessed in a thread-safe manner.
 
Phani Raju
Greenhorn
Posts: 19
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Connection pooling is just one of many benefits we get by going for datasources. When we call the getConnection method on a datasource, the underlying implementation has to take one out of the available pool (could be simply marking this connection as "in use") and this pool could be a list like data structure. This is what needs to be synchronized. Hope it is clear now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic