GeeCON Prague 2014*
The moose likes Servlets and the fly likes Synchronize a method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "Synchronize a method " Watch "Synchronize a method " New topic
Author

Synchronize a method

Yuma Shankar
Greenhorn

Joined: Jun 07, 2005
Posts: 24
I have a situation where there is method that creates an ArrayList and populates the ArrayList with data from a database resultset. The application in question is a multithreaded application. Hence, when two users(threads) access this same method, the arraylist elements are getting out of wack-of course -since ArrayList is not synchronized. When I synchronize the method, it still does not help with the ArrayList even though the arraylist is local to the method. I do not understand that... Since by synchronizing I have a lock on the method, why does a object(the arraylist)local to the method not adhere to the lock?
Example below

public ArrayList getRecords(String className, String structure,
String condition)
{
ArrayList a = new ArrayList();

Object recordData,retval;

rs = getData(structure, condition, "query");
while (rs.next())
{ a.add(recordData);
}
}
Kevin Alterman
Greenhorn

Joined: May 21, 2005
Posts: 12
I don't see why you need to synchronize at all. The new object is being created locally within the scope of the function (on the stack) so how does another thread even have access to it?
Rahul Juneja
Ranch Hand

Joined: Aug 03, 2002
Posts: 425
Actually yes, thats what I understood with the code. But yeah if you are passing the arraylist object to this method. the you may be requiring to synchrnoze this method.

Cheers,
Rahul


Rahul Juneja
ThoughtClicks - http://techlabs.thoughtclicks.com
Yuma Shankar
Greenhorn

Joined: Jun 07, 2005
Posts: 24
You are right. It is local, but it is a return parameter. Below is the complete example with the return statement. - Thanks


public synchronized ArrayList getRecords(String className, String structure,
String condition)
{
ArrayList a = new ArrayList();

Object recordData,retval;

rs = getData(structure, condition, "query");
while (rs.next())
{ a.add(recordData);

return a;
}
}
Jack Wiesenthaler
Ranch Hand

Joined: Jul 26, 2001
Posts: 75
Still should not matter unless you're passing the reference up to class level. Each thread has it's own stack
Yuma Shankar
Greenhorn

Joined: Jun 07, 2005
Posts: 24
Thanks guys and sorry about the post. On further debugging, I find that the problem is elsewhere.

Thanks
Rahul Juneja
Ranch Hand

Joined: Aug 03, 2002
Posts: 425
Coool Man ! You found it yourself.

Cheers,
Rahul
 
GeeCON Prague 2014
 
subject: Synchronize a method