File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes thread safety issue....... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "thread safety issue......." Watch "thread safety issue......." New topic
Author

thread safety issue.......

lusha tak
Ranch Hand

Joined: Dec 30, 2000
Posts: 185
Hi all!!
what u have to say about threads safety in the folowing code sample, as my applcation is running fine if accessed by a single user but causes problems such as reslultset is closed or invalid cursor state....etc.(if accessed by multiple users concurrently..)
please help!!!
Lusha

[This message has been edited by lusha tak (edited September 23, 2001).]
[This message has been edited by lusha tak (edited September 23, 2001).]
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

So typically only a single instance of a servlet (or jsp) will created for each page. This means that there is only a single copy of the instance variables. If multiple people hit a single page, multiple threads will be allowed to access that single instance of the servlet class.
Fixing the thread-safety of your code is as simple as changing this:

to this:

In the first version, a person will get a db Connection, start a statement etc, then a second person will come along and overwrite the first first person's Connection.
In the second version, each person accessing the page will get their own version of these variables and they won't interact.
Dave.
lusha tak
Ranch Hand

Joined: Dec 30, 2000
Posts: 185
Thank David....
i will make the changes, the way u have described... one more thing...how do i ensure the same level of independence among various users in my servlets...
i mean, what refers to servlets as this (<%! declarations %> ) in jsp pages..
Thanks for ur precious time...
lusha
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

If I understand your question correctly, you are asking what this looks like in Servlets?
Any instance variable.
Therefore this is not thread-safe:

If you absolutely positively have to use local variables, you either have to handle synchronization issues yourself or have a look at SingleThreadModel.
Dave.
[This message has been edited by David O'Meara (edited September 24, 2001).]
lusha tak
Ranch Hand

Joined: Dec 30, 2000
Posts: 185
Thanks a lot, David!!
Lusha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread safety issue.......