1. can i put this code inside a method to synchronize a particular block
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.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Jul 11, 2001
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.
Joined: May 09, 2005
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.