Sunday, 5 August 2018

Java Spin lock implementation

In this article we will see how to implement Spin Lock in Java.

Introduction:

Lets first understand what is Spin Lock. Spin Lock is a type of lock where the threads instead of getting blocked keeps looking for locks. In Spin Lock, the thread does not go into wait state. The thread remains in Runnable / Running state and continuously trying to get lock (say in while loop) and this is the reason it is named as Spin Lock.

Usecase / Advantage:

So the next question that pop ups in mind is that where to use the Spin Lock over Wait Lock. Here are the following use-cases:

  • Avoiding Deadlock : 

    • Spin Lock is another way to avoid Deadlock. Since the thread trying for lock does not go into wait state instead spinning for lock, using Spin Lock avoids deadlock.

  • When there is very small functionality between lock and unlock : 

    • Suppose I want to just write small functionality bounded by locks. If you use mechanism where thread goes to wait state (eg. Reentrant Lock ) and then back to Runnable state (after acquiring lock), this means you are making call cpu expensive for a thread going into wait and runnable state. Perhaps you could choose Spin Lock which is a kind of busy waiting for a very short period of time before acquiring lock.

Disadvantage:

Do-nothing loop : As Spin Locks constantly checking if locks are available, it keeps wasting CPU time which could be allocated to other productive thread. Thats why longer duration of spin lock is not recommended.

Code Example:

Here is the Code Example in Java for Spin Lock Implementation:


SpinLock.java
package com.blogspot.tech693;

import java.util.concurrent.locks.ReentrantLock;

public class SpinLock extends ReentrantLock{

public SpinLock() {
  super();
 }


 public void lock() {
  while(!super.tryLock()) {
    // Do Nothing
  }

 }

 public void unlock() {
  super.unlock();
 }

}

Thats all for Spin Lock Example in Java. If you have questions / doubts, please write it on comment sections Thanks.

Related Articles:

You may also like:

No comments:

Post a Comment