Home  >  Core Java

Example of newFixedThreadPool in Java

By Arvind Rai, March 01, 2013
On this page we will provide example of newFixedThreadPool() in java. newFixedThreadPool() is the method of java.util.concurrent.Executors and has been introduced in JDK 1.5. newFixedThreadPool() accepts number of threads for pool and instance of ThreadFactory which is optional. If we do not pass instance of ThreadFactory, default ThreadFactory will be used. newFixedThreadPool() creates a thread pool with fixed number of threads. If requests arrive and there is no idle thread in the pool, they will wait in queue. If a thread dies or terminated in the pool, a new thread will be created. The pool will be alive until we externally call shutdown. newFixedThreadPool() has two constructors .
ExecutorService exService = Executors.newFixedThreadPool(no_of_threads); 
 
In the above constructor default ThreadFactory is used. If we want to pass our own ThreadFactory, we can do as follows.
ExecutorService exService = Executors.newFixedThreadPool(no_of_threads, ThreadFactory); 
 
Runnable thread is called by execute() method and submit() method both. submit() method returns the given value on successful completion of request and can be fetched by Future. In the below case done will be returned.
final Future<String> runFuture = exService.submit(new RunnableThread(), "done");
final String  runval = runFuture.get();
And when submit() method calls Callable thread, it returns the value returned by callable thread and can be fetched by Future.
final Future<Integer> callFuture = exService.submit(new CallableThread());
final int callval = callFuture.get();

newFixedThreadPool() Example with Default ThreadFactory

Find the sample example of newFixedThreadPool(no_of_threads).
NewFixedThreadPoolDemoOne.java
package com.concretepage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class NewFixedThreadPoolDemoOne {
    public static void main(final String... args) throws InterruptedException, ExecutionException {
        final int noOfTh = 2;
        // creates fixed thread pool
        final ExecutorService exService = Executors.newFixedThreadPool(noOfTh);
        // runnable thread start to execute. "done" will be returned after successful thread run
        final Future<String> runFuture = exService.submit(new RunnableThread(), "done");
        // gets value for Runnable thread
        final String runval = runFuture.get();
        System.out.println("Task:" + runval);
        // callable thread starts to execute
        final Future<Integer> callFuture = exService.submit(new CallableThread());
        // gets value of callable thread
        final int callval = callFuture.get();
        System.out.println("Return Value:" + callval);
        // checks for thread termination
        final boolean isTerminated = exService.isTerminated();
        System.out.println(isTerminated);
        // waits for termination for 30 seconds only
        exService.awaitTermination(30, TimeUnit.SECONDS);
        exService.shutdown();
    }
}
CallableThread.java
package com.concretepage;
import java.util.concurrent.Callable;
public class CallableThread implements Callable<Integer> {
    @Override
    public Integer call() {
        int cnt = 1;
        for (; cnt < 3; cnt++) {
            System.out.println("Callable:" + cnt);
        }
        return cnt;
    }
}
RunnableThread.java
package com.concretepage;
public class RunnableThread implements Runnable {
    @Override
    public void run() {
        int cnt = 1;
        for (; cnt < 3; cnt++) {
            System.out.println("Runnable:" + cnt);
        }
    }
}
Output
Runnable:1
Runnable:2
Task:done
Callable:1
Callable:2
Return Value:3
false 

newFixedThreadPool() Example with User ThreadFactory

Find the sample example of newFixedThreadPool(no_of_thread, ThreadFactory).
NewFixedThreadPoolDemoTwo.java
package com.concretepage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class NewFixedThreadPoolDemoTwo {
    public static void main(final String... args) throws InterruptedException, ExecutionException {
        final int noOfTh = 2;
        final ExecutorService exService = Executors.newFixedThreadPool(noOfTh, new MyThreadFactory());
        exService.execute(new RunnableThread());
        final Future<Integer> callFuture = exService.submit(new CallableThread());
        final int callval = callFuture.get();
        System.out.println("Return Value:" + callval);        
        exService.shutdown();
    }
}
MyThreadFactory.java
package com.concretepage;
import java.util.concurrent.ThreadFactory;
public class MyThreadFactory implements ThreadFactory {
	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		t.setPriority(Thread.MAX_PRIORITY );
		System.out.println("---Thread Created---");
		return t;
	}
}
Output
---Thread Created---
Runnable:1
Runnable:2
---Thread Created---
Callable:1
Callable:2
Return Value:3
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us