0

static synchronized method locks in the class object and the synchronized method locks the current instance of an object. I am not able to relate to any real-world examples and cant clearly distinguish the difference between them. So if possible give me some examples that I can relate to concept.

Hemesh
  • 107
  • 9
  • 1
    there is only one class object for all instances, so lock on class will block all callers, lock on instances only callers to the same instance – Iłya Bursov Apr 28 '22 at 13:36
  • So, if there is a lock in instance level, then no other instance can access the class right?, then what is the need of locking it in class level. – Hemesh Apr 28 '22 at 13:47
  • 1
    no, if you lock instance - all other instances can be accessed – Iłya Bursov Apr 28 '22 at 13:49
  • So, if i lock in instance level, another instance can access the class while the first instance is working/executing? – Hemesh Apr 28 '22 at 13:53
  • 1
    yes, caller can access another instance – Iłya Bursov Apr 28 '22 at 13:55
  • Static synchronized should be avoided because you're creating a bottleneck. So there aren't going to be lots of good real world examples because it's not usually a good thing. Sounds like you're not clear on scope of locking. – Nathan Hughes Apr 28 '22 at 14:41

1 Answers1

0

Let's look at Java's Thread class. It offers self explanatory examples.

Synchronized static method - single JVM wide id generator

private static int threadInitNumber;
private static synchronized int nextThreadNum() {
    return threadInitNumber++;
}

Synchronized instance method - lock each thread instance:

public synchronized void start() {
  ...
}
Delta George
  • 2,560
  • 2
  • 17
  • 11