Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Tuesday, September 30, 2014

MultiThreading and Exception

Class ThreadException {

TestKl0t1Example example = new TestKl0t1Example();
TestKl0t1Example.Criteria criteria = example.createCriteria();
criteria.andT1trnoEqualTo(new BigDecimal(dto.getTranNo()))

List<Object> dbResult = getCommonDao()
.selectByExampleDltmOff(example);


t1 = (TestKl0t1) dbResult.get(0);
List<TestKl0t1> results = new ArrayList<TestKl0t1>();
for (int i = 0; i < dbResult.size(); i++) {
results.add((TestKl0t1) dbResult.get(i));
}
ExecutorService executor = Executors.newFixedThreadPool(dbResult
.size());
List<Transactiompl> callingList = new ArrayList<ThreadException.Transactiompl>();
for (int i = 0; i < dbResult.size(); i++) {
Transactiompl localImpl = new Transactiompl(dbResult.get(i));
callingList.add(localImpl);
}
List<Future<TestKl0t1>> results1 = null;

try {

results1 = executor.invokeAll(callingList);

// executor.shutdown();
// while (!executor.isTerminated()) {
// executor=null;
// }

} catch (Exception e) {
executor = null;

}
executor = null;

}
Class Transactiompl extends RequestContextAwareCallable{
Transactiompl(Object readTestKl0t1) {
this.t1 = (TestKl0t1) readTestKl0t1;

}



public TestKl0t1 onCall() throws InterruptedException {
beginTransaction();





public abstract class RequestContextAwareCallable<V> implements Callable<V> {

private final RequestAttributes requestAttributes;
private Thread thread;

public RequestContextAwareCallable() {
this.requestAttributes = RequestContextHolder
.getRequestAttributes();
this.thread = Thread.currentThread();
}

public V call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return onCall();
} catch (Exception e) {
System.out.println("Oh boy, something broke!");
e.printStackTrace();
rollbackTransaction();
checkforcommit=false;
throw e;


}

finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}

thread = null;
}
}

public abstract V onCall() throws Exception;
public void beginTransaction() {

DefaultTransactionDefition txDef = new DefaultTransactionDefition();
txDef.setPropagationBehavior(0);
txStatus = txManager.getTransaction(txDef);
}

public void commitTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.commit(txStatus);
} else {
System.out.println("error");
}
}

public void rollbackTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.rollback(txStatus);
} else {
System.out.println("rollbackcalled");
}
}
}

@Override
public void resetGlobalVariables() {
// TODO Auto-generated method stub

}

private PlatformTransactionManager txManager;

public void setTxManager(PlatformTransactionManager txManager) {
this.txManager = txManager;
}

public PlatformTransactionManager getTxManager() {
return txManager;
}

Saturday, September 27, 2014

Thread Local


class ThreadRun implements Runnable {

    NumberValue number;
    int value;

    ThreadRun(NumberValue number,int value) {

     
        this.number=number;
        this.value = value;
        Thread t = new Thread(this);
        t.start();
    }
   

    @Override
    public void run() {
     
//        number = number.getThreadLocal();
       
     
        number.setId(number.getId()+value);
     
        System.out.println(number.getId());

    }

}

public class ThreadTest {
    public static void main(String[] args) {
        NumberValue number = new NumberValue(1);

       
        new ThreadRun(number, 1);
        new ThreadRun(number, 2);
    }
}

class NumberValue {

    int id;
 

   
    ThreadLocal<NumberValue> threadLocal = new ThreadLocal<NumberValue>() {
   
    @Override
    protected NumberValue initialValue() {
     
        return new NumberValue(id);
    }
    };
       
   

    NumberValue(int id) {
        this.id = id;
     
    }

 

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    public NumberValue getThreadLocal() {
        return threadLocal.get();
    }

 

   

 
}

Thread Local


class ThreadRun implements Runnable {

    NumberValue number;
    int value;

    ThreadRun(NumberValue number,int value) {

     
        this.number=number;
        this.value = value;
        Thread t = new Thread(this);
        t.start();
    }
   

    @Override
    public void run() {
     
//        number = number.getThreadLocal();
       
     
        number.setId(number.getId()+value);
     
        System.out.println(number.getId());

    }

}

public class ThreadTest {
    public static void main(String[] args) {
        NumberValue number = new NumberValue(1);

       
        new ThreadRun(number, 1);
        new ThreadRun(number, 2);
    }
}

class NumberValue {

    int id;
 

   
    ThreadLocal<NumberValue> threadLocal = new ThreadLocal<NumberValue>() {
   
    @Override
    protected NumberValue initialValue() {
     
        return new NumberValue(id);
    }
    };
       
   

    NumberValue(int id) {
        this.id = id;
     
    }

 

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    public NumberValue getThreadLocal() {
        return threadLocal.get();
    }

 

   

 
}

Sample Threading

import java.util.HashMap;
import java.util.Vector;

public class AutoPlayer implements Runnable {

    private RequestDispatcher requestDispatcher;

    public AutoPlayer(RequestDispatcher requestDispatcher) {
    this.requestDispatcher = requestDispatcher;
    }


    public static void main(String[] args) {

    HashMap<String, Game> games = new HashMap<String, Game>();

    RequestDispatcher rd = new RequestDispatcher(games);

    Vector<Thread> threads = new Vector<Thread>();

    for (int i = 0; i < 10; i++) {
        AutoPlayer autoPlayer = new AutoPlayer(rd);
        Thread thread = new Thread(autoPlayer);
        threads.add(thread);
        thread.start();
    }

    for (int i = 0; i < threads.size(); i++) {
        try {
        threads.get(i).join();
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }

    }



    @Override
    public void run() {

    PlayResponse response = null;

    for (int i = 0; i < 1000; i++) {
        byte[] numbers = requestDispatcher.cardRequest();

        try {
        response = new PlayResponse();
        requestDispatcher.process("Lucky", 10, numbers, response);
        } catch (UnknownGameException e) {
        e.printStackTrace();
        }

        if (response != null) {
        System.out.println("[" + Thread.currentThread() + "] total requests:" + requestDispatcher.generatedCards);
        }
    }
    }

}

Wait and Notify

public class Threading {      
    public static void main(String[] args) {
   
     
final  Runnable one = new Runnable() {

                public void run() {
                 
//                    SomeOpeartion();
one .notify();


                }
                   
            };
            one.run();

 final Runnable two = new Runnable() {

                public void run() {

    two .wait();
//    SomeOpeartion();
    two .notify();
}
                 

               
            };
         


 final Runnable three= new Runnable() {

                public void run() {

    three.wait();
//    SomeOpeartion();
    three .notify();
}
                 

               
            };
            three.run();

final  Runnable four =new Runnable() {

                public void run() {

    four.wait();
//    SomeOpeartion();
    four .notify();

                 

               
            };
            four.run();


         final   Runnable five= new Runnable() {

                public void run() {

    five.wait();
//    SomeOpeartion();
    five .notify();
}
                 
               
            });
   

    }}}
           




//Thread blocks because of RuntimeException?

Simple Example 1


import java.lang.Math;
class MathSin extends Thread {
   public double deg;
   public double res;
   public MathSin(int degree) {
   deg = degree;
   }
   public void run() {
      System.out.println("Executing sin of"+deg);
      double Deg2Rad = Math.toRadians(deg);
      res = Math.sin(Deg2Rad);
      System.out.println("Exit from MathSin. Res ="+res);
   }
}
class MathCos extends Thread {
   public double deg;
   public double res;
   public MathCos(int degree) {
       deg = degree;
      }
      public void run() {
         System.out.println("Executing cos of"+deg);
         double Deg2Rad = Math.toRadians(deg);
         res = Math.cos(Deg2Rad);
         System.out.println("Exit from MathCos. Res ="+res);
      }
   }
   class MathTan extends Thread {
      public double deg;
      public double res;
     
      public MathTan(int degree) {
       deg = degree;
      }
      public void run() {
         System.out.println("Executing tan of"+deg);
         double Deg2Rad = Math.toRadians(deg);
         res = Math.tan(Deg2Rad);
         System.out.println("Exit from MathTan. Res ="+res);
      }
   }
   class MathThreads {
      public static void main(String args[]) {
         MathSin st = new MathSin(45);
         MathCos ct = new MathCos(60);
         MathTan tt = new MathTan(30);
         st.start();
         ct.start();
         tt.start();
         try {   // wa
             st.join();
             ct.join(); //wait for completion of MathCos object
             tt.join();
             double z = st.res + ct.res + tt.res;
             System.out.println("Sum of sin, cos, tan ="+z);
           }
           catch(InterruptedException IntExp) {
           }
        }
     }
 
       

ThreadLocal Sample3

package ThreadLocal;


import java.text.SimpleDateFormat;
import java.util.Random;

public class ThreadLocalExample implements Runnable{

    // SimpleDateFormat is not thread-safe, so give one to each thread
 // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyyMMdd HHmm");
        }
    };
   
    public static void main(String[] args) throws InterruptedException {
        ThreadLocalExample obj = new ThreadLocalExample();
        for(int i=0 ; i<10; i++){
            Thread t = new Thread(obj, ""+i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }

    @Override
    public void run() {
        System.out.println("Thread Name= "+Thread.currentThread().getName()+" default Formatter = "+formatter.get().toPattern());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
        formatter.set(new SimpleDateFormat());
       
        System.out.println("Thread Name= "+Thread.currentThread().getName()+" formatter = "+formatter.get().toPattern());
    }

}

ThreadLocal Sample2

package ThreadLocal;


public class BusinessService {

    public void businessMethod() {
        // get the context from thread local
        Context context = MyThreadLocal.get();
        System.out.println(context.getTransactionId());
    }
}


package ThreadLocal;


public class Context {

    /**
     * @return the transactionId
     */
    public String getTransactionId() {
        return transactionId;
    }

    /**
     * @param transactionId the transactionId to set
     */
    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    private String transactionId = null;

        /* getters and setters here */

}


package ThreadLocal;


/**
 * this class acts as a container to our thread local variables.
 * @author vsundar
 *
 */
public class MyThreadLocal {

    public static final ThreadLocal userThreadLocal = new ThreadLocal();

    public static void set(Context user) {
        userThreadLocal.set(user);
    }

    public static void unset() {
        userThreadLocal.remove();
    }

    public static Context get() {
        return (Context) userThreadLocal.get();
    }
}


package ThreadLocal;


public class ThreadLocalDemo extends Thread {

    public static void main(String args[]) {

        Thread threadOne = new ThreadLocalDemo();
        threadOne.start();

        Thread threadTwo = new ThreadLocalDemo();
        threadTwo.start();
    }

    @Override
    public void run() {
        // sample code to simulate transaction id
        Context context = new Context();
        context.setTransactionId(getName());

        // set the context object in thread local to access it somewhere else
        MyThreadLocal.set(context);

        /* note that we are not explicitly passing the transaction id */
        new BusinessService().businessMethod();
        MyThreadLocal.unset();

    }
}

Thread Pooling

import static java.util.Arrays.asList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class ThreadPoolExample1 {
 
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
       Employee first= new Employee();
       Employee first1 =first.get();
       first.setName("abishkar");
       first.setSalary(100);
       Employee seccond= new Employee();
       Employee seccond1=   seccond.get();
       first.setName("BillGates");
       first.setSalary(10);
        List<Future<Employee>> results = executor.invokeAll(asList(new MyThread1(first1), new MyThread1(first1)));
        executor.shutdown();

        for (Future<Employee> result : results) {
            System.out.println("Result: " + result.get());
        }

    }

}

class MyThread1 implements Callable<Employee> {
    Employee object;
    String name="";

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
   
        this.name = name;
    }

    MyThread1(Employee object) {
        this.object = object;

    }

    @Override
    public Employee call() throws Exception {
        System.out.println(object.getName()+ object.getSalary());
        object.setName("BillGates");
        object.setSalary(10);
        System.out.println(object.getName()+ object.getSalary());
        setName(object.getName());
        System.out.println(getName());
       
       
//        }
       return new Employee();
    }

}


class MyThread2 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        for (int j = 100; j < 110; j++) {
            System.out.println("j = " + j);
            Thread.sleep(500);
        }
        return new Object();
    }

}

class Employee {
    private String name;
    private int salary;

