jayanth
jayanth

Reputation: 85

Can a thread executing in it's critical section be preempted in java?

If it can be ,then what if the thread that preempts the current running thread tries to acquire lock on the same object ? Those threads will forever be in a deadlock,right?

Upvotes: 2

Views: 485

Answers (1)

GhostCat
GhostCat

Reputation: 140475

Think about it:

  • Thread A acquires lock X
  • Thread A is "suspended"
  • Thread B wants to lock on X, too
  • Thread B is blocked

What makes you think that "Thread B is blocked" results in thread A not getting executed at some point?

So yes, given the above scenario, A and B are currently not progressing. But nothing prevents A from being resumed to continue its work, and to release X at some point.

Beyond that, the usual disclaimers: in 2018, there are almost no more single processor systems (that run java). And "pre-emption" is a pretty fuzzy concept, and the actual "threading behavior" of JVMs very much depends on the JVM type and the underlying OS.

Regarding the priority situation: any reasonable implementation will pick the "next" thread to give cycles to from the set of threads that can actually progress. It doesn't matter if B has higher priority: it is blocked. If A can progress, and B can't then at some point A will progress and should release the lock.

Upvotes: 1

Related Questions