Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronize a method

 
Yuma Shankar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Yuma Shankar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Still should not matter unless you're passing the reference up to class level. Each thread has it's own stack
 
Yuma Shankar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys and sorry about the post. On further debugging, I find that the problem is elsewhere.

Thanks
 
Rahul Juneja
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Coool Man ! You found it yourself.

Cheers,
Rahul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic