Balaji G
Balaji G

Reputation: 197

Synchronization and static Synchronization

I am trying to understand the main difference between synchronized and static-synchronized methods.

For instance considering an Employee class that has a couple of instances e1, e2.

synchronized method1() {
    //--- blah blah---
}

When e1 is executing method1() by acquiring object level lock, e2 would be waiting for the lock to be released which was hwld by e1.

In case of static-synchronized also when e1 holding the lock at class level, e2 can't enter into that block.

static synchronized method1() {
    //--- blah blah---
}

How are those two cases different? I dont see any difference bwtween static and non-static synchronized method access.

Upvotes: 2

Views: 155

Answers (1)

assylias
assylias

Reputation: 328568

In your first example, the synchronization is operated at the instance level, so if you call e1.method1() and e2.method1() concurrently, they are allowed to run in parallel.

In your second example, the synchronization is operated at the class level, so if you call e1.method1() and e2.method1() concurrently, they will NOT run in parallel.

Upvotes: 2

Related Questions