File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object being modified by other instances

 
Colin Cheng
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 502
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64173
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic