Callable and Runnable Examples – ExecutorService

ExecutorService – Callable and Runnable Example
In this article let us see an example using Runnable and Callable tasks using ExecutorService.

Please refer here for Overview of ExecutorService

Runnable Example
Runnable does not return any value and cannot throw checked exceptions

Output:

NOTE:
From the output, we can notice how the executorservice works. We haven’t used Synchronized keyword in any of our methods, but ExecutorService makes sure one thread accesses the methods at a time.

Callable Example
Callable can return Future objects and can throw checked exceptions

Output:

We  have used future object to return string, Future object can return Integer, Boolean etc.
Sample example of using Boolean for the above code,

 

Read More

ExecutorService – An Overview

ExecutorService in Java

What is Executor Service?
Executor service is an interface, which allows us to process tasks asynchronously by threads.

Why ExecutorService over Threads?

ExecutorService has many advantages when compared with using casual threads,

ExecutorService takes care of threads creation for us and also re-uses threads. In java thread creation is expensive as it has to reserve the memory for each threads.  so with ExecutorService, we can create/manage/control life cycle of Threads. Also, ExecutorService provides us with methods like shutdown() and shutdownnow(), When closes the executorservice and will not accept anymore new tasks.

When we use callable in executors, we can get return result for the process.  invokeany() and invokeall() help us to run any or all threads at once.

How to create an ExecutorService?
These are some of the commonly used types of executorservices,

ExecutorService executorService = Executors.newFixedThreadPool(<size>);
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(<size>);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

How to create tasks?
We can create tasks that is either Runnable or Callable. Both instances are executed by another thread. So what is the difference between Runnable and Callable tasks?

Runnable

Callable

Runnable doesn’t return a value Callable can return a value
Runnable cannot throw checked exceptions Callable can throw checked exceptions

Once we have implemented the tasks, we use ExecutorService to execute() or submit() the tasks.  What is the difference between execute() and submit()?

execute() – Return type is void
submit() – Returns future object for managing the tasks.

Future Object:

Using Future object we can get the status of callable tasks.  Future.get() method can wait till the callable task is finished and will return the result

invokeAll() – Executes the given tasks, returning a list of Futures holding their status and results when all complete.

invokeAny() – Executes the given tasks, returning the result of one that has completed successfully, without exception.

Shutdown() – Shutdowns the ExecutorService after completing all the submitted tasks and will not accept any new tasks.

ShutdownNow() – Stops all the executing tasks and returns the list of tasks waiting for execution.

We have covered basics of ExecutorService.

 

Read More

HTTP GET Method – Ways to form GET URL

HTTP GET Method – Ways to form GET URL

In this article let us see the ways to form GET URL for http requests. We are going to use Spring Boot and Google Chrome Postman to verify the URL formation.

Common ways of forming GET url’s are by

  1. Path
  2. Body

Query: (Path)

When GET URL is formed along with query, the URL will look like,

http://example/{id}

Params: (Body)

When GET URL is formed along with Params, we will send the parameters along with the body.

http://example?id=1

There are four parameters with request param,

  • defaultValue – This is the default value, if the request is not having the value or it is empty.
  • name – Parameter name
  • required – true, if we want to make the parameter required one.
  • value – value of the parameter

Now let us see an example – Various ways to form GET URL.
I have created a simple springboot application with a controller. The output shown below are from chrome postman application.

you can download the code here

Output:
/javainfinite

 

/javainfinite/{id}


/javainfinite/idParam

/javainfinite/params

/javainfinite/uriComponentBuild

/javainfinite/uriBuild

 

Download here

 

Read More

Spring Boot Actuators – Customizing Actuator Endpoint

Spring Boot Actuators – Customizing Actuator Endpoint

SpringBoot – Actuators (Example here)
Spring Boot Actuator brings in several production grade services to your application. Spring Boot Actuators has various number of built-in endpoints.

Actuators helps us monitor and interact with your application. Spring Boot also lets us to create our own endpoints too. These end points can be both enabled or disabled.

We have already seen in-build actuator endpoints here – Spring Boot Actuators – in-built EndPoint.

Let us see how to customize the already existing endpoint. Let us override the /actuator/health endpoint.

To override the health endpoint we will be extending a class – AbstractHealthIndicator

AbstractHealthIndicator:
Class which has base health indicator implementations and encapsulates creation of health and error handling. This will override the method – protected abstract void doHealthCheck(Health.Builder builder) throws Exception.

Let us see an example,

pom.xml

application.properties

ControllerSample.java

App.java

Now without customizing endpoint, if we run the application

Now let us override the health endpoint,

Output after overriding the healthIndicator,


Download this example here

 

 

 

Read More

Spring Boot Actuators – How to use it in application

SpringBoot – Actuators
Spring Boot Actuator brings in several production grade services to your application. Spring Boot Actuators has various number of built-in endpoints.

Actuators helps us monitor and interact with your application. Spring Boot also lets us to create our own endpoints too. These end points can be both enabled or disabled.

Below are some of the Spring Boot Actuator endpoints,

EndPoint Description
/actuator/health Basic health information of the application
/actuator/configprops list of all @ConfigurationProperties
/actuator/info Arbitrary Information
/actuator/auditevents audit events of the application
/actuator/httptrace HTTP trace information
/actuator/metrics Metrics information of the application
/actuator/mappings @RequestMappings in the application
/actuator/scheduledtasks Scheduled tasks in the application
/actuator/shutdown Shutdowns the application

Let us write a sample application to test the spring boot actuator end points.

pom.xml

add this property in application.properties,

application.properties

SampleController.java

App.java

Let us start the application,

 

Once the application is started, we can see the actuators are getting initialized. when we hit localhost:8080/actuator/{endpoint} we can see the information

Here are some sample endpoint outputs,

/actuator/health

/actuator/mappings

/actuator/httptrace

Download Example here

Read More