×

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

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 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.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.