1

Here we are taking a lock on Node object "f" and performing some update operation in synchronised way.

Could someone please let me know, how we can convert this code using ReentrantLock?

I read we can take a lock on block of code using lock() and unlock() methods but not see anywhere how we can take a lock on object.

public void updateNodeValue(){
    Node<K,V> f = getNode();
    synchronized (f) {
        // do something here to update the value in Node Object f
    }
}

public Node<K,V> getNode(){
    //  return NodeObject from an Array
}
  • You would need to declare a `ReentrantLock` on `Node` and lock it in place of the synchronized block. – shmosel Nov 10 '17 at 05:05
  • You mean to say that class Node { final int hash; final K key; volatile V val; volatile Node next; final Lock lock; Node(int hash, K key, V val, Node next) { this.hash = hash; this.key = key; this.val = val; this.next = next; this.lock = new ReentrantLock(); } } and the use it like Lock l = node.lock; l.lock(); do something(); l.unlock(); In this way it will take a lock only on a particular Node object and other thread can use other Node object. – Sourabh Kanojiya Nov 10 '17 at 06:38
  • Something like that. – shmosel Nov 10 '17 at 06:43
  • What you are talking will happen even with synchronized too, Thread will wait only for the locked objects, only, If thread has a different object other than the locked, it will enter in synchronized block in any case. I think what @shmosel has suggested seems to be right answer – Raman Sharma Nov 10 '17 at 11:27
  • Refer to linked question for more details. This question too provides better insight: https://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java/ – Ravindra babu Nov 11 '17 at 06:32

1 Answers1

-1

Locks are not related to instance fields. They lock the whole object in which the instance field is.

Lock striping is an option, though.

Törpetestű
  • 192
  • 10