This question already has answers here:
Is 'synchronized' really just syntactic sugar?
(5 answers)
Is there an advantage to use a Synchronized Method instead of a Synchronized Block?
(23 answers)
Closed 10 years ago.
I have read somewhere that these following fragments of code are equivalent regarding syncronized code:
public synchronized void printMsg() {
System.out.println("synchronized");
}
public void printMsg() {
synchronized(this) {
System.out.println("synchronized");
}
}
As far as I know though, when a Thread accesses a synchronized method on an Object, its non-synchronized methods are not locked, namely other Threads can access them using the same instance.
Observing the second fragment, I have the impression that since the code is synchronized on this, a Thread accessing that code acquires the lock on the Object.
My question is whether the other class methods can be accessed by other Threads when an Thraed maintains the lock excecuting the method printMsg() using the second code-snippet?
If no, the above methods are not exactly same. What is true?
Your first method implicitly grabs the lock on this so it is the same as your second method.
Any other method that is not synhronized, or synchronized on this in the method body, does not attempt to lock the object , and can be run concurrently by other threads.
The above methods are equal. A thread doesn't need to acquire a lock on the object to access its methods unless they're marked with synchronized keyword - ergo, all other threads will execute these methods even if there's a thread holding synchronized (this) lock.
Related
This question already has answers here:
What is the purpose of passing parameter to synchronized block?
(3 answers)
Closed 5 years ago.
I was reading about synchronization concept in java and came across synchronized statements .
I want to know , why do we pass arguments to it , though it appears like static block(it's just an example) , and the arguments passed do not have any data type specified with it .
Example :
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
If any one knows about it , please explain .
In a multithreaded application when you want the states of an object to be read and written in a synchronized way by multiple threads then you use synchronized keyword.
The mechanism that Java uses to support synchronization is the monitor. Each object has a monitor associated with it. Synchronized block needs an object to work with, so that the threads in competition can compete and the winner thread can aquire the monitor.
Each non static method in java has an implicit this object upon which the particular method is invoked. If you use synchronized keyword in the method signature then it means you are depending upon the implicit this object for synchronization. If you wish to depend upon any other object then you can use the synchronized blocks and use the object reference in it.
Remember there may be various synchronized blocks but the blocks with synchronized block on same object will only gurantee the proper syncronized execution with respect to each other. Synchronized Blocks which have references of different objects do not force threads to work in synchronized way.
Thus Suppose when there is some threadA which modifies some states of an objectX and works with synchronized block with ObjectA. There may be another piece of code may be in some other class where some other threadB may be reading the states of the same objectX. Now threadB should also do the reading within a synchronized block with ObjectA so that states of objectX are read properly.
This question already has answers here:
What does 'synchronized' mean?
(17 answers)
Closed 6 years ago.
public int synchronizedBlockGet() {
synchronized( this ) {
return i;
}
}
I have come across this code while reading some article. what is synchronized ? a class , or method or interface ? Please explain.
Synchronized or in general synchronization come when you are dealing with threads. For example, let's say there are 2 threads in you program. Both of these threads are using the same object. (Consider a scenario where one thread is writing to an ArrayList and the other one is reading from it). It those cases, we have to ensure that the other thread don't do a read or a write while a thread is writing to the list. This is because, a write to a list will consist of at least 3 steps
read from memory
modify the object(list)
write back to the memory.
In order to make sure that these threads don't intercept and will not cause inconsistencies, we use the concept of thread synchronization.
There are several ways of achieving synchronization including synchronized methods and synchronized blocks. The code you have provided is a synchronized block.
public int synchronizedBlockGet() {
synchronized( this ) {
return i;
}
}
Here what happens is, once a thread is inside the synchronizedBlockGet method, it will lock the entire object(called acquiring the lock of the object) where the above method is.
synchronized(this) means that the current thread will lock the entire object. No other thread can therefore access this object until the current thread leave the synchronized block and release the object. Even though the example you have given is not a necessary situation of synchronization, the thing that happens behind is the same.
Its a keyword and it will allow only single thread at a time to enter into the block.
It will achieve this by acquiring lock on this object.
This question already has answers here:
Java 1.4 synchronization: only allow one instance of method to run (non blocking)?
(4 answers)
Closed 6 years ago.
I need to isolate function myFunc() from executing from several threads. I know how to solve this task with Mutex. Since Java 1.4 not supports Mutex how to solve this task in another way?
In Java all objects have an intrinsic lock, also called a monitor lock. This is enough to provide simple mutual exclusion but it does have limitations.
public final class MyClass1 {
public synchronized void myFunc() {
// Exclusive work here
}
}
The synchronized keyword on the method means that the intrinsic lock of the MyClass1 object instance must be acquired before myFunc can run.
public static final class MyClass2 {
private final Object mutex = new Object();
public void myFunc() {
synchronized (mutex) {
// Exclusive work here
}
// There is no mutual exclusion here
}
}
A block inside of a method can be synchronized for the scope of the block. This also allows you chose the object to acquire the lock of.
An intrinsic lock will either be acquired eventually or the thread will hang. An attempt to acquire an intrinsic lock does not timeout and cannot be interrupted.
An intrinsic lock is reentrant so you do not need to worry about a thread deadlocking with itself. Deadlocks can still happen when acquiring locks in different orders.
The synchronized keyword also ensure memory visibility of reads and write when they both take place in a synchronised code that locks the same object.
https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html
You should also know that the Java memory model has changed since 1.4 so much of the current information will not be applicable.
https://www.ibm.com/developerworks/library/j-jtp03304/
Why do you have to specify, which object has locked a synchronized block of code?
You don't have to specify which object has locked a synchronized method as it is always locked by 'this' (I believe).
I have two questions:
Why can't you block a none static method with an object other than
'this' ?
Why do you have to specify the object that has blocked
synchronized code?
I have read chapter nine of SCJP for Java 6, but I am still not clear on this.
I realize it is probably a basic question, but I am new to Threading.
Why can't you block a none static method with an object other than 'this' ?
You can:
public void foo() {
synchronized (lock) {
...
}
}
Why do you have to specify the object that has blocked synchronized code?
Because that's how the language designers chose to design the language. synchronized, when used on instance methods, implicitely uses this as the lock. synchronized when used on a block must explicitely specify the lock.
You can.
The code
synchronized foo() {
// some stuff
}
Is logically equal to code
foo() {
synchronized(this) {
// some stuff
}
}
I said "logically" because these 2 examples generate different byte code.
If method foo() is static synchronization is done of class object.
However you can wish to create several synchronized blocks that are synchronized on different objects into one class or even into one method. In this case you can use synchronized (lock) where lock is not this:
foo() {
synchronized(one) {}
///..........
synchronized(two) {}
}
You can specify any object you want which should have the lock on the synchronized code block. Actually, you shouldn't use synchronize(this) at all (or maybe be careful about it, see Avoid synchronized(this) in Java?).
EVERY object has a lock on which you can synchronize:
final Object lock = new Object()
synchronized ( lock ) { ... }
If you want to synchronize the whole method, you cannot say on which object, so it is always "this" object.
synchronized foo() {....}
The first way of locking is better, by the way.
It is not recommended to lock each method with this as it reduces the concurrency in most cases. So it is recommended to use Lock Stripping in which only the specific part of the code that needs to be protected is kept in synchronized block.
It is a practice that is explained well in Java Concurrency in Practice. But note this book is useful only when you have some basic experience with threading.
Some nuggets to keep in mind:
Do not overuse synchronization
use method level synchronization only when the whole method needs to be protected
Use different locks to protect two unrelated entities, which will increase the chances of concurrency. or else for reading or writing two unrelated entities threads will block on same lock.
public void incrementCounter1(){
synchronized(lockForCounter1){
counter1++;
}
}
public void incrementCounter2(){
synchronized(lockForCounter2){
counter2++;
}
}
I think your two questions actually are same. let's say if you wanna synchronized a method m of object a between multiple threads, you need a common base system or channel that threads can talk to, this is actually what object lock offers, so when you wanna a method of a object be synchronized there is no need for another object lock to do this, because the object you access itself has this lock, that's how and why lanuage designed.
while synchronized a block is not the same thing, threads can have different talking base other than this object itself, for instance, you can set a same object as synchronized object lock for synchronized block, so all objects of this Class can be synchronized at that block!
From the concurrency tutorial, the Synchronized methods part:
To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to interleave. 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.
Simply put, that's how synchronization in Java works.
You don't have to specify which object has locked a synchronized method as it is always locked by 'this' (I believe).
True for instance methods, for static methods it locks upon the class object.
Why can't you block a none static method with an object other than 'this' ?
Note that:
public synchronized void increment() {
c++;
}
is equivalent in behavior to:
public void increment() {
synchronized(this) {
c++;
}
}
In this code snippet you can replace this with any object you wish.
Why do you have to specify the object that has blocked synchronized code?
Some, let's call it critical, block of code is to be ran only sequentially, but in uncontrolled concurrent environment it is possible that it will be ran in parallel. That's why synchronization mechanisms exists.
So we can divide the code like this:
the code safe to be ran in parallel (default situation)
the code that has to be synchronized (must be marked somehow)
That markation is made via the synchronized keyword and the corresponding lock object.
If you have two different critical code blocks that must not be ran together, they'll both have the synchronized keyword, and let's say they have the same lock object.
While the first block is executing, the lock object becomes "locked". If during that time the second block needs to get executed, the first command of that code block is:
synchronized(lock) {
but that lock object is in locked state because the first block is executing. The execution of the second block halts on that statement until the first block finishes the execution, and unlocks the state of the lock object. Then the second block may proceed with the execution (and lock the lock object again).
That mechanism is called the mutual exclusion and the lock is a general concept not tied to the Java programming language.
The details of the "lock object locking" process can be found here.
You can lock with any instance of an object but programmers usually
use this or locker...
Because it restrict access to that part of code by other threads
(unit of code processing) so you make sure whole of that part run in
consistence and nothing (i.e. a variable) would be alerted by another thread.
Consider:
a = 1;
a++;
Thread one reaches second line and you expect a = 2 but another thread executes first line and instead of 2 you have a = 1 for first thread and a = 2 for second thread. Now:
synchronized (whatever)
{
a = 1;
a++;
}
Now second thread would be blocked from entering into the code block (synchronized body) until first one leaves it (release the lock).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
synchronized block vs synchronized method?
From accepted answer to this question: In Java critical sections, what should I synchronize on?
I learn that
public synchronized void foo() {
// do something thread-safe
}
and:
public void foo() {
synchronized (this) {
// do something thread-safe
}
}
do exactly the same thing. But in first case we make synchronized only one method of object, and in second case we make inaccessible Whole object. So why this two code snippests do same things?
You seem to be mixing things.
Firstly
public synchronized void method() {
}
is equivalent, from a synchronization perspective, to:
public void method() {
synchronized (this) {
}
}
The pros / cons have already been mentioned and the various duplicates give more information.
Secondly,
synchronized(someObject) {
//some instructions
}
means that the instructions in the synchronized block can't be executed simultaneously by 2 threads because they need to acquire the monitor on someObject to do so. (That assumes that someObject is a final reference that does not change).
In your case, someObject happens to be this.
Any code in your object that is not synchronized, can still be executed concurrently, even if the monitor on this is held by a thread because it is running the synchronized block. In other words, synchronized(this) does NOT "lock the whole object". It only prevents 2 threads from executing the synchronized block at the same time.
Finally, if you have two synchronized methods (both using this as a lock), if one thread (T1) acquires a lock on this to execute one of those 2 methods, no other thread is allowed to execute any of the two methods, because they would need to acquire the lock on this, which is already held by T1.
That situation can create contention in critical sections, in which case a more fine grained locking strategy must be used (for example, using multiple locks).
We don't synchronize an object, instead we synchronize a block of code. In the first that block of code is the method itself, while in the second it's the synchronized block.
The object only provides the lock so as to prevent multiple threads from simultaneously entering that block of code. In the first case, the this object (the one on which the method is invoked) will be used implicitly as the lock, while in the second case it doesn't always have to be this object, it could be some other object also.
They do the same thing. The first form is a short-hand for the second form.
One minor difference between the two constructs is this - synchronized blocks are compiled into monitorenter (op-code 0xC2) and monitorexit (op-code 0xC3) instructions.
A synchronized method, when compiled, is distinguished in the runtime constant pool by
the ACC_SYNCHRONIZED flag, which is checked by JVM’s the method invocation instructions. This difference does not have much significance in practice though.
They dont do same things. First part being synched from beginning to end. Second is just synching the block(not whole method). Second one has some flexibility.