    Employee() {
        this.name = "abishkar";
        this.salary = 100;
    }
    Employee(int i) {
        this.name = "BillGates ";
        this.salary = 10;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the salary
     */
    public int getSalary() {
        return salary;
    }
    /**
     * @param salary the salary to set
     */
    public void setSalary(int salary) {
        this.salary = salary;
    }
    private static ThreadLocal threadLocal = new ThreadLocal(){
        @Override
        protected Employee initialValue() {
            return new Employee();
        }

    };
    public static Employee get() {
        return (Employee) threadLocal.get();
    }

}

ThreadLocal

import java.util.HashMap;
import java.util.Map;

public class CustomThreadLocal {

    private static Map threadMap = new HashMap();

    public static void add(Object object) {
        threadMap.put(Thread.currentThread(), object);
    }

    public static void remove(Object object) {
        threadMap.remove(Thread.currentThread());
    }

    public static Object get() {
        return threadMap.get(Thread.currentThread());
    }

}


public class hreadLocalMainSampleEx1 {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(1l);
                threadContext.setUserId("User 1");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(2l);
                threadContext.setUserId("User 2");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
    }
}

public class PrintThreadContextValues {
    public static void printThreadContextValues(){
        System.out.println(CustomThreadLocal.get());
    }
}

public class ThreadContext {

    private String userId;

    private Long transactionId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Long getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(Long transactionId) {
        this.transactionId = transactionId;
    }

    public String toString() {
        return "userId:" + userId + ",transactionId:" + transactionId;
    }

}

Saturday, September 20, 2014

Thread List

package research;


public class Test2 {

public static void main (String [] args) throws Exception

    {

        final int THREADS = 8;

        final long LENGTH = 100000000000L / THREADS;

        long start = System.currentTimeMillis ();

        Runnable task = new Runnable ()

        {

            public void run ()

            {

                long j = 0;

                for (long i = 0; i <LENGTH; i ++)

                    j ++;              

            }

        };

        Thread [] threadList = new Thread [THREADS];

        for (int i = 0; i <threadList.length; i ++)

        {

            threadList [i] = new Thread (task);

            threadList [i]. start ();

        }

       for (int i = 0; i <threadList.length; i ++)

            threadList [i]. join ();      

       long end = System.currentTimeMillis ();

        System.out.println ("END" + (end - start));

    }
}

Thread Monitor

package research;

public class Test {
public   static   void main (String [] args)
{
    for (int i =   0; i <   3000; i ++)
    {
        Thread thread =   new   Thread ()
        {
            final   Object monitor =   new   Object ();

            public   void run ()
            {
                synchronized (monitor)
                {
                    try   {monitor.wait( 40000);   }
                    catch (InterruptedException ex)   {}
                }
            }
        };
        thread. start ();
   }
}
}

Thread Locking

package research;

 class LockingThread1 implements Runnable{
private volatile int number=0;
LockingThread2 a=new LockingThread2();


@Override
public void run() {
a.Add(7);
// Add(5);

}
synchronized void Add(int numberValue){
number=number+numberValue;
System.out.println(number);
}

}
 class LockingThread2 {
// private volatile int number=0;
 private  int number=0;
//  synchronized void Add(int numberValue){
// number=number+numberValue;
// System.out.println(number);
// }
 void Add(int numberValue){
 number=number+numberValue;
 System.out.println(number);
}





}
public class LockingThread{
public static void main (String [] args) throws Exception

{
LockingThread1 thread1=new LockingThread1();
// LockingThread1 thread2=new LockingThread1();
// LockingThread1 thread3=new LockingThread1();
Thread no1=new Thread(thread1);
Thread no2=new Thread(thread1);
Thread no3=new Thread(thread1);
// no1.start();
// no2.start();
// no3.start();
//
no1.start();
no2.start();
no3.start();
}
}

Monday, June 30, 2014

AwaitTermination

package Algorithm;

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

public class awaitTermination {


@org.junit.Test
public void Test() throws InterruptedException {
ExecutorService a = Executors.newFixedThreadPool(20);
for (int i = 0; i <= 20; i++) {
a.execute(new Termination());


}
a.shutdown();
// true is returned if all task is completed and for completion 10 sec is waited but this facility was not provided in istermimanted and it does not wait for all tasks to complete and if that task does not complete within given time then it is
if(a.awaitTermination(10, TimeUnit.SECONDS)){
System.out.println("finihed");

}


}

}

class Termination implements Runnable {

@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("in");

}

}

}

Join,Start,Run

