Java Callable and Future Simple Example

 

🧵 Java Callable and Future – Simple Example

💡 Overview

In Java, the Callable and Future interfaces are part of the java.util.concurrent package and provide a more powerful alternative to the traditional Runnable interface.

Both Runnable and Callable are designed for classes whose instances can be executed by another thread — but with one key difference:

InterfaceReturns Result?Throws Checked Exception?
Runnable❌ No❌ No
Callable✅ Yes✅ Yes

So, if you need a thread to return a result or throw a checked exception, Callable is the right choice.


⚙️ Key Concepts

  1. Callable Interface

    • Similar to Runnable, but defines a method call() that can return a result and throw exceptions.

    • Signature:

      V call() throws Exception;
  2. ExecutorService

    • Manages a pool of worker threads.

    • Handles thread creation, task scheduling, and shutdown gracefully.

  3. Future Interface

    • Represents the result of an asynchronous computation.

    • Allows you to retrieve the result using future.get() once the task completes.


🧩 Example: Callable and Future in Action

1️⃣ File: CallableExample.java

package threading; 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; /** * Demonstrates the use of ExecutorService, Callable, and Future interfaces. * * <ul> * <li>Thread1 implements Callable and overrides call() to return the thread name.</li> * <li>ExecutorService uses a fixed thread pool to execute multiple tasks.</li> * <li>Future stores and retrieves the result returned by Callable.</li> * </ul> * * Author: Vinod Kariyathungal Kumaran */ public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { // Create a fixed thread pool of 10 threads ExecutorService ex = Executors.newFixedThreadPool(10); Thread1 t1 = new Thread1(); // Submit the Callable task multiple times and print results for (int i = 0; i <= 10; i++) { Future<String> future = ex.submit(t1); System.out.println(future.get()); } // Shutdown the executor ex.shutdown(); } } /** * Thread1 implements Callable and returns the current thread's name. */ class Thread1 implements Callable<String> { @Override public String call() throws Exception { return Thread.currentThread().getName(); } }

🧾 Output

pool-1-thread-1 pool-1-thread-2 pool-1-thread-3 pool-1-thread-4 pool-1-thread-5 pool-1-thread-6 pool-1-thread-7 pool-1-thread-8 pool-1-thread-9 pool-1-thread-10 pool-1-thread-1

🧠 Explanation

  1. ExecutorService creates a pool of 10 threads.
    This means at most 10 threads can run concurrently.

  2. Each time we call ex.submit(t1), the executor picks an available thread from the pool and runs the task.

  3. The Future<String> returned by submit() is used to get the result from Thread1.call().

  4. The output shows that threads are reused by the executor (thread-1 appears again at the end).

 

Java Template engine Freemarker simple example

1. Create a maven project and add below dependency

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.19</version>
</dependency>
            

2. Create a Template file and placed in to project folder (helloworld.flt)

Hello world Mr ${name}

3. Create a main class (FreeMarkerExample.java)

package com.pretech;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerExample {
	public static void main(String[] args) {
		try {
			Configuration config = new Configuration();
			Map<String, String> root = new HashMap<String, String>();
			root.put("name", "PRETECH");
			Template template;
			template = config.getTemplate("helloworld.ftl");
			StringWriter out = new StringWriter();
			template.process(root, out);
			System.out.println(out.getBuffer().toString());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}

4. Output



Hello Mr PRETECH


Joining Iterable values using Guava Joiner

Joiner is an object which joins pieces of text which is from Iterable like ArrayList or Map. Here is one simple example to Joins ArrayList and Map values using Guava Joiner.

1. Create a Maven project add Guava dependency

  <dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>r09</version>
</dependency>

2. Create a Main Program to Join values (JoinerExample.java)

package com.pretech;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public class JoinerExample {
	public static void main(String[] args) {
		// ArrayList Joining and skipping null
		final List<String> days = Lists.newArrayList("sunday", "monday",
				"tuesday", null);
		System.out.println(Joiner.on("\t ").skipNulls().join(days));
		// Map Joining
		final Map<String, String> personDetails = ImmutableMap.of("Name",
				"vinod", "Location", "Bangalore");
		System.out.println(Joiner.on("\t").withKeyValueSeparator(": ")
				.join(personDetails));
	}
}

3. Output



sunday     monday     tuesday
Name: vinod    Location: Bangalore


How to convert Java Properties to HashMap?

package com.pretech;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesToHashMap {
	public static void main(String args[]) {
		Properties properties = new Properties();
		properties.put("name", "Raj");
		Map<String, String> map = new HashMap<String, String>((Map) properties);
		System.out.println("Name is :" + map.get("name"));
	}
}

Output



Name is :Raj


XML to Java object using XMLDecoder Example

XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean.
The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like ObjectInputStream. Here is one simple example to convert a java object to xml String and xml String to Java object

1. Create a java bean (Customer.java)

package com.pretech;
public class Customer {
	private String name;
	private String address;
	public Customer() {
	}
	public Customer(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}
//Getters and Setters

2. Create a main class to convert java object to xml

package com.pretech;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class ExlDecoderExample {
	public static void main(String[] args) {
		Customer c1 = new Customer("Pretech", "Bangalore");
		
		String customerXml=objectToXML(c1);
		System.out.println("Customer xml data :" +customerXml );
		System.out.println("Customer object data :" + XMLToObject(customerXml));
	}
	public static String objectToXML(Object voObj) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = null;
		try {
			xmlEncoder = new XMLEncoder(new BufferedOutputStream(stream));
			xmlEncoder.writeObject(voObj);
			xmlEncoder.close();
			return stream.toString("UTF-8");
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	public static Object XMLToObject(String dataXML) {
		XMLDecoder d = null;
		try {
			d = new XMLDecoder(new ByteArrayInputStream(
					dataXML.getBytes("UTF-8")));
			Object voObj = d.readObject();
			d.close();
			return voObj;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
}

3.Output

Customer xml data :<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_04" class="java.beans.XMLDecoder">
 <object class="com.pretech.Customer">
  <void property="address">
   <string>Bangalore</string>
  </void>
  <void property="name">
   <string>Pretech</string>
  </void>
 </object>
</java>
Customer object data :Customer [name=Pretech, address=Bangalore]

Ref: http://www.oracle.com/technetwork/java/persistence4-140124.html

Java object to xml using XmlEncoder Example

XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean. Here is one simple example to convert a java object to xml String.

1. Create a java bean (Customer.java)

package com.pretech;
public class Customer {
	private String name;
	private String address;
	public Customer() {
	}
	public Customer(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}
//Getters and Setters

2. Create a main class to convert java object to xml

package com.pretech;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
public class XMLEncoderExample {
	public static void main(String[] args) {
		Customer c1 = new Customer("Pretech", "Bangalore");
		
		String customerXml=objectToXML(c1);
		System.out.println("Customer xml data :" +customerXml );
	}
	public static String objectToXML(Object voObj) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = null;
		try {
			xmlEncoder = new XMLEncoder(new BufferedOutputStream(stream));
			xmlEncoder.writeObject(voObj);
			xmlEncoder.close();
			return stream.toString("UTF-8");
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	
}

3.Output

Customer xml data :<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_04" class="java.beans.XMLDecoder">
 <object class="com.pretech.Customer">
  <void property="address">
   <string>Bangalore</string>
  </void>
  <void property="name">
   <string>Pretech</string>
  </void>
 </object>
</java>

Ref: http://www.oracle.com/technetwork/java/persistence4-140124.html

Spring ResourceLoader/ResourceloaderAware Example

Spring org.springframework.core.io.Resource interface is used to load resources from the class path. Here is one simple example to load a text file from the class path.
 

Create a maven project and add Spring dependencies

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
 

Create a Spring configuration class

package com.vinod.test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.vinod.test")
public class MySpringConifg {
   
}
 

Place one text file in to the class path

vinod.txt in to src/main/resources folder

Test class

package com.vinod.test;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;

public class ResourceLoaderTest {

    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MySpringConifg.class);
        context.refresh();
        Resource resource = context.getResource("classpath:vinod.txt");
        String theString = IOUtils.toString(resource.getInputStream(), "UTF-8");
        System.out.println(theString);
   
    }

}
 

Run the program and check the console for the output..

In the above program we are getting the Resource from the Spring context it self, if we wanted to get it from our own bean, spring provides ResourceLoaderAware interface , this will helps to inject ResourceLoader and we can use that bean to load the resources 

Note: Internally AplicationContext also using the same ResourceLoader to load the resources

Let us see how can we implement this..

package com.vinod.test;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class MyResourceLoader implements ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public Resource getResource(String path) {
        System.out.println("loading resources "+path);
        return this.getResourceLoader().getResource(path);
    }

}
 

Modified Main class

package com.vinod.test;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.Resource;

public class ResourceLoaderTest {

    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MySpringConifg.class);
        context.refresh();
        MyResourceLoader resource = context.getBean(MyResourceLoader.class);
        Resource file = resource.getResource("classpath:vinod.txt");
        String theString = IOUtils.toString(file.getInputStream(), "UTF-8");
        System.out.println(theString);

    }

}
 

Output

loading resources classpath:vinod.txt

hai i am vinod

Done!!!

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts