java syntax: "synchronized (this)"
Asked Answered
M

5

50

can you please explain to me this piece of java code? I cannot understand this syntax.

synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
}
Marty answered 7/11, 2012 at 7:3 Comment(0)
G
73

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.

Gismo answered 7/11, 2012 at 7:5 Comment(0)
P
14
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

Polaris answered 7/11, 2012 at 7:10 Comment(0)
I
1

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.

Insignificant answered 7/11, 2012 at 7:16 Comment(0)
R
0

synchronized(this) - We get a lock associated with the object pointed to "this". When we use this block, we mean that we are willing to wait until the thread using this monitor, releases it. This makes sense to use the lock, if you change the data object (the object's variables).

wait - causes the currently executing thread to wait until another thread calls the notify method or for the specified duration.

Ravi answered 7/11, 2012 at 7:12 Comment(0)
L
-2

In most situations, only one thread can access the "Synchronized(this)" at a time. But this is not always true!! Consider the code below. In my code I synchronized on a static Object as a lock and everything works fine. When I change the code to synchronize on (this) multiple threads are accessing the code at the same time and it messes everything up. Be careful synchronizing on (this). Note: The code creates threads recursively then displays them in reverse order.

Main

public class Project2 
{
    public static void main(String[] args) throws InterruptedException 
    {
        Object lock = new Object();
        Threads2 t1 = new Threads2(1);
        t1.setName("Thread 1");
        t1.start();
        Threads2.que.add(t1);
        t1.join();
    } 
}

Threads2

public class Threads2 extends Thread
{
    //private final ArrayBlockingQueue<Threads> que = new ArrayBlockingQueue<>(5);
    public static ArrayList<Thread> que = new ArrayList<>(5);
    private volatile int i;
    private static volatile boolean locked = true;
    private static final Object lock = new Object();

    public Threads2(int i) 
    {        
        this.i = i;
    }
    @Override
    public void run()
    {   
        try
        {
            System.out.println("Thread " + i + ": created");       
            synchronized(lock)
            {
                i++;
            }       
            if(i <= 50)
            {
                Threads2 t = new Threads2(i);
                t.setName("Thread " + i);
                t.start();  
                que.add(Thread.currentThread());
            }
            else
            {
                Thread.currentThread().interrupt();
            }
            while(locked)
            {
                Thread.sleep(10000);
            }
        }
        catch(InterruptedException ex)
        {   
            synchronized(lock)
            {
                if(i >= 0)
                {
                    que.get(i-2).interrupt();
                    i--;
                    System.out.println(Thread.currentThread().getName());
                }    
            }       
        }       
    }    
}
Legend answered 17/1, 2018 at 22:9 Comment(2)
Synchronizing on this breaks here because there’s no shared lock.Chessboard
Did someone fix this code? I don't see synchronized(this) and the code seems to work fineGoulder

© 2022 - 2024 — McMap. All rights reserved.