package Algorithm;

import org.junit.Test;
// executor framework eliminates the need for creating thread and calling it.It automatically handles it ,we  does not have to concern on it,as the code return below does not need to be write while working with thread using executor framework

/*The clear distinction can be seen in Run Vs Start.
 * In Start main method does not wait for Other threads run operation to complete.
 * It is totally asychronous.But,in run it is syschronous after completion of all threads operation main thread again resume its operation.
 * So,in case of start join can be used so that the thread waits until the operation of other thread is completed.
 *
 */

public class Basic {
private int i;
private int k;

public void SomeMethod1() throws InterruptedException {

Runnable separateTask1 = new Runnable() {

@Override
public void run() {
i = 1;

}

};
separateTask1.run();
}

public void SomeMethod11() throws InterruptedException {

Runnable separateTask1 = new Runnable() {

@Override
public void run() {
i = 1;

}

};
Thread thread = new Thread(separateTask1);
thread.start();

// thread.join();
}

public void SomeMethod2() throws InterruptedException {

Runnable separateTask1 = new Runnable() {

@Override
public void run() {
for (int i = 0; i <= 1000000000; i++) {
k = 2;
}

}

};
separateTask1.run();

}

public void SomeMethod22() throws InterruptedException {

Runnable separateTask1 = new Runnable() {

@Override
public void run() {
for (int i = 0; i <= 1000000000; i++) {
k = 2;
}

}

};
Thread thread = new Thread(separateTask1);
thread.start();
thread.join();

}

@Test
public void Sum() throws InterruptedException {
SomeMethod11();
SomeMethod22();

System.out.println(i + k);
}

}

Executor

package Algorithm;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorImplementation {
@org.junit.Test
public void Test() {
ExecutorService a = Executors.newFixedThreadPool(20);
//case1
for (int i = 0; i <= 3; i++) {
a.execute(new a());
// List<Runnable> b = a.shutdownNow();
// System.out.println(b);
}
//pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1 in
// shutdownnow attempt to shut all running task and return list of task that never executed
// in shutdown case no new task will be accepted in our case pool size was 20.3 is already started from pool and now in case2 for i=0 to 5 no execution will be done with exception thrown as
//ask Algorithm.a@68fede rejected from java.util.concurrent.ThreadPoolExecutor@134b58c[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 4]
// case2
a.shutdown();
for (int i = 0; i <= 5; i++) {
// so before executing this task we can check i it shudown with method isShutdown
a.execute(new a());
}
}

public void Test1() {
ExecutorService a = Executors.newFixedThreadPool(5);
for (int i = 0; i <= 5; i++) {
a.execute(new a());
}

for (int i = 0; i <= 5; i++) {
a.execute(new a());
}
}

public void Test2() throws InterruptedException, ExecutionException {
ExecutorService a = Executors.newFixedThreadPool(5);
List<Future> resultet=new ArrayList<Future>();
for (int i = 0; i <= 5; i++) {
Future reult=a.submit(new b());
resultet.add(reult);
}
for(Future individualresult:resultet){
individualresult.get();
}

for (int i = 0; i <= 5; i++) {
a.execute(new a());
}
for (int i = 0; i <= 5; i++) {
Future s = a.submit(new a());
s.get();
}
}

public void Test3() throws InterruptedException, ExecutionException {
ExecutorService a = Executors.newFixedThreadPool(5);
List<Pojo> pojolist = new ArrayList<Pojo>();
for (int i = 0; i <= 5; i++) {
pojolist.add(new Pojo());
}
List<ExecutorImplementation.c> list = new ArrayList<ExecutorImplementation.c>();
for (int i = 0; i <= pojolist.size(); i++) {
ExecutorImplementation.c ind = new ExecutorImplementation.c(
pojolist.get(i));
list.add(ind);

}
List<Future<Pojo>> result = a.invokeAll(list);
// iterate all the list for getting the return value ;
result.get(0).get();

}


public void Test4() throws InterruptedException, ExecutionException {
ExecutorService a = Executors.newFixedThreadPool(5);
List<Pojo> pojolist = new ArrayList<Pojo>();
for (int i = 0; i < 5; i++) {
pojolist.add(new Pojo());
}
List<d> list = new ArrayList<d>();
for (int i = 0; i < pojolist.size(); i++) {
d ind = new d(pojolist.get(i));
list.add(ind);

}
List<Future<Pojo>> result = a.invokeAll(list);

}

class c implements Callable<Pojo> {
private Pojo pojo;

private int i = 0;

c(Pojo pojo) {
this.pojo = pojo;

}

@Override
public Pojo call() throws Exception {
return new Pojo();
}
}
}

