• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization

 
Glenny Dsilva
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. can i put this code inside a method to synchronize a particular block
2. does synchoronize(this) block works only on instance variables.

for e.g.


here stmt and con are local variables


private void method1()
{

synchronize(this)
{
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO table1 values
(1,2);
stmt.close();
con.close();
}
}
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. can i put this code inside a method to synchronize a particular block

Yes.

2. does synchoronize(this) block works only on instance variables.

When you use synchronization, you synchronize on an object. With "synchronize (this)", you synchronize on the current object (what "this" points to). When you do that, you lock the current object for concurrent access by other threads. So yes, "synchronized (this)" is a good way to ensure that only one thread has access to the instance variables.

What exactly to you mean with "local variables"? If you mean variables declared inside a method: you do NOT have to synchronize on those. There's a separate copy of those variables for each thread - a thread cannot access the local variables of another thread.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Threads and Synchronization...
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesper de Jong:
What exactly to you mean with "local variables"? If you mean variables declared inside a method: you do NOT have to synchronize on those. There's a separate copy of those variables for each thread - a thread cannot access the local variables of another thread.


As you correctly said, you don't synchronize on variables, but on objects. The local variables of different threads can very well reference the same object, so synchronization might be necessary in some circumstances.

You definitely don't need to synchronize on objects that you create inside a method and don't pass to the outside, though.
 
Glenny Dsilva
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The connection object used is an instance variable. so i synchronized all the methods in the file where the connection object is used.

But sometimes the page is not getting downloaded fully.

Is it because i have synchronized all the methods in the file ?.

Should i just synchronize the Connection instance variable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic