Java ConcurrentSkipListSet Example

By Arvind Rai, November 14, 2023
1. Java ConcurrentSkipListSet is used in concurrent threading environment.
2. ConcurrentSkipListSet maintains the behavior same as TreeSet.
3. The elements in ConcurrentSkipListSet can be accessed simultaneously and element's integrity will be maintained.
4. ConcurrentSkipListSet does not affect the performance. All accesses are lock free and we do not need to worry for synchronization because it handles concurrent accesses.

Example

ConcurrentSkipListSetTest.java
package com.concretepage;
import java.util.concurrent.ConcurrentSkipListSet;

public class ConcurrentSkipListSetTest {
    ConcurrentSkipListSet<String> csls= new ConcurrentSkipListSet<String>();
    class AddThread implements Runnable {
        @Override
        public void run() {
            //adds specified element in the set
            csls.add("A");
            csls.add("B");

            // returns the first element
            String s1=csls.first();

            System.out.println(s1);
            //returns the last element.
            String s2=csls.last();

            System.out.println(s2);
        }
    }
    class SubThread implements Runnable {
        @Override
        public void run() {
            // removes the specified element from the set.
           csls.remove("A");
        }
    }
    public static void main(String... args) {
    	ConcurrentSkipListSetTest ob = new ConcurrentSkipListSetTest();
        new Thread(ob.new AddThread()).start();
        new Thread(ob.new SubThread()).start();
    }
}
In the example there are two threads, one object of ConcurrentSkipListSet and two threads are doing operation on this object.
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us