×

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

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.