Camel Jetty Component Example

The jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. Here is one simple example to expose a jetty end point and serving the http request from REST client.

1. Create Maven project with below dependencies.

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.12.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Create a Simple Route to expose Jetty endpoint.

package com.vinod.test;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class CamelJettyExample {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyCamelJettyBuilder());
        main.run(args);
    }
}

class MyCamelJettyBuilder extends RouteBuilder {
    public void configure() {
        from("jetty:http://localhost:8181/mytestservice").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String message = exchange.getIn().getBody(String.class);
                System.out.println("Hello Mr :" + message);
                exchange.getOut().setBody("Hello world Mr " + message);
            }
        });
    }
}

3. Run it
Run the application and hit the service
http://localhost:8181/mytestservice


4. Done !! Download application
https://github.com/kkvinodkumaran/camel

Java Thread join() — Run Threads in a Specific Order

Java Thread join() — Run Threads in a Specific Order 

The join() method is one of the simplest yet most powerful ways to control thread execution order in Java.

By default, Java threads run asynchronously, meaning:

  • They start immediately

  • They run independently

  • Their execution order is not guaranteed

But in some use cases—such as sequential processing, workflow pipelines, scheduler tasks—you need Thread A → then Thread B → then Thread C.

This is where join() helps.


What Does join() Do? (Simple Explanation)

join() tells the current thread:

“Wait here until the other thread finishes.”

Example:
If t1.join() is called inside the main thread:

main thread waits → until t1 finishes → then continues

So you get guaranteed ordering.


Use Case: Run Threads in Sequence

We want:

Thread 1Thread 2Thread 3

Each thread must start only after the previous one completes.


Full Java Example — Using join()

ThreadJoinExample.java

package threading; /** * This example demonstrates how the Thread join() method works. * * Requirement: * - Thread 2 must start only after Thread 1 completes * - Thread 3 must start only after Thread 2 completes * * We use join() to ensure strict sequential execution. * * @author vinod */ public class ThreadJoinExample { public static void main(String[] args) { Thread t1 = new Thread(new MyThread1()); Thread t2 = new Thread(new MyThread2()); Thread t3 = new Thread(new MyThread3()); try { t1.start(); // Thread 2 will start only after completion of Thread 1 t1.join(); t2.start(); // Thread 3 will start only after completion of Thread 2 t2.join(); t3.start(); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyThread1 implements Runnable { public void run() { System.out.println("Thread1 Started"); } } class MyThread2 implements Runnable { public void run() { System.out.println("Thread2 Started"); } } class MyThread3 implements Runnable { public void run() { System.out.println("Thread3 Started"); } }

Output

Thread1 Started Thread2 Started Thread3 Started

Execution order is guaranteed.


How It Works (Visual Diagram)

main thread │ ├── t1.start() │── wait using t1.join() │ ├── t2.start() │── wait using t2.join() │ └── t3.start()

Timeline:

t1: ──────────────(done) t2: ──────────────(done) t3: ──────────────(done)

When Should You Use join()?

Use join() when you need deterministic ordering:

✔ Workflow steps

Step 1 → Step 2 → Step 3

✔ Dependent tasks

Database migration → Index rebuild → Service restart

✔ Blocking until background work completes

Render UI only after data loads

✔ Waiting for multiple threads (with join() on each)


Important Notes

  • join() blocks the current thread, not the target thread

  • join() can cause performance issues if overused

  • For large-scale concurrency, prefer ExecutorService or Virtual Threads


Interview Tip

Q: What is the difference between start() and run()?

  • start() → creates a new thread

  • run() → executes like a normal method in the same thread

join() only works with start().


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

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts