Synchronizing on this and on other object - java

I think this question must have been asked somewhere but when I look for it I unfortunately find only different topics. Anyway here is the code:
public class A {
Object lockX = new Object();
Object lockY = new Object();
Object lockZ = new Object();
int c1;
int c2;
public void foo1() {
synchronized(lockX) {
c1++;
}
}
public void bar1() {
synchronized(lockY) {
c1++;
}
}
public void foo2() {
synchronized(lockZ) {
c2++;
}
}
public void bar2() {
synchronized(this) {
c2++;
}
}
}
Basically foo1 and bar1 are incorrect. They use different lock to protect c1, so in fact c1 won't be protected and both those functions can run concurrently. My question however is about foo2 and bar2. Are they ok? They also use different locks but bar2 is locking whole object, so does it prevents modifing c2 concurrently?

bar2 is locking whole object
Once you properly understand the semantics of mutual exclusion locks (mutexes), you will realize that this is an empty statement. A mutex doesn't have any inherent scope: a thread either does or does not hold it at any point in time. Synchronizing on this simply acquires the mutex associated with the this instance. Synchronizing on lockZ acquires an entirely independent mutex, and both can be acquired at the same time.

foo2 and bar2 are similar to foo1 and bar1. In case of bar2 the lock is on class A object where as foo2 is using lock of object lockZ.
The object this doesn't become locked, rather the object this is used as the mutex and the body is prevented from executing concurrently with other code sections also synchronized on this.

The quick answer is: NO. Even c2 is not protected for concurrent access because is locked by different object instances. Moreover a better form for
public void bar2() {
synchronized(this) {
c2++;
}
}
is
synchronized public void bar2() {
c2++;
}

As mentioned in #Marko's the semantics of locking is different from what you already conceive.
Synchronizing on an object X does not mean you are applying an access/method execution restriction on object X itself. When a certain thread A synchronizes over an instance X, it restricts other threads from synchronizing on the same instance X until the thread A finishes execution inside the synchronized(X) block and thus releasing the lock over object X. To make it more clear, only one thread at a time can acquire a lock on a single immutable instance of an object, and until this lock is released, any other thread that is trying to acquire a lock on the same instance will block.
Think of a synchronized block as a room with a door, and this door opens with a key, when a thread wants to enter the room and do stuff inside, it takes a key, opens the door then goes inside but keeping the key with it, other threads that want to enter the room with the same key have to wait on the door until the thread inside finishes its business, leaves the room and sets the key free for other threads to use it. If another thread uses a different key, while another thread is already in the room, it can enter the same room and do its business inside while the other thread is still in there and thus those two threads can modify the same stuff in the room, which may cause what is described as a race condition.
So in your case the answer is : No.

Related

Java synchronization/locking

