Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java syntax: "synchronized (this)"

People also ask

What is synchronized this in Java?

synchronized (this) is syntax to implement block-level synchronization. It means that on this object only and only one thread can excute the enclosed block at one time.

What does synchronized this mean?

Definition of synchronize intransitive verb. : to happen at the same time. transitive verb. 1 : to represent or arrange (events) to indicate coincidence or coexistence.

How do you synchronize objects in Java?

Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time.


It means that this block of code is synchronized meaning no more than one thread will be able to access the code inside that block.

Also this means you can synchronize on the current instance (obtain lock on the current instance).

This is what I found in Kathy Sierra's java certification book.

Because synchronization does hurt concurrency, you don't want to synchronize any more code than is necessary to protect your data. So if the scope of a method is more than needed, you can reduce the scope of the synchronized part to something less than a full method—to just a block.

Look at the following code snippet:

public synchronized void doStuff() {
    System.out.println("synchronized");
}

which can be changed to this:

public void doStuff() {
   //do some stuff for which you do not require synchronization
   synchronized(this) {
     System.out.println("synchronized");
     // perform stuff for which you require synchronization
   }
}

In the second snippet, the synchronization lock is only applied for that block of code instead of the entire method.


synchronized (this)

is syntax to implement block-level synchronization.

It means that on this object only and only one thread can excute the enclosed block at one time.

Look here for more detailed answer: Block level synchronization


This first line controls concurrent access to the enclosed block of code. Only one thread at a time can execute the code block at a time. Read Section 2.2 of this tutorial for more information

synchronized (this) {

The enclosed code block below appears to be using a (very poor) method of pausing the thread of execution for a given amount of time.

    try {
        wait(endTime - System.currentTimeMillis());
    } catch (Exception e) {
    }

In addition it is 'swallowing' any exceptions that may be thrown in the course of the wait, which is very naughty indeed.