Java Component Examples

LockFreeSet Example

/*
 * Copyright (c) 2008 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.amino.examples;

/*   The set only contains none identical items.
 *   This example shows the mainly interfaces of LockFreeSet.
 *   Including: add(), remove(), isEmpty(), size(), iterator().
 *  
 *   The SetAdder class try to add items maybe identical.
 *   The SetRemover will remove no more than ELEMENT_NUM items in the set.
 *   The main thread will wait until all the threads in the pool to finish, and it will
 *   print all the items still in the Set.
 *  
 *   2009/05/22
 */

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.amino.ds.lockfree.LockFreeSet;

public class SetExample {

    public static final int ELEMENT_NUM = 1000;
    private static final int TASKS_NUM = 4;
    public static void main(String[] argvs) {

        ExecutorService exec = Executors.newFixedThreadPool(TASKS_NUM);

        final LockFreeSet<String> setStr = new LockFreeSet<String>();

        for (int i = 0; i < TASKS_NUM; ++i) {
            exec.submit(new SetAdder(setStr));
            if ( i%2 == 0)exec.submit(new SetRemover(setStr));
        }

        exec.shutdown();
        // Wait until all the threads in pool to finish.
        try {
            while(!exec.awaitTermination(600, TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        // If the Set is empty now, the program will exit.
        if (setStr.isEmpty())
        {
            System.out.println("The Set is empty, so I will exit!");
            System.exit(1);
        }
        
        // The simple way for printing all the elements in List.
        for (String str : setStr)
            System.out.println(str);
        
        // Clear all the elements.    
        System.out.println("before clear size: " + setStr.size());
        setStr.clear();        
        System.out.println("cleared size: " + setStr.size());
    }
}

/*
 *  The SetAdder try to add items which maybe identical to Set.  
 */
class SetAdder implements Runnable {
    Set<String> tskSet;
    private int count = 0;
    
    public SetAdder(Set<String> taskSet)
    {
        tskSet = taskSet;      
    }
        
    public void run(){
        while (count < ListExample.ELEMENT_NUM)
        {
            //The duplicated number shouldn't be added!
            if (tskSet.add(Integer.toString(count++))) {
                System.out.println(Thread.currentThread()+ " Added " + count);
            } else {
                System.out.println(Thread.currentThread()+ " !!!try to add identical item:" + count);
            }
        }
        Thread.yield();
    }  
}

// The SetRemover class will remove the items.
class SetRemover implements Runnable {
    Set<String> tskSet;
    private int count = 0;
    
    public SetRemover(Set<String> taskSet)
    {
        tskSet = taskSet;      
    }
        
    public void run(){
        int times = 0;
        
        while (times < ListExample.ELEMENT_NUM)
        {
            if (!tskSet.remove(Integer.toString(count++))) {
                System.out.println(Thread.currentThread()+ "Removed: " + count);
            }
            times++;
        }
        Thread.yield();
    }  
}
Back Home