0

1.

public class SynchronizedCounter
 {
private int c = 0;`

     public synchronized void increment() 
     {
         c++;
     }

    public synchronized void decrement() 
    {
        c--;
    }

    public synchronized int value() 
    {
        return c;
    }
}

2.

public class MyThread extends Thread
 {
     private int threadId;
     private final static Object obj = new Object();

     public MyThread(int threadId)
     {
         this.threadId = threadId;
     }

     @Override
     public void run()
     {
         synchronized (obj)
         {
             for (int i = 0; i < 1000; i++)
                 System.out.println(this.threadId);
         }
    }
}

I would like to present my reasoning and ask you to indicate whether it is correct.

Ex 1 All 3 methods are synchronized. They are non-static and synchronized on a given instance of that class. This means that if we have an object c1 of class SynchronizedCounter then if thread1 executes, for example, the increment method then this method as well as all other synchronized methods are blocked for other threads, other threads cannot call these methods at the same time.

Ex 2 Here we are blocking the body of the run method on the final, importantly, static obj object. By virtue of being static, it is a property of the class, and therefore shared by all objects of that class, static obj is a common monitor for all instances of MyThread. So if thread1 calls the run method it will block it on the obj object. And since the obj object is static ,this means that no other threads will not be able to call this method until the thread that blocked it unblocks it.

wydra__
  • 25
  • 4
  • 2
    Seems about right. But you mixed up your modifiers: `static`goes before `final` so your lock should be `private static final Object obj = new Object();` – Valerij Dobler May 04 '23 at 20:01
  • 2
    yes and yes - [this](https://stackoverflow.com/questions/15438727/if-i-synchronized-two-methods-on-the-same-class-can-they-run-simultaneously) might help. – Andrew S May 04 '23 at 20:02

1 Answers1

1

Not quite.

#1 other threads cannot call these methods at the same time

Other threads CAN call the methods BUT they will be blocked from entering the method until the synchronized lock is released, also which thread accesses the lock is indeterminate.

Its equivalent to synchronized(this) { ... }

#2 this means that no other threads will not be able to call this method

Any thread can call the run method, but only a single thread can acquire obj's lock and enter the synchronized block.

See:

Using synchronized forces the JVM to acquire and release the lock, even if there is no contention.

You should look at the package java.util.concurrent.locks for optimistic locking in #2, and java.util.concurrent.atomic for a better way of implementing #1.

Bill Mair
  • 1,073
  • 6
  • 15