Sofia Kelly

Sofia Kelly

1566615950

How to use Java Executor framework for Multithreading

The previous Blog covered how to create Threads by Extending the Thread class and implementing the Runnable Interface.

This article will be covering 2 topics.

  • Creating Threads by implementing the Callable Interface
  • Using the Executor Framework in Java

Implementing the Callable Interface

In order to create a Piece of code which can be run in a Thread, we create a class and then implement the CallableInterface. The task being done by this piece of code needs to be put in the call() function. In the below code you can see that CallableTask is a class which implements Callable Interface, and the task of summing up numbers from 0 to 4 is being done in the function.

import java.util.concurrent.Callable;
class CallableTask implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {

		int sum = 0;
		for (int i = 0; i < 5; i++) {
			sum += i;
		}
		return sum;
	}

}

In the above code you would notice that Callable has a parameter of Integer. This shows that the return type of this Callable will be Integer. Also it can be seen that the call function returns Integer type.

Creating the Threads and running them

The code below shows how to create the Threads and then run them.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableInterfaceDemo {

	public static void main(String[] args) {
		FutureTask<Integer>[] futureList = new FutureTask[5];

		for (int i = 0; i <= 4; i++) {
			Callable<Integer> callable = new CallableTask();
			futureList[i] = new FutureTask<Integer>(callable);
			Thread t = new Thread(futureList[i]);
			t.start();

		}

		for (int i = 0; i <= 4; i++) {
			FutureTask<Integer> result = futureList[i];
			try {
				System.out.println("Future Task" + i + ":" + result.get());
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			} catch (ExecutionException e) {
				
				e.printStackTrace();
			}
		}

	}

}

In order to create a Thread, first we need to create an Instance of CallableTask which implements the CallableInterface as shown in

Callable<Integer> callable = new CallableTask();

Then we need to create an Instance of the FutureTask class and pass the instance of Callable task as an argument as shown in

futureList[i] = new FutureTask<Integer>(callable);

Then to create a Thread we create an instance of the Thread class and pass the Instance of the FutureTask class as an argument as shown in

Thread t = new Thread(futureList[i]);

Finally the Thread is started with the start() function.

Getting the result from the Thread

In case of Callables the Thread can actually return a value. In order to get this value we can call the get() function on the instance of the FutureTask. In our code, the return value of the thread is the sum of numbers from 0 to 4.

This is shown in the below code snippet

FutureTask<Integer> result = futureList[i];
try {
	System.out.println("Future Task" + i + ":" + result.get());
} catch (InterruptedException e) {
				
	e.printStackTrace();
} catch (ExecutionException e) {
				
	e.printStackTrace();
}

Also the thread may throw an Exception as well which can be handled with try catch blocks.

Complete Code

Here is the complete code discussed till now

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class CallableTask implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {

		int sum = 0;
		for (int i = 0; i < 5; i++) {
			sum += i;
		}
		return sum;
	}

}

public class CallableInterfaceDemo {

	public static void main(String[] args) {
		FutureTask<Integer>[] futureList = new FutureTask[5];

		for (int i = 0; i <= 4; i++) {
			Callable<Integer> callable = new CallableTask();
			futureList[i] = new FutureTask<Integer>(callable);
			Thread t = new Thread(futureList[i]);
			t.start();

		}

		for (int i = 0; i <= 4; i++) {
			FutureTask<Integer> result = futureList[i];
			try {
				System.out.println("Future Task" + i + ":" + result.get());
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			} catch (ExecutionException e) {
				
				e.printStackTrace();
			}
		}

	}

}

The Executor Framework

Creating a Thread on the Fly everytime is Resource Intensive. One good alternative for this is to have some Threads already setup and then allocate our tasks to these threads. This is where the Executors Class and ExecutorService are very useful.

A Thread pool with 4 threads

The above image shows a Thread pool with 4 threads. Whenever we want any task to be run, we can assign it to these threads. Once the task is complete, the Thread will be freed to take up other tasks.

How to use the Executor Framework

Here is a code which uses the Executor framework.

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;

class Worker implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {

		int sum = 0;
		for (int i = 0; i < 5; i++) {
			sum += i;
		}
		return sum;
	}

}

public class ExecutorDemo {

	public static void main(String[] args) {
		ExecutorService executors = Executors.newFixedThreadPool(4);
		Future<Integer>[] futures = new Future[5];
		Callable<Integer> w = new Worker();
		try {
			for (int i = 0; i < 5; i++) {
				Future<Integer> future = executors.submit(w);
				futures[i] = future;

			}

			for (int i = 0; i < futures.length; i++) {
				try {
					System.out.println("Result from Future " + i + ":" + futures[i].get());
				} catch (InterruptedException e) {

					e.printStackTrace();
				} catch (ExecutionException e) {

					e.printStackTrace();
				}
			}
		} finally {
			executors.shutdown();
		}

	}

}