class a implements Runnable {
private int i = 0;

@Override
public void run() {
i = 1;
i = i + 1;
System.out.println("This is testig ");
System.out.println(i);
}

}

class b implements Callable<Pojo> {

@Override
public Pojo call() throws Exception {
return new Pojo();
}
}

class d implements Callable<Pojo> {
private Pojo pojo;

private int i = 1;

d(Pojo pojo) {
this.pojo = pojo;

}

@Override
public Pojo call() throws Exception {
i++;
System.out.println(pojo.getId());
System.out.println(pojo.getName());
System.out.println(i);
return pojo;
}
}

class Pojo {
private String name = "ram";

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id
*            the id to set
*/
public void setId(int id) {
this.id = id;
}

private int id = 11;

}

Runnable

package Algorithm;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class ExtendImpl implements Runnable {

@Override
public void run() {
System.out.println("3");

}

@Test
public void Start() {
List<Runnable> list = new ArrayList<Runnable>();
Runnable impl1 = new ExtendImpl();
Runnable impl11 = new ExtendImpl();
Runnable impl111 = new ExtendImpl();
Runnable impl1111 = new ExtendImpl();
Runnable impl2 = new ExtendImpl1();
Runnable impl3 = new ExtendImpl2();
list.add(impl1);
list.add(impl2);
list.add(impl3);
list.add(impl11);
list.add(impl111);
list.add(impl1111);
for (Runnable r : list) {
r.run();
}
}
}

class ExtendImpl1 implements Runnable {
// Singleton if it uses the same singleton object
//can be problem when both uses it

@Override
public void run() {
System.out.println("1");
}

}

class ExtendImpl2 implements Runnable {
// Singleton if it uses the same singleton object

@Override
public void run() {
System.out.println("2");
}

}
class Singleton{
private String name ;
}

isTerminated

package Algorithm;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class isTerminated {
@org.junit.Test
public void Test() {
ExecutorService a = Executors.newFixedThreadPool(20);
for (int i = 0; i <= 20; i++) {
a.execute(new terminated());


}
// false is returned if all task is completed
// true is returned if all task is completed and shut down Or shut down now is called
if(!a.isTerminated()){
System.out.println("Finished working ");
}

}

}

class terminated implements Runnable {

@Override
public void run() {
for (int i = 0; i <= 100000; i++) {
System.out.println("in");

}

}

}





shutdownNow

Program1
package Algorithm;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class shutdownNow {
@org.junit.Test
public void Test() {
ExecutorService a = Executors.newFixedThreadPool(10);
for (int i = 0; i <= 20; i++) {
a.execute(new shutdownnowclass());
}
// The main point  of both shut down and shut down now is that no new task will be executed after calling these method .An exception will be thrown if tried   to execute after calling these methods
List<Runnable> listofthatneverexecuted=a.shutdownNow();
System.out.println(listofthatneverexecuted);

}

}

class shutdownnowclass implements Runnable {

@Override
public void run() {
for (int i = 0; i <= 2; i++) {
System.out.println("in");

}

}
}

Program2
package Algorithm;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class shutdown {

@org.junit.Test
public void Test() {
ExecutorService a = Executors.newFixedThreadPool(20);
for (int i = 0; i <= 3; i++) {
a.execute(new shutdownclass());
}
// When shut down is called the execution is shut down .Below code is not executed .An exception is thrown .To cure exception following checking can be done
//@if(!a.isShutdown()){
// }
for (int i = 0; i <= 5; i++) {
a.execute(new shutdownclass());
}
a.shutdown();
// now there is no exception as following line is never executed
if(!a.isShutdown()){
for (int i = 0; i <= 5; i++) {
a.execute(new shutdownclass());
}
}
}

}

class shutdownclass implements Runnable {

@Override
public void run() {
for (int i = 0; i <= 1000000000; i++) {
System.out.println("in");

}

}

}