aspose file tools*
The moose likes JSP and the fly likes Object being modified by other instances Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Object being modified by other instances" Watch "Object being modified by other instances" New topic
Author

Object being modified by other instances

Colin Cheng
Greenhorn

Joined: Nov 09, 2004
Posts: 1
Here's the program:

public class Data1 {
private int field1=0;
public int getField1() {return field1;}
public void setField(int i) {field1=i;}
}

public class problemhere extends javax.servlet.http.HttpServlet
{
public Data1 objdata1 = null;

public void fetchdata() {
int i = valuefromrecordset;
objdata1 = new Data1();
objdata1.setField(i);
}

public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
....
fetchdata();
....
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("page1.jsp");
dispatcher.forward(request, response);
....
}

The problem is: when 2 users are running the servlet at the same time, field value set in objdata1 by user1 will be changed by user2's instance(sometimes).

Can someone explain why this happens? I don't want the data obj to be shared in 2 instances. To my knowledge, it shouldn't.

Thanks in advance for any suggestion.
Jayesh Lalwani
Ranch Hand

Joined: Nov 05, 2004
Posts: 502
The Servlet engine will share the instance of you servlet across multiple users. Since, objdata1 is an instance variable, it follows that objdata1 will be shared among users. You need to rework your methods so that objdata1 is not an instance variable. You should probably make objdata1 a local variable. Some thing like this

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61420
    
  67

"Colin C",

We're pleased to have you here with us on the Ranch, but there are a few rules that need to be followed, and one is that proper names are required. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
Forum Bartender


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object being modified by other instances