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.
Related
I came across code like this in one of the repos. I checked it out and it works. (Only one thread enters the synchronized block.)
public Void hello(String s) {
synchronized (s) {
i++;
System.out.println(i);
}
return null;
}
My question is is the lock obtained on the String class itself? If yes, wouldn't it mean if code like this exists else where in the code base, they will all wait to obtain a lock on the same object? Thus adding unnecessary delays?
The intrinsic lock on the String object is the lock that gets acquired. But whether locking works depends on if the string is always the same instance or not. String pools and interning will affect this.
That it is difficult to figure out if the same instance will be used is only one reason not to do this.
If two classes in the application use the same string instance then one of them can acquire the lock and shut the other out. So you can have conceptually unrelated objects affecting each other, contending for the same lock.
Also people are going to be confused into thinking they can use the string value to mean something and have code change the value of s inside the synchronized block or method. That will break all the locking. Locks are on the objects, not on the variables. Changing values means the thread currently holding the lock now has the old object but threads trying to get in are trying to get the lock on the new object, a thread can acquire the new object and start executing the synchronized code before the previous thread is done.
It might work by accident sometimes but it is a terrible idea. Use a dedicated object as a lock instead:
private final Object lock = new Object();
This question already has answers here:
Avoid synchronized(this) in Java?
(23 answers)
Closed 7 years ago.
I am reading the Oracle tutorials about multithreading programming in Java. I don't understand why should I create a new object to sync the some part of code? For what reason does the creation of new dummy object serve?
I do understand that creating these two objects will prevent compiler from reordering the code segment guarded by the construction syncronized(lock1){}
However, I would like to know can I use any other objects (except MsLunch) in the construction syncronized(lock1){} ?
What is the motivation behind introducing such construction syncronized(lock1){} ?
Here is the piece of code, I am concerned with:
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
// what is the purpose of these two objects? how do they serve as locks?
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
First some basics:
The synchronization object is used as a key to open a door to a restricted area (the synchronization block).
As long as a thread entered this restricted area it holds the monitor (lock) so that no other thread can enter. When a thread exits the restricted area it releases the monitor and another thread can take it.
This means that each synchronization block that uses the same synchronization object will prevent other thread to enter until the monitor is available (unlocked).
For what reason does the creation of new dummy object serve?
The reason is that you should use objects that are not accessible by others objects than the ones that use them. That's why the synchronization objects are private. If they would be accessible by others, other might use them in their synchronization blocks somewhere in the application. If the synchronizcation object is e.g. public then every other object can use it. This might lead to unexpected usage and might result in deadlocks.
So you should make sure who will get a reference to the synchronization object.
The lock is accessed by the threads to check if the code is currently "in use" or if they can execute it after locking the object themselves.
You may think it could be automatic, but it has a use compilers couldn't infer : you can use the same lock to synchronize multiple code blocks, restraining the access to any of them at the same time.
In my opinion, dummy Object just represents the point of synchronization.
For synchronize different threads, you must be able to declare point of synchronization and(if it is needed) give access to this point from different parts of the code. For example:
private Object lock = new Object();
public void inc1() {
synchronized(lock) {
c1++;
}
}
public void inc2() {
synchronized(lock) {
c2++;
}
}
In this example shown the usage of same point of synchronization from different part of code.
And because Java is Object oriented language i.e. unit of language in Java is Object, we have exactly such a construction.
By the way, you can use any object in as point of synchronization. You can do even this:
public void inc1() {
synchronized(this) {
c1++;
}
}
what is the purpose of these two objects? how do they serve as locks?
As shown in your code, inc1() and inc2() can only be invoked by one thread each. This means that c1 and c2 can be increased just once per thread - but simultaneuosly by two different threads (because both threads synchronize on different objects).
If both blocks were synchronized like this synchronized(lock1), c1 and c2 could not be increased simultaneuosly.
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.
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.
This question already has answers here:
What does 'synchronized' mean?
(17 answers)
Closed 5 years ago.
I have been trying to learn design patterns. This site uses the synchronized keyword, but I don't understand what it does.
I searched on the net and found that it is somewhat related to multi-threading and memory, but I am a mechanical engineer and don't understand what that means.
Can anybody please help me understand threads and the synchronized keyword?
There is no synchronized keyword in C++.
There is one in Java, though, where for methods it means the following two things:
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.
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.
Similar rules apply to arbitrary blocks.
Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.
In the (Java) example
public static synchronized Singleton getInstance()
means that only one thread at a time should be able to access the getInstance() method this to avoid a racing condition.
As the commenters already pointed out, synchronized is a Java keyword.
It means that two threads cannot execute the method at the same time and the JVM takes care of enforcing that.
In C++, you will have to use some synchronization construct, like a critical section or a mutex. You can consult this.