×

Java callable example

What is callable in Java?

Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other is to combine a Runnable with a thread. The inability to force a thread to return results when it ends or when run () is finished is a feature that Runnable lacks. The Callable interface is introduced in Java to facilitate this functionality.

Callable example:

Let us create a java code that implements the callable interface.

Let's look at the snippet of code that uses the Callable interface and, after a delay of between 0 and 5 seconds, produces a random integer between 0 and 20.

CallableExample.java

// A Java code for the Callable interface implementation
// For generating random numbers between 0 - 20  
  
// Importing the packages required.
import java. util. concurrent. Callable;  
import java.util.Random;  
  
class Jtp implements Callable {  
public Object call () throws Exception {  
Random obj = new Random ();  
// Object creation for the Random class using new   
Integer num = obj.nextInt(20);  
// generating a random number between 0 to 20 using nextInt method.
Thread.sleep(num * 1000);  
// the thread is kept in sleep mode for some random time  
return num;  
}  
}  

The callable interface is demonstrated in the previous sample of code. But the work is not yet finished. The returned object, accessible to the main thread, must be stored after the call () method exits. It is important as the main thread must know the call () method returning value. The same goal is achieved by using a Future object. The response from a separate thread is sent from the call () function and is stored in a Future object.

Future is an application just like Callable. Therefore, it must be put into practice to be used. The Future interface does not, however, need to be manually implemented. The FutureTask class from the Java library already implements the Runnable and Future interfaces.

CallableExample1.java

// A Java code for the Callable interface implementation
// For generating random numbers between 0 - 20  
import java. util. concurrent. Callable;  
import java.util.Random;  
import java.util.concurrent.FutureTask;  
  // importing the packages required.  


Class JCal implements Callable  
{  
@Override  
public Object call () throws Exception  
{  
Random obj = new Random ();  
// Object creation for the Random class   
Integer num = obj.nextInt(10);  
// generating a random number between 0 to 9 using nextInt method.  
  
Thread.sleep(num * 1000);  
// the thread is kept in sleep mode for some random time
// returning the object created that contains a random number  
return num;  
}  
}  
  
public class CallableExample1 {  
  // start of the main method 
  public static void main (String args[]) throws Exception {  
      
    // creating an array of 5 objects of the FutureTask class  
    FutureTask[] treads = new FutureTask[10];  
    
    // using a loop for creating and running 10 threads  
    for (int j = 0; j < 10; j++)  
    {  
      // Object creation for the JavaCallable class  
      Callable cobj = new JavaCallable();  
    
      //Creation of the FutureTask reference with Callable object
      treads[j] = new FutureTask(cobj);  
    
      Thread tobj = new Thread(treads[j]);  
      tobj.start();  
    }  
    
    // Using a loop for generating the random numbers  
    for (int i = 0; i < 10; i++)  
    {  
  
      // Calling the get () method to invoke the thread 
      Object ojb1 = treads[i]. get ();  
        
      // While waiting for the result, the get method maintains control. 
      //When the method is disrupted, the get method may throw the checked exception.
      // Due to this, we must include the throws statement in the main method.  
        
       // printing the numbers generated randomly
      System.out.println("Random number generated is: " + obj1);  
  
    }  
  }  
}  

Output:

Java callable example

We created 10 separate threads in the code. The call () method is called by each thread, which generates a random number and returns it. The main thread receives the generated random number object from the various threads using the get () function. The FutureTask class implements the get () method, defined in the Future interface.

Callable Interface:

  • If we are working with the Callable interface, the call () method must be defined.
  • An Object is the return type of the interface's call () function. Consequently, an Object is returned by the call () function.
  • An exception may be thrown by the call () method.
  • The Callable interface does not allow for the Creation of threads.

Related Topics

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.