I'm relatively new to concurrency in Java (still have yet to read JCIP, but it's on my list!) and I have a question regarding locking behavior. Specifically, does Java lock on the reference of an object, or on the object itself?
Code example (not an sscce because I don't know how to demo this behavior in practice):
static final Object lockA = new Object();
public void method1() {
synchronized(lockA) {
// do stuff here
}
}
public void method2() {
Object lockB = lockA;
synchronized(lockB) {
// do stuff
}
}
If another thread is executing method1() (and therefore has a lock on lockA), will method2() be allowed to execute?
Thanks!
Synchronization is done on the object, so the synchronized block in method2 will need to wait for the synchronized block in method1 to finish.
Each object has an "intrinsic lock" associated with it (see Intrinsic Locks and Synchronization). The synchronized block uses the intrinsic lock associated with the object on which you are synchronizing.
No, method2() will block since the two methods are synchronizing on the same object (lockB is merely a reference pointing to the same object as lockA).

Java synchronized keyword - Does it protect a class method from being executed at the same time?

I need some clarificaton on how the syncronized keyword works in java 6.
Using the following example class.
class Carrier {
private String[] _collection = new String[2];
public Carrier() {
this._collection[0] = "abc";
this._collection[1] = "123";
}
public syncronized void change(int cId) {
Thread.sleep(3000);
this._collection[cId] = "changed";
}
}
Now, some place in the application, referencing the same object instance of the Carrier class, the .change() method is called, possibly at the same time.
...carrier.change(1);
...
...carrier.change(1);
Will the syncronized keyword prevent asyncronized execution of the method? Will it simply queue the call to .change(), waiting for each one to complete?
Yes, the second thread will block while the first thread is executing. That's because they both try to acquire the monitor on the same object - via this, in this case. So your change method is equivalent to:
public void change(int cId) {
synchronized (this) {
Thread.sleep(3000);
this._collection[cId] = "changed";
}
}
Personally I don't like synchronizing on "this" as it means any other code with access to the object itself could acquire the same monitor. I prefer to create an object just for locking which only code within the class has access to:
private final Object lock = new Object();
public void change(int cId) {
synchronized (lock) {
Thread.sleep(3000);
this._collection[cId] = "changed";
}
}
That will still have the same effect in terms of two threads calling change on the same object, because both threads will still be acquiring the same monitor - just the one associated with the lock-specific object.
Yes, it will prevent the two method calls from executing at the same time.
That is really what the main use of the synchronized keyword is.
When one synchronized method runs, it obtains a 'lock' on the object it is called on. That means no other synchronized code can be run on that object while that method holds the lock. Once the method is done executing, it will release the lock, and other synchronized methods can obtain a lock on that object.
Yes, and yes. (Note that it's synchronized, not syncronized)
Yes - the synchronized keyword prevents simultaneous execution of the method by different threads.
Note: A "class method" is a static method. An "instance method" (ie non-static) is what you have in your question.
synchronized are used for preventing simultaneously accesses in cuncurrent programming.
For example when you have to client, one that reads and another that writes:
Lock here for an exhaustive explanation.

Synchronized makes object lock

I have a confusion about object lock.
The below class having 4 methods, the method addB() is synchronized.
In my scienario, there are 4 threads. When a thread-2 access the addB() method (it creates a lock on Test object), will there any other thread access addC() or addD() same time?
Does the Object lock allows only one thread at a time ?
class Test{
private Integer a;
private Integer b;
private Integer c;
private Integer d;
public void addA(){
synchronized(a) {
a++;
}
}
public synchronized void addB(){
b++;
}
public void addC(){
c++;
}
public void addD(){
d++;
}
}
EDIT:
I have 3 threads(t1, t2 and t3) , and each one is going to access addB(), addC() and addD(). If thread t1 access the method addB(), could thread t2 access addC() method simultaneously? If not what would be t2 state?
class Test{
private Integer a;
private Integer b;
private Integer c;
private Integer d;
public void addA(){
synchronized(a) {
a++;
}
}
public synchronized void addB(){
b++;
}
public synchronized void addC(){
c++;
}
public synchronized void addD(){
d++;
}
}
A lock does indeed allow only one thread at a time, but different locks do not affect each other.
In your example, you have two locks - one on the mutex belonging to a, and one on the mutex belonging to this (which is implicit when you use the synchronized keyword, as you correctly mentioned in your post).
So calls to addB() will be synchronized but will not block calls to any other method. If one thread holds the lock on this, another thread can hold the lock on a, and multiple other threads can execute addC() and addD() concurrently.
Edit: as an aside, you might be interested to learn about the AtomicInteger class if you really are working with Integers. They provide atomic operations such that you don't need to worry about synchronizing around them.
A synchronized block is just an environment where you treat the object it was "executed" on as a reentrant lock. Indeed, only one thread is allowed locking on an object at the same time.
The methods C and D never lock and can be executed any time by any thread.
And as other pointed, when you execute a++, you create a new instance of Integer.
You have two locks in your code, only one Thread will be able to traverse either Lock #1 or Lock #2. Both locks are independent, meaning they do not exclude Threads from each other.
Lock #1 synchronizes on the a Object
public void addA(){
synchronized(a) {
a++;
}
}
lock #2 Synchronizes on the Test Instance (this)
public synchronized void addB(){
b++;
}
addC() and addD() have no locks on them at all, any amount of Threads can access these concurrently.
Lock provides a mechanism for synchronizing the thread. this means that at the same point in time only one thread can access the AddB method of your object.
Unless you release the lock after completion of the code, the next code iteration cannot enter the block.
Locking of thread depends on the instance of the object used
e.g:
class MyClass extends Thread{
Test instanceObj=null;
public MyClass(Test obj){
instanceObj=obj;
}
public void run(){
obj.addB();
}
}
the addB() function can be rewriten as
public void addB(){
synchronized(this){
//func
}
}
Here the lock is on the object for access the snippet of the function.
other functions can be accessed by other threads.
More over the lock on addA is on an object obj.a which has its own indepedent lock.Hence two different threads can acccess addA and addB at the same time.

My Long pending confusion on multi-threading in Java. Need help

I am having this doubt about multi-threading and I have faced lots of questions about in multi-threading in many of the interviews.
I speak a lot of about acquiring a lock on the object as such. My doubt is when you have two methods that are synchronized and there are two threads which wants to access those two methods, ThreadA wants to access MethodA and ThreadB wants to access MethodB.
Now both the methods are in the same object. But I use to say acquiring lock on an object and i have not heard acquiring lock on a method. Now Can both the threads parallely access MethodA and MethodB? My assumption is once you acquire lock on object, no other thread on work on it. Isnt it?
And what is the significance synchronized(XYZ.class)?
No, they cannot. If I understand you correctly then you mean:
class Foo {
public synchronized void methodA () {
doSmth ();
}
public synchronized void methodB () {
doSmthElse ();
}
}
In this case synchronized modifier is equal to:
class Foo {
public void methodA () {
synchronized (this) {
doSmth ();
}
}
public void methodB () {
synchronized (this) {
doSmthElse ();
}
}
}
This means that only 1 thread can work at the same time inside one of these 2 methods on each Foo-object.
And what is the significance synchronized(XYZ.class)?
That's what you have behind the scenes of
class XYZ {
public static synchronized void someMethod () { ... }
}
Declaring a method as synchronized is basically the same as containing the entire method body in a "synchronized(this) { ... }" block. So the lock on synchronized method is on the entire object instance, meaning that you are locking out others who want to use synchronized methods on that same object.
If you want per method synchronization instead of per object synchronization you will have to synchronize on something else, either by using synchronized(guardObject) in that particular method or by using one of the Lock objects in java (most of them added in 1.5).
And what is the significance synchronized(XYZ.class)?
This means that you are using the class as a guard object, it means that the lock in the class itself (not the instance) will be protecting access to the block. The difference to using the object instance as a guard is that if you have ten thousand objects you will only be able to access one of them at a time, compared to protecting access by more than one thread to an instance at a time.
If methodA and methodB use different data structures, and it's safe to call methodA while somebody else is calling methodB, then those two methods should use different locks.
Here's the skinny on synchronized(XYZ.class)
synchronized (XYZ.class) is how you implment the above pattern -- it's a synchronized block that:
acquires a lock on an object (in this class the instance of java.lang.class that represents XYZ)
does some work
releases the lock.
The key is to remember that every object in Java has a lock (the technical term is a monitor) that can be held by only one thread at a time. You can request the lock for any object that you have a reference to.
The synchronized keyword on a method:
public synchronized void foo() {
//do something
}
is just syntactic sugar for this:
public void foo() {
synchronized(this) {
//do something
}
}
There is one significant drawback to this approach: since anyone with a reference to an object can acquire its lock, synchronized methods won't work properly if an external caller acquires and holds the object lock.
(Incidentally, this is why locking on XYZ.class is also a bad idea: it's a globally accesible object, and you never know who might decide to acquire its lock)
To avoid these drawbacks, this pattern is usually used instead of the synchronized method:
private final Object LOCK = new Object();
public void foo() {
synchronized(LOCK) {
//do something
}
}
Since no external caller can have a reference to the LOCK object, only this class can acquire its lock, and the synchronized method will always work as expected.
When you have two different methods that need to be locked separately, the usual way to do that is for each method to lock on a different privately held object:
private final Object LOCKA = new Object();
private final Object LOCKB = new Object();
public void foo() {
synchronized(LOCKA) {
//do something
}
}
public void bar() {
synchronized(LOCKB) {
//do something else
}
}
Then it's possible for a thread to call foo() while another thread is calling bar(), but only one thread will be able to call foo() at a time, and only one thread will be able to call bar() at a time.
Using synchronized(XYZ.class) is very restrictive. This means whatever code is being guarded by this XYZ.class will be executed by one thread only at the same time. You should be aware of this as it could lead to severe starvation problem.
A thread entering into monitor on entrance to critical section defined as 'synchronized'
So you can define each method (not the whole class) as synchronized or even a code block within a method.
http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Can any one tell me the advantage of synchronized method over synchronized block with an example?
Can anyone tell me the advantage of the synchronized method over the synchronized block with an example? Thanks.
There is not a clear advantage of using synchronized method over the block.
Perhaps the only one ( but I wouldn't call it an advantage ) is you don't need to include the object reference this.
Method:
public synchronized void method() { // blocks "this" from here....
...
...
...
} // to here
Block:
public void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} // to here...
}
See? No advantage at all.
Blocks do have advantages over methods though, mostly in flexibility because you can use another object as lock whereas syncing the method would lock the entire object.
Compare:
// locks the whole object
...
private synchronized void someInputRelatedWork() {
...
}
private synchronized void someOutputRelatedWork() {
...
}
vs.
// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();
private void someInputRelatedWork() {
synchronized(inputLock) {
...
}
}
private void someOutputRelatedWork() {
synchronized(outputLock) {
...
}
}
Also if the method grows you can still keep the synchronized section separated:
private void method() {
... code here
... code here
... code here
synchronized( lock ) {
... very few lines of code here
}
... code here
... code here
... code here
... code here
}
The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method). For example, these are semantically equivalent:
synchronized void foo() {
...
}
void foo() {
synchronized (this) {
...
}
}
The latter is more flexible since it can compete for the associated lock of any object, often a member variable. It's also more granular because you could have concurrent code executing before and after the block but still within the method. Of course, you could just as easily use a synchronized method by refactoring the concurrent code into separate non-synchronized methods. Use whichever makes the code more comprehensible.
Synchronized Method
Pros:
Your IDE can indicate the synchronized methods.
The syntax is more compact.
Forces to split the synchronized blocks to separate methods.
Cons:
Synchronizes to this and so makes it possible to outsiders to synchronize to it too.
It is harder to move code outside the synchronized block.
Synchronized block
Pros:
Allows using a private variable for the lock and so forcing the lock to stay inside the class.
Synchronized blocks can be found by searching references to the variable.
Cons:
The syntax is more complicated and so makes the code harder to read.
Personally I prefer using synchronized methods with classes focused only to the thing needing synchronization. Such class should be as small as possible and so it should be easy to review the synchronization. Others shouldn't need to care about synchronization.
The main difference is that if you use a synchronized block you may lock on an object other than this which allows to be much more flexible.
Assume you have a message queue and multiple message producers and consumers. We don't want producers to interfere with each other, but the consumers should be able to retrieve messages without having to wait for the producers.
So we just create an object
Object writeLock = new Object();
And from now on every time a producers wants to add a new message we just lock on that:
synchronized(writeLock){
// do something
}
So consumers may still read, and producers will be locked.
Synchronized method
Synchronized methods have two effects.
First, when one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.
Synchronized Statement
Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: Most often I use this to synchronize access to a list or map but I don't want to block access to all methods of the object.
Q: Intrinsic Locks and Synchronization
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
package test;
public class SynchTest implements Runnable {
private int c = 0;
public static void main(String[] args) {
new SynchTest().test();
}
public void test() {
// Create the object with the run() method
Runnable runnable = new SynchTest();
Runnable runnable2 = new SynchTest();
// Create the thread supplying it with the runnable object
Thread thread = new Thread(runnable,"thread-1");
Thread thread2 = new Thread(runnable,"thread-2");
// Here the key point is passing same object, if you pass runnable2 for thread2,
// then its not applicable for synchronization test and that wont give expected
// output Synchronization method means "it is not possible for two invocations
// of synchronized methods on the same object to interleave"
// Start the thread
thread.start();
thread2.start();
}
public synchronized void increment() {
System.out.println("Begin thread " + Thread.currentThread().getName());
System.out.println(this.hashCode() + "Value of C = " + c);
// If we uncomment this for synchronized block, then the result would be different
// synchronized(this) {
for (int i = 0; i < 9999999; i++) {
c += i;
}
// }
System.out.println("End thread " + Thread.currentThread().getName());
}
// public synchronized void decrement() {
// System.out.println("Decrement " + Thread.currentThread().getName());
// }
public int value() {
return c;
}
#Override
public void run() {
this.increment();
}
}
Cross check different outputs with synchronized method, block and without synchronization.
Note: static synchronized methods and blocks work on the Class object.
public class MyClass {
// locks MyClass.class
public static synchronized void foo() {
// do something
}
// similar
public static void foo() {
synchronized(MyClass.class) {
// do something
}
}
}
When java compiler converts your source code to byte code, it handles synchronized methods and synchronized blocks very differently.
When the JVM executes a synchronized method, the executing thread identifies that the method's method_info structure has the ACC_SYNCHRONIZED flag set, then it automatically acquires the object's lock, calls the method, and releases the lock. If an exception occurs, the thread automatically releases the lock.
Synchronizing a method block, on the other hand, bypasses the JVM's built-in support for acquiring an object's lock and exception handling and requires that the functionality be explicitly written in byte code. If you read the byte code for a method with a synchronized block, you will see more than a dozen additional operations to manage this functionality.
This shows calls to generate both a synchronized method and a synchronized block:
public class SynchronizationExample {
private int i;
public synchronized int synchronizedMethodGet() {
return i;
}
public int synchronizedBlockGet() {
synchronized( this ) {
return i;
}
}
}
The synchronizedMethodGet() method generates the following byte code:
0: aload_0
1: getfield
2: nop
3: iconst_m1
4: ireturn
And here's the byte code from the synchronizedBlockGet() method:
0: aload_0
1: dup
2: astore_1
3: monitorenter
4: aload_0
5: getfield
6: nop
7: iconst_m1
8: aload_1
9: monitorexit
10: ireturn
11: astore_2
12: aload_1
13: monitorexit
14: aload_2
15: athrow
One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance. This improves performance drastically because locking is only required one or two times.
While using synchronized methods, you will need to take extra care if you mix both static synchronized and non-static synchronized methods.
Most often I use this to synchronize access to a list or map but I don't want to block access to all methods of the object.
In the following code one thread modifying the list will not block waiting for a thread that is modifying the map. If the methods were synchronized on the object then each method would have to wait even though the modifications they are making would not conflict.
private List<Foo> myList = new ArrayList<Foo>();
private Map<String,Bar) myMap = new HashMap<String,Bar>();
public void put( String s, Bar b ) {
synchronized( myMap ) {
myMap.put( s,b );
// then some thing that may take a while like a database access or RPC or notifying listeners
}
}
public void hasKey( String s, ) {
synchronized( myMap ) {
myMap.hasKey( s );
}
}
public void add( Foo f ) {
synchronized( myList ) {
myList.add( f );
// then some thing that may take a while like a database access or RPC or notifying listeners
}
}
public Thing getMedianFoo() {
Foo med = null;
synchronized( myList ) {
Collections.sort(myList);
med = myList.get(myList.size()/2);
}
return med;
}
With synchronized blocks, you can have multiple synchronizers, so that multiple simultaneous but non-conflicting things can go on at the same time.
Synchronized methods can be checked using reflection API. This can be useful for testing some contracts, such as all methods in model are synchronized.
The following snippet prints all the synchronized methods of Hashtable:
for (Method m : Hashtable.class.getMethods()) {
if (Modifier.isSynchronized(m.getModifiers())) {
System.out.println(m);
}
}
Important note on using the synchronized block: careful what you use as lock object!
The code snippet from user2277816 above illustrates this point in that a reference to a string literal is used as locking object.
Realize that string literals are automatically interned in Java and you should begin to see the problem: every piece of code that synchronizes on the literal "lock", shares the same lock! This can easily lead to deadlocks with completely unrelated pieces of code.
It is not just String objects that you need to be careful with. Boxed primitives are also a danger, since autoboxing and the valueOf methods can reuse the same objects, depending on the value.
For more information see:
https://www.securecoding.cert.org/confluence/display/java/LCK01-J.+Do+not+synchronize+on+objects+that+may+be+reused
Often using a lock on a method level is too rude. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, you can create dummy objects to implement block level synchronization.
The block level is more efficient because it does not lock the whole method.
Here some example
Method Level
class MethodLevel {
//shared among threads
SharedResource x, y ;
public void synchronized method1() {
//multiple threads can't access
}
public void synchronized method2() {
//multiple threads can't access
}
public void method3() {
//not synchronized
//multiple threads can access
}
}
Block Level
class BlockLevel {
//shared among threads
SharedResource x, y ;
//dummy objects for locking
Object xLock = new Object();
Object yLock = new Object();
public void method1() {
synchronized(xLock){
//access x here. thread safe
}
//do something here but don't use SharedResource x, y
// because will not be thread-safe
synchronized(xLock) {
synchronized(yLock) {
//access x,y here. thread safe
}
}
//do something here but don't use SharedResource x, y
//because will not be thread-safe
}//end of method1
}
[Edit]
For Collection like Vector and Hashtable they are synchronized when ArrayList or HashMap are not and you need set synchronized keyword or invoke Collections synchronized method:
Map myMap = Collections.synchronizedMap (myMap); // single lock for the entire map
List myList = Collections.synchronizedList (myList); // single lock for the entire list
The only difference : synchronized blocks allows granular locking unlike synchronized method
Basically synchronized block or methods have been used to write thread safe code by avoiding memory inconsistency errors.
This question is very old and many things have been changed during last 7 years.
New programming constructs have been introduced for thread safety.
You can achieve thread safety by using advanced concurrency API instead of synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.
Lock Objects support locking idioms that simplify many concurrent applications.
Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.
ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Better replacement for synchronized is ReentrantLock, which uses Lock API
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
Example with locks:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.
Refer to this related question too:
Synchronization vs Lock
Synchronized method is used for lock all the objects
Synchronized block is used to lock specific object
In general these are mostly the same other than being explicit about the object's monitor that's being used vs the implicit this object. One downside of synchronized methods that I think is sometimes overlooked is that in using the "this" reference to synchronize on you are leaving open the possibility of external objects locking on the same object. That can be a very subtle bug if you run into it. Synchronizing on an internal explicit Object or other existing field can avoid this issue, completely encapsulating the synchronization.
As already said here synchronized block can use user-defined variable as lock object, when synchronized function uses only "this". And of course you can manipulate with areas of your function which should be synchronized.
But everyone says that no difference between synchronized function and block which covers whole function using "this" as lock object. That is not true, difference is in byte code which will be generated in both situations. In case of synchronized block usage should be allocated local variable which holds reference to "this". And as result we will have a little bit larger size for function (not relevant if you have only few number of functions).
More detailed explanation of the difference you can find here:
http://www.artima.com/insidejvm/ed2/threadsynchP.html
In case of synchronized methods, lock will be acquired on an Object. But if you go with synchronized block you have an option to specify an object on which the lock will be acquired.
Example :
Class Example {
String test = "abc";
// lock will be acquired on String test object.
synchronized (test) {
// do something
}
lock will be acquired on Example Object
public synchronized void testMethod() {
// do some thing
}
}
I know this is an old question, but with my quick read of the responses here, I didn't really see anyone mention that at times a synchronized method may be the wrong lock.
From Java Concurrency In Practice (pg. 72):
public class ListHelper<E> {
public List<E> list = Collections.syncrhonizedList(new ArrayList<>());
...
public syncrhonized boolean putIfAbsent(E x) {
boolean absent = !list.contains(x);
if(absent) {
list.add(x);
}
return absent;
}
The above code has the appearance of being thread-safe. However, in reality it is not. In this case the lock is obtained on the instance of the class. However, it is possible for the list to be modified by another thread not using that method. The correct approach would be to use
public boolean putIfAbsent(E x) {
synchronized(list) {
boolean absent = !list.contains(x);
if(absent) {
list.add(x);
}
return absent;
}
}
The above code would block all threads trying to modify list from modifying the list until the synchronized block has completed.
As a practical matter, the advantage of synchronized methods over synchronized blocks is that they are more idiot-resistant; because you can't choose an arbitrary object to lock on, you can't misuse the synchronized method syntax to do stupid things like locking on a string literal or locking on the contents of a mutable field that gets changed out from under the threads.
On the other hand, with synchronized methods you can't protect the lock from getting acquired by any thread that can get a reference to the object.
So using synchronized as a modifier on methods is better at protecting your cow-orkers from hurting themselves, while using synchronized blocks in conjunction with private final lock objects is better at protecting your own code from the cow-orkers.
From a Java specification summary:
http://www.cs.cornell.edu/andru/javaspec/17.doc.html
The synchronized statement (§14.17) computes a reference to an object;
it then attempts to perform a lock action on that object and does not
proceed further until the lock action has successfully completed. ...
A synchronized method (§8.4.3.5) automatically performs a lock action
when it is invoked; its body is not executed until the lock action has
successfully completed. If the method is an instance method, it
locks the lock associated with the instance for which it was invoked
(that is, the object that will be known as this during execution of
the body of the method). If the method is static, it locks the
lock associated with the Class object that represents the class in
which the method is defined. ...
Based on these descriptions, I would say most previous answers are correct, and a synchronized method might be particularly useful for static methods, where you would otherwise have to figure out how to get the "Class object that represents the class in which the method was defined."
Edit: I originally thought these were quotes of the actual Java spec. Clarified that this page is just a summary/explanation of the spec
TLDR; Neither use the synchronized modifier nor the synchronized(this){...} expression but synchronized(myLock){...} where myLock is a final instance field holding a private object.
The difference between using the synchronized modifier on the method declaration and the synchronized(..){ } expression in the method body are this:
The synchronized modifier specified on the method's signature
is visible in the generated JavaDoc,
is programmatically determinable via reflection when testing a method's modifier for Modifier.SYNCHRONIZED,
requires less typing and indention compared to synchronized(this) { .... }, and
(depending on your IDE) is visible in the class outline and code completion,
uses the this object as lock when declared on non-static method or the enclosing class when declared on a static method.
The synchronized(...){...} expression allows you
to only synchronize the execution of parts of a method's body,
to be used within a constructor or a (static) initialization block,
to choose the lock object which controls the synchronized access.
However, using the synchronized modifier or synchronized(...) {...} with this as the lock object (as in synchronized(this) {...}), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).
Therefore best practice is to neither use the synchronized modifier nor the synchronized(...) expression in conjunction with this as lock object but a lock object private to this object. For example:
public class MyService {
private final lock = new Object();
public void doThis() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
public void doThat() {
synchronized(lock) {
// do code that requires synchronous execution
}
}
}
You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.
public class MyService {
private final lock1 = new Object();
private final lock2 = new Object();
public void doThis() {
synchronized(lock1) {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThat() and doMore().
}
}
public void doThat() {
synchronized(lock1) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doMore() may execute concurrently
}
}
public void doMore() {
synchronized(lock2) {
// code here is guaranteed not to be executes at the same time
// as the synchronized code in doThis().
// doThat() may execute concurrently
}
}
}
I suppose this question is about the difference between Thread Safe Singleton and Lazy initialization with Double check locking. I always refer to this article when I need to implement some specific singleton.
Well, this is a Thread Safe Singleton:
// Java program to create Thread Safe
// Singleton class
public class GFG
{
// private instance, so that it can be
// accessed by only by getInstance() method
private static GFG instance;
private GFG()
{
// private constructor
}
//synchronized method to control simultaneous access
synchronized public static GFG getInstance()
{
if (instance == null)
{
// if instance is null, initialize
instance = new GFG();
}
return instance;
}
}
Pros:
Lazy initialization is possible.
It is thread safe.
Cons:
getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.
This is a Lazy initialization with Double check locking:
// Java code to explain double check locking
public class GFG
{
// private instance, so that it can be
// accessed by only by getInstance() method
private static GFG instance;
private GFG()
{
// private constructor
}
public static GFG getInstance()
{
if (instance == null)
{
//synchronized block to remove overhead
synchronized (GFG.class)
{
if(instance==null)
{
// if instance is null, initialize
instance = new GFG();
}
}
}
return instance;
}
}
Pros:
Lazy initialization is possible.
It is also thread safe.
Performance reduced because of synchronized keyword is overcome.
Cons:
First time, it can affect performance.
As cons. of double check locking method is bearable so it can be
used for high performance multi-threaded applications.
Please refer to this article for more details:
https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/
Synchronizing with threads.
1) NEVER use synchronized(this) in a thread it doesn't work. Synchronizing with (this) uses the current thread as the locking thread object. Since each thread is independent of other threads, there is NO coordination of synchronization.
2) Tests of code show that in Java 1.6 on a Mac the method synchronization does not work.
3) synchronized(lockObj) where lockObj is a common shared object of all threads synchronizing on it will work.
4) ReenterantLock.lock() and .unlock() work. See Java tutorials for this.
The following code shows these points. It also contains the thread-safe Vector which would be substituted for the ArrayList, to show that many threads adding to a Vector do not lose any information, while the same with an ArrayList can lose information.
0) Current code shows loss of information due to race conditions
A) Comment the current labeled A line, and uncomment the A line above it, then run, method loses data but it shouldn't.
B) Reverse step A, uncomment B and // end block }. Then run to see results no loss of data
C) Comment out B, uncomment C. Run, see synchronizing on (this) loses data, as expected.
Don't have time to complete all the variations, hope this helps.
If synchronizing on (this), or the method synchronization works, please state what version of Java and OS you tested. Thank you.
import java.util.*;
/** RaceCondition - Shows that when multiple threads compete for resources
thread one may grab the resource expecting to update a particular
area but is removed from the CPU before finishing. Thread one still
points to that resource. Then thread two grabs that resource and
completes the update. Then thread one gets to complete the update,
which over writes thread two's work.
DEMO: 1) Run as is - see missing counts from race condition, Run severa times, values change
2) Uncomment "synchronized(countLock){ }" - see counts work
Synchronized creates a lock on that block of code, no other threads can
execute code within a block that another thread has a lock.
3) Comment ArrayList, unComment Vector - See no loss in collection
Vectors work like ArrayList, but Vectors are "Thread Safe"
May use this code as long as attribution to the author remains intact.
/mf
*/
public class RaceCondition {
private ArrayList<Integer> raceList = new ArrayList<Integer>(); // simple add(#)
// private Vector<Integer> raceList = new Vector<Integer>(); // simple add(#)
private String countLock="lock"; // Object use for locking the raceCount
private int raceCount = 0; // simple add 1 to this counter
private int MAX = 10000; // Do this 10,000 times
private int NUM_THREADS = 100; // Create 100 threads
public static void main(String [] args) {
new RaceCondition();
}
public RaceCondition() {
ArrayList<Thread> arT = new ArrayList<Thread>();
// Create thread objects, add them to an array list
for( int i=0; i<NUM_THREADS; i++){
Thread rt = new RaceThread( ); // i );
arT.add( rt );
}
// Start all object at once.
for( Thread rt : arT ){
rt.start();
}
// Wait for all threads to finish before we can print totals created by threads
for( int i=0; i<NUM_THREADS; i++){
try { arT.get(i).join(); }
catch( InterruptedException ie ) { System.out.println("Interrupted thread "+i); }
}
// All threads finished, print the summary information.
// (Try to print this informaiton without the join loop above)
System.out.printf("\nRace condition, should have %,d. Really have %,d in array, and count of %,d.\n",
MAX*NUM_THREADS, raceList.size(), raceCount );
System.out.printf("Array lost %,d. Count lost %,d\n",
MAX*NUM_THREADS-raceList.size(), MAX*NUM_THREADS-raceCount );
} // end RaceCondition constructor
class RaceThread extends Thread {
public void run() {
for ( int i=0; i<MAX; i++){
try {
update( i );
} // These catches show when one thread steps on another's values
catch( ArrayIndexOutOfBoundsException ai ){ System.out.print("A"); }
catch( OutOfMemoryError oome ) { System.out.print("O"); }
}
}
// so we don't lose counts, need to synchronize on some object, not primitive
// Created "countLock" to show how this can work.
// Comment out the synchronized and ending {, see that we lose counts.
// public synchronized void update(int i){ // use A
public void update(int i){ // remove this when adding A
// synchronized(countLock){ // or B
// synchronized(this){ // or C
raceCount = raceCount + 1;
raceList.add( i ); // use Vector
// } // end block for B or C
} // end update
} // end RaceThread inner class
} // end RaceCondition outter class

Categories

Resources