Showing posts with label java-thread. Show all posts
Showing posts with label java-thread. Show all posts

Friday, October 28, 2022

Java - Always Name Your Thread Pools - Naming threads and thread-pools of ExecutorService - set name of thread

You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory).

The factory will be responsibe for creating threads, and will be able to name them.
ExecutorService is a JDK API that makes asynchronous task execution easier.

ExecutorService offers a pool of threads and an easy-to-use API for assigning tasks.

The ExecutorService gives the name of the threads in the thread pool.

This shot discusses how we can assign custom names to the threads of the thread pool of the ExecutorService.
BasicThreadFactory

An ExecutorService employs a ThreadFactory to create its threads to execute tasks.

In many circumstances, users do not need to worry about a ThreadFactory because the ExecutorService's default one will suffice.

A custom ThreadFactory must be constructed with particular needs, such as thread naming.
import java.util.TimerTask;
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        // instant thread execution
        ExecutorService executorService = Executors.newFixedThreadPool(3, namedThreadFactory("test-thread"));
        for (int i=0; i < 5; i++) {
            executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
        }
        executorService.shutdown();

        // scheduled thread execution


        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(namedThreadFactory("scheduled-thread"));
        TimerTask repeatedTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName());
                }
                finally {
                    executor.shutdownNow();
                }
            }
        };
        executor.schedule(repeatedTask, 1L, TimeUnit.MINUTES);
    }

    static ThreadFactory namedThreadFactory(String name) {
        return new YourThreadFactory(name);
    }
}

class YourThreadFactory implements ThreadFactory {
    private String name = "[No Name]";

    YourThreadFactory(String name) {
        this.name = name;
    }

    public Thread newThread(Runnable r) {
        return new Thread(r, name);
    }
}

Wednesday, November 1, 2017

Java FutureTask Example With ExecutorService | Java Callable Future Example With ExecutorService

Here Executor framework used to execute 5 tasks in parallel in 2 thread pool (not more than 2 thread will be execute at the same time) and use Java Future to get the result of the submitted tasks. SJava Callable Future interfaces used to get the concurrent processing benefits of threads and we know that they are capable of returning value to the calling program. Also we can use of isDone() method to check make sure thread ends once all the tasks are executed.



package com.pkm;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by pritom on 31/10/2017.
 */
public class FutureExecutorService implements Callable {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        List<Future<String>> list = new ArrayList<Future<String>>();
        FutureExecutorService callable = new FutureExecutorService();
        for (Integer i = 0; i < 5; i++) {
            Future<String> future = executor.submit(callable);
            list.add(future);
        }
        for (Future<String> future : list) {
            Object object = future.get();
        }
        executor.shutdown();
    }

    @Override
    public Object call() throws Exception {
        System.out.println("Thread started at = " + (new Date()));
        Thread.sleep(1000L * (1 + (new SecureRandom().nextInt(2))));
        System.out.println("Thread finished at = " + (new Date()) + ", thread=" + Thread.currentThread().getName());
        return "Thread executed at = " + (new Date()) +
                ", name=" + Thread.currentThread().getName();
    }
}


Output as below:


Thread started at = Wed Nov 01 09:33:50 BDT 2017
Thread started at = Wed Nov 01 09:33:50 BDT 2017
Thread finished at = Wed Nov 01 09:33:51 BDT 2017, thread=pool-1-thread-1
Thread started at = Wed Nov 01 09:33:51 BDT 2017
Thread finished at = Wed Nov 01 09:33:52 BDT 2017, thread=pool-1-thread-2
Thread started at = Wed Nov 01 09:33:52 BDT 2017
Thread finished at = Wed Nov 01 09:33:52 BDT 2017, thread=pool-1-thread-1
Thread started at = Wed Nov 01 09:33:52 BDT 2017
Thread finished at = Wed Nov 01 09:33:54 BDT 2017, thread=pool-1-thread-2
Thread finished at = Wed Nov 01 09:33:54 BDT 2017, thread=pool-1-thread-1


As you can show in output that 2 thread are running at a time and once one of them finished another one started execution. So is the use of ExecutorService to maintain thread pool.


Tuesday, October 31, 2017

Callable and Future in Java | Callable vs Runnable | Java Callable Future Example

Callable and Future in Java | Callable vs Runnable | Java Callable Future Example

Java Callable and Future are used a lot in multithreaded programming. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception. Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Below is a simple example:


package com.pkm;

import java.security.SecureRandom;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Created by pritom on 31/10/2017.
 */
public class CallableTest implements Callable {
    private Integer n;

    public static void main(String[] args) throws Exception {
        FutureTask[] futureTasks = new FutureTask[5];
        for (Integer i = 0; i < 5; i++) {
            CallableTest callable = new CallableTest(i);
            futureTasks[i] = new FutureTask(callable);
            Thread thread = new Thread(futureTasks[i]);
            thread.start();
        }
        for (Integer i = 0; i < 5; i++) {
            System.out.println(futureTasks[i].get());
        }
    }

    public CallableTest(Integer n) {
        this.n = n;
    }

    @Override
    public Object call() throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        Thread.sleep(1000L * (1 + (new SecureRandom().nextInt(5))));
        return "Thread executed at = " + (new Date()) +
                ", name=" + Thread.currentThread().getName() + "." + n;
    }
}


Output is below:


Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread called at = Tue Oct 31 16:02:08 BDT 2017
Thread executed at = Tue Oct 31 16:02:13 BDT 2017, name=Thread-0.0
Thread executed at = Tue Oct 31 16:02:13 BDT 2017, name=Thread-1.1
Thread executed at = Tue Oct 31 16:02:11 BDT 2017, name=Thread-2.2
Thread executed at = Tue Oct 31 16:02:10 BDT 2017, name=Thread-3.3
Thread executed at = Tue Oct 31 16:02:09 BDT 2017, name=Thread-4.4


Java Thread Example by extending Thread class | Java Thread Example by implementing Runnable interface

Java Thread Example by extending Thread class



package com.pkm;

import java.util.Date;

/**
 * Created by pritom on 31/10/2017.
 */
public class ThreadTest extends Thread {
    public static void main(String[] args) throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        new ThreadTest().start();
    }

    public void run() {
        try {
            sleep(10000L);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread executed at = " + (new Date()));
    }
}


Java Thread Example by implementing Runnable interface


package com.pkm;

import java.util.Date;

/**
 * Created by pritom on 31/10/2017.
 */
public class RunnableTest implements Runnable {
    public static void main(String[] args) throws Exception {
        System.out.println("Thread called at = " + (new Date()));
        new Thread(new RunnableTest()).start();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10000L);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread executed at = " + (new Date()));
    }
}

So we can use "Runnable" interface, it will help us inherit another class, because if we use "Thread" inheritance then we should loose one scope to inherit another class if we need.