First we create a Worker Class which implements Callable and does the task which we need.

Next we need to create an ExecutorService.

The Executors class has multiple implementations of the ExecutorService.

Let us use the Executors class to create a fixed Thread pool of size 4. This is done as follows

ExecutorService executors = Executors.newFixedThreadPool(4);

Next we need to submit our task to the Executor Service. This is done using the following Line of code

Future<Integer> future = executors.submit(w);

On submitting the task we get an Instance of the Future Object. The Future Object is what will store the result of the Task.

Getting the result of the Thread

In order to get the result of each task, we can call the get() method of the Future Instance. This is shown in the below code snippet.

try {
	System.out.println("Result from Future " + i + ":" + futures[i].get());
} catch (InterruptedException e) {

	e.printStackTrace();
} catch (ExecutionException e) {

	e.printStackTrace();
}

The thread can also Throw an Exception which can be handled using try catch.

Some possible Scenarios of the Fixed Thread Pool

  • Creating Threads by implementing the Callable Interface
  • Using the Executor Framework in Java

Shutting down the ExecutorService

The ExecutorService needs to be shutdown when the threads are not needed anymore. This will ensure that the JVM is not consuming Additional Resources.

The ExecutorService can be shutdown using the following command

executors.shutdown();

It can be seen that this shutdown is put within the finally block. This is to ensure that the shutdown is always executed at the end of the code even if any exception occured.

If the shutdown is not done in the right way, then in case any exception occurs then the ExecutorService will still be running and will be consuming Additional JVM resources.

Code

All the code discussed in this article can be found in this git repo

Congrats😃

Now you know the following concepts

  • Creating Threads by implementing the Callable Interface
  • Using the Executor Framework in Java

In my future Articles I will be covering more topics on Multithreading

Further reading:

Send Email in Java

Achieving Functional Programming in Java

Functional Programming? Don’t Even Bother, It’s a Silly Toy

The Differences Between a Junior, Mid-Level and Senior Developer

Object-Oriented Programming is Bad

Object-Oriented Programming — The Trillion Dollar Disaster

Java 11 & Spring Boot 2.2 Tutorial: Build your First REST API App

Building a Secure API with GraphQL & Spring Boot

Java Reflection API Tutorial

Best Java machine learning library

#java

What is GEEK

Buddha Community

How to use Java Executor framework for Multithreading
Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Joseph  Murray

Joseph Murray

1621492530

7 Test Frameworks To Follow in 2021 for Java/Fullstack Developers

It is time to learn new test frameworks in 2021 to improve your code quality and decrease the time of your testing phase. Let’s explore 6 options for devs.

It is time to learn new test frameworks to improve your code quality and decrease the time of your testing phase. I have selected six testing frameworks that sound promising. Some have existed for quite a long time but I have not heard about them before.

At the end of the article, please tell me what you think about them and what your favorite ones are.

Robot Framework

Robot Framework is a generic open-source automation framework. It can be used for test automation and robotic process automation (RPA).

Robot Framework is open and extensible and can be integrated with virtually any other tool to create powerful and flexible automation solutions. Being open-source also means that Robot Framework is free to use without licensing costs.

The RoboFramework is a framework** to write test cases and automation processes.** It means that it may replace** your classic combo Selenium + Cucumber + Gherkins**. To be more precise, the Cucumber Gherkins custom implementation you wrote will be handled by RoboFramework and Selenium invoked below.

For the Java developers, this framework can be executed with Maven or Gradle (but less mature for the latter solution).

#java #testing #test #java framework #java frameworks #testing and developing #java testing #robot framework #test framework #2021

Joseph  Murray

Joseph Murray

1623304800

Why We Need Collection Framework in Java?

A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task. Before Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors, or Hash tables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class.

Collection Framework is a powerful framework in java. This framework defines the most common methods that can be used for any collection of objects. But the question arises that we have an array concept in java then why we need collection framework in java? Now let’s see that why we need collection framework in java with some valid points of difference between array and collection.

#java #java-collections #why we need collection framework in java #java collections framework #framework in java

Samanta  Moore

Samanta Moore

1623834960

Top 10 Popular Java Frameworks Every Developer Should Know in 2021

Java frameworks are essentially blocks of pre-written code, to which a programmer may add his code to solve specific problems. Several Java frameworks exist, all of which have their pros and cons. All of them can be used to solve problems in a variety of fields and domains. Java frameworks reduce the amount of coding from scratch that programmers have to do to come up with a solution.

Table of Contents

#full stack development #frameworks #java #java frameworks #top 10 popular java frameworks every developer should know in 2021 #top 10 popular java frameworks

Samanta  Moore

Samanta Moore

1620458875

Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var has on other pre-existing characteristics.

#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity