0

I have a requirement wherein I want to make sure that if a particular method "Repo.get()" is getting called from the class, it should get called inside a synchronized block (or a synchronized method). I can modify the "Repo.get()". But I cannot modify the calling classes.

Check the below example:

class A {
    public void testA() {
        Repo r = new Repo();
        synchronized (this) {
            r.get();
        }
    }
}

class B {
    public void testB() {
        Repo r = new Repo();
        r.get();
    }
}

class Repo {
    public void get() {
        // My code goes here.
        // When called from A, we should be able to print "YES"
        // When called from B, we should be able to print "NO"
    }
}

How can we achieve this?

Thanks, Nikhil

KnockingHeads
  • 1,569
  • 1
  • 22
  • 42
Nikhil
  • 93
  • 1
  • 2
  • 6
  • Your code is breaking the basic concept of synchronization which is either to do synchronization on the same object for different threads or do static synchronization by holding the lock on the entire class. There are other concepts as well like Locks, Semaphores, but this is what you must know first. – KnockingHeads May 11 '21 at 13:03
  • See this for synchronization doubts: https://stackoverflow.com/questions/574240/is-there-an-advantage-to-use-a-synchronized-method-instead-of-a-synchronized-blo?rq=1 – KnockingHeads May 11 '21 at 13:29

1 Answers1

1

it should get called inside a synchronized block (or a synchronized method).

This is a non-sensical requirement. In that I can trivially adhere to it accomplishing absolutely not a thing.

synchronized (new Object()) {
   // this does absolutely nothing
}

synchronized blocks do nothing except interact with other synchronized blocks on the same object reference. Thus, it makes no sense to demand that 'synchronized' is used. It can make sense to demand that 'synchronized on this specific X is used'.

The above code does nothing by definition because it synchronizes on an object that no other thread could possibly reference, thus guaranteeing it is completely useless, which then proves that your requirement is silly.

If you want to upgrade into the non-silly requirement ('must sync on specifically this object reference'):

Thread.holdsLock(objRef) is all you need.

If you want to check if the current thread is holding any lock, well, that's not really possible, but it's good that this isn't possible, because that'd be a silly thing to want to do.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72