FIFO for Write Order in ConcurrentHashMap

757 Views Asked by At

My CHM already contains following Data ->

1 Apple
2 Banana
3 Cat
4 dog

1,2,3,4 are keys and Apple, banana... are keys correspondingly.

If 3 threads t1, t2, t3 wants to modify the same existing record [3 Cat] . I need this write in FIFO order.[Then some Operation will be performed . Ex Logging to keep record of value change pattern] I checked the existing Source code it does not guarantee FIFO Write. In source Code Locking is performed on a Segment. Following is the source code in CHM Class

   static final class Segment<K,V> extends ReentrantLock implements Serializable {

            Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
                         this.loadFactor = lf;
                         this.threshold = threshold;
                         this.table = tab;
            }
            // .... Rest of Code
    }   

Segment Class invokes the Default constructor of ReentrantLock which does not provides fair locking mechanisam.

public ReentrantLock() {
    sync = new NonfairSync();
}

If i Write my new CHM class and make the following change

            Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
                         super(true);
                         this.loadFactor = lf;
                         this.threshold = threshold;
                         this.table = tab;
            }

the super(true) will invoke the following constructor of ReEntrantLock

           public ReentrantLock(boolean fair) {
                sync = fair ? new FairSync() : new NonfairSync();
           }

I think it will make sagment locking Operation Fair and Write Operation will be performed in FIFO Order. Please Suggest your Views.

0

There are 0 best solutions below