{{theTime}}

Search This Blog

Total Pageviews

Showing posts with label Java Concurrency. Show all posts
Showing posts with label Java Concurrency. Show all posts

AtomicLong Example in MultiThread Environment

import java.util.concurrent.atomic.AtomicLong;

/**
       -- A long value that may be updated atomically. You can refer the java.util.concurrent.atomic package properties of atomic variables. 
       --  An AtomicLong is used in applications such as atomically incremented sequence numbers, and cannot be used as a replacement for a java.lang.Long. 
       --   However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
 */
public class TestAtomicLong
{
    private static TestAtomicLong instance;
    private final AtomicLong sequenceNumber ;

    static {
        instance = new TestAtomicLong() ;
    }
    
    private TestAtomicLong(){
        sequenceNumber = new AtomicLong(1) ;
    }
    
    public void increatementSequence(){
        System.out.println(sequenceNumber.incrementAndGet() );
        System.out.println(sequenceNumber.get()) ;
    }
    
    private class ScoreCounter implements Runnable{
        
        public ScoreCounter() {
        }

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run()
        {
            sequenceNumber.incrementAndGet() ;
            System.out.println("Score Manager :" + Thread.currentThread().getName() + " updated the score : " + sequenceNumber.get()) ;
        }        
    }
    
    private void runScoreManager() {
        for(int i=0; i<10; i++) {
            ScoreCounter sc = new ScoreCounter() ;
            Thread scoreBoardManager = new Thread(sc) ;
            scoreBoardManager.start() ;            
        }        
    }
    
    public static void main(String str[]) throws Exception {
        TestAtomicLong tal = new TestAtomicLong() ;
        tal.runScoreManager() ;
    }
}

Producer and Consumer Example using LinkedBlockingQueue in Multi Thread Env.

/**
 * Program to Producer the tasks using 100 Threads and 100 Threads Consuming the tasks using LinkedBlockingQueue.

 *   LinkedBlockingQueue Works well in Multi threading env
 *   Orders item in first-in-first-out
 *   Linked Blocking Queue has higher throughput than Array Blocking Queue
 *   add method -- adds the task
 *   take method  -- removes the task 
 * 
 */
import java.util.concurrent.LinkedBlockingQueue;

public class TestLinkedBlockingQueue
{
    
    private static LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>(1000);
    
    private static class TaskProducer implements Runnable {
        
        String name ;
        public TaskProducer(String s){
            this.name = s;
        }

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run()
        {
                linkedBlockingQueue.add("Task " + name) ;
                System.out.println("Task added "+ name) ;
        }
    }
    
    private static class TaskConsumer implements Runnable {

        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run()
        {
                String con1;
                try {
                    con1 = linkedBlockingQueue.take();
                    System.out.println("Consumer taken" + con1) ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } 
        }        
    }
    
    public static void main(String str[]) throws Exception {                
        for(int i= 0; i< 100; i++){            
            TaskProducer taskProducer = new TaskProducer(i+"") ;
            Thread pt = new Thread(taskProducer) ;
            pt.start() ;
            pt.join() ;
        }
        for(int i= 0; i< 100; i++){
            TaskConsumer taskConsumer = new TaskConsumer() ;
            Thread ct = new Thread(taskConsumer) ;
            ct.start() ;
            ct.join() ;
        }
    }
}

Java CountDownLatch Example Program.

import java.util.concurrent.CountDownLatch;

public class ThreadOnOffGate
{
    public static void main(String str[]) throws InterruptedException{
        int N = 10000 ;
        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(N);
        
        for (int i = 0; i < N; ++i) // create and start threads
            new Thread(new Worker(startSignal, doneSignal)).start();
        
        System.out.println ("Main Thread will wait here") ;
        startSignal.countDown();      // let all threads proceed
        System.out.println(" Main thread waiting"); 
        doneSignal.await();           // wait for all to finish
        System.out.println(" Main thread work done.") ;
        
    }
}

class Worker implements Runnable {
    
    private CountDownLatch startCountDownLatch;
    private CountDownLatch doneCountDownLatch;

    Worker(CountDownLatch start, CountDownLatch done){
        this.startCountDownLatch = start ;
        this.doneCountDownLatch = done ;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run()
    {
        try {
            startCountDownLatch.await() ;
            doWork() ;
            doneCountDownLatch.countDown() ;
            
        }catch(InterruptedException e){
            
        }
    }

    /**
     * 
     */
    private void doWork()
    {
         System.out.println("Current Thread : " + Thread.currentThread().getName() + " working") ;      
    }
}

AI Predictive Bot - Scenario Model

  💡 How to Read the Costco Scenario Model This simulator bridges the gap between how a company operates (its business performance) and how...