AnkitSablok
AnkitSablok

Reputation: 3159

Synchronization issues on a linked list data structure?

Lets suppose there are just 3 nodes in a linked list N0 , N1 , N2 and I want to acquire a lock on N2 using the following synchronized statement

synchronized(N1.next)

what will the above statement do, will it first lock N1 and then N1.next or will it directly lock N1.next?

Upvotes: 0

Views: 75

Answers (3)

Stephen C
Stephen C

Reputation: 719229

You seem to have some strange ideas about how mutexes work; e.g. your previous question as well.

When you execute a synchronized method or a synchronized block, only one mutex is acquired; i.e. only one "thing" is locked. And acquiring that mutex only affects other threads if they attempt to acquire the same mutex.

There is no "if I lock this, will it lock that as well". That only happens if your application consistently uses a specific mutex / lock to mean that.

Upvotes: 2

rocketboy
rocketboy

Reputation: 9741

The syntax is:

SynchronizedStatement:         
  synchronized ( Expression ) 
    Block

Further quoting:

The type of Expression must be a reference type, or a compile-time error occurs.

A synchronized statement is executed by first evaluating the Expression.

If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

So yes in your case whatever N1.next evaluates to, will act as a mutex.

Related JLS §14.19 read.

Upvotes: 0

Kayaman
Kayaman

Reputation: 73568

It will lock N1.next naturally, since that is the object specified.

Upvotes: 0

Related Questions