Java Component Examples

LockFreeTree 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;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.amino.mcas.LockFreeBSTree;

public class TreeExample {
    private static final int ELEMENT_NUM = 1000;
    
    public static void main(String[] argvs) {
    
        ExecutorService exec = Executors.newCachedThreadPool();

        final LockFreeBSTree<Integer, String> bstree = new LockFreeBSTree<Integer, String>();

        for (int i = 0; i < ELEMENT_NUM; ++i) {
            exec.submit(new InsertTask(bstree));
        }

        exec.shutdown();
        try {
            exec.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Boolean result = true;
        for (int i = 1; i < ELEMENT_NUM; ++i) {
            if (bstree.find(i) == null) {
                System.out.println("didn't find " + i);
                result = false;
            }
        }
        
        if(result) {
            System.out.println("Test successfully!");
        }
    }

}

class InsertTask implements Runnable {
    private static AtomicInteger count = new AtomicInteger();
    LockFreeBSTree tree;

    public InsertTask(LockFreeBSTree tr) {
        tree = tr;
    }

    public void run() {
        int c = count.incrementAndGet();
        if(tree.update(c, c) != null) {
            System.out.println("did not insert " + c);
        }
    }
}
Back Home