Log4j2 Maven Configuration

This post is regarding logging (log4j2) configuration in a maven project.

Here’s the steps to add lo4j2 in your maven project :-

Maven Project Structure

You need to have the above project structure .The log4j2.xml that is the logging configuration file ,needs to be placed under src/main/resources folder.

Dependencies

The following dependencies to be added for logging configuration.

Log4j Dependencies
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
Jackson Dependencies

You also need to add the jackson dependencies.If you don’t add these dependencies you will getting the following error while running your application.Log4j require these dependencies.

Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ser.FilterProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
… 21 more

Log4j XML Configuration

You need to create log4j configuration file and place it under src/main/resources .

Rolling File Appender

I have created two Rolling File appenders

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE" name="web" monitorInterval="30" >
<Appenders>
<RollingFile name="RollingFile" fileName="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample.log"
filePattern="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample-%d{yyyy-MM-dd}-%i.log">
<PatternLayout>
<Pattern>%d{ISO8601},%-5p\ [%c],[%X],%m,%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1 MB"/>
</Policies>
</RollingFile>
<RollingFile name="AuditLogAppender" fileName="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample.log"
filePattern="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample-%d{yyyy-MM-dd}-%i.log">
<JsonLayout locationInfo="true" complete="false" charset="UTF-8" compact="true" eventEol="true" properties="true"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1 MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="RollingFile"/>
</Root>
<Logger name="AuditLogger" level="INFO" additivity="false">
<AppenderRef ref="AuditLogAppender"/>
</Logger>
</Loggers>
</Configuration>

Running the Java Application

Create a java application and create a logger instance and try to add some logs for testing the logging configuration.

After you run this java application logs should be created at the file location given in the log4j xml file.

Logging File

That’s all about log4j2 configuration.Happy Coding 🙂

ORA-01882: timezone region not found error in Payara Server

This tutorial will explain how to resolve the “time zone region not found error ” when the user tries to set a JDBC Connection pool in payara server.

We usually get this error when we try to create a JDBC Connection pool in payara server.You will get the following error when you try to ping a newly created connection pool.

The error message shows ORA-01882 : timezone region not found.

To fix this error go to server-config under Configurations. Go to JVM Options( server-config->JVM Settings->JVM Options).

Add the following JVM option and save it:-

-Doracle.jdbc.timezoneAsRegion=false

JVM Options Payara server (timezone Region)

Then try to ping the JBC connection pool and it should work fine.

JDBC Connection Pool in Payara Server

The payara server version which I used is 4.1.1.154. But this solution should work on all the versions of payara server.

Let me know if it works for you. Happy Coding 🙂

Callable Vs Runnable Interface

Both Callable and Runnable are interfaces used to define task supposed to be executed by a separate thread.Also, both of them can be used with lambda expressions. But there are key differences between the two interfaces.

  • Callable interface can return the result of the task defined to be executed whereas Runnable does not return any result .Callable return a Future object which has methods to fetch the result of the task, check if the task has been completed or cancelled etc.
  • Callable can throw checked exceptions whereas Runnable does not throw any exceptions.
  • Callable is a functional interface which is added in Java 1.5 whereas Runnable exists since Java 1.0
  • Callable has call() method which needs to be overriden to define the task whereas Runnable has run() method which needs to be overriden
  • You can not pass the Callable to a Thread ,the way you pass the Runnable Object.You need to use the ExecutorService interface to execute the Callable interface.The interface defines the submit method which takes the Callable object and return a Future Object to retrieve the result.

Runnable Example

Runnable Interface Example

Since runnable interface does not return any result so future.get() method returns null.

Callable Example

Callable Interface Example

In case of callable return the result of the task which is retrieved by future.get() method.

Future Interface

Future has several API to help us with the processing task.

Future.isDone() method tells us if the task has been processed or not.If the task is processed it returns true else false.

Future.get() method returns the actual result of the task being processed.This method blocks the execution until the task is complete.

Future.cancel() method stop the execution of the task and interrupts its underlying thread.If we try to call Future.get() method after the cancel() method ,CancellationException is thrown.

Future.isCancelled() method tells if a future is already cancelled. It return true if it was cancelled .

References:- Java 8 API Documentation

That’s all about Runnable , Callable and Future interface.Happy Coding 🙂

Java Executor Framework Tutorial

The concurrency API in Java was introduced in Java 1.5 .Java Executor framework is used to run the Runnable objects without creating new threads and reusing the existing ones as creating threads is an expensive process. It simplifies the execution of tasks in asynchronous mode.

ExecutorService

An ExecutorService is created using Executors factory methods. The main thread delegates the task to the ExecutorService and it executes the task concurrently, independent of the thread that submitted the task.

ExecutorService is an interface and it has the following implentations:-

Creating ExecutorService

ExecutorService executorService1 = Executors.newSingleThreadExecutor();

ExecutorService executorService2 = Executors.newFixedThreadPool(10);

ExecutorService executorService3 = Executors.newScheduledThreadPool(10);

Delegating tasks to ExecutorService

There are several ways to assign task to ExecutorService. It has methods like execute, submit ,invokeAny ,invokeAll which take a runnable or callable object.

Example

Executor Service Example

The execute service take a runnable object and executes it asynchronously. In the above example I have created an anonymous runnable object and passed it to the execute method.

Output

The execute() method has void return type and its doesn’t return the result of the task execution.

The submit() method take a runnable or callable object and return a Future object.The Future.get() method returns the result of the task.In case of Runnable it returns null if the task has been successfully.

The Callable result can be obtained by the Future’s object using the get method.

Callable Example

Output

The invokeAll() method assigns a collection of tasks to ExecutorService and each of the task is executed.The ExecutorService returns a list of Future Objects and we can obtain the result of the all the callable objects submitted for execution.

The invokeAny() method takes a collection of Callable Objects.It returns the result of one of the Callable Object but there’s is no guarantee which of the Callable result is returned.The ExecutorService returns the result of one of the successful task (if there’s any)

ExecutorService Shutdown

To stop the threads from running in ExecutorService ,the shutdown() method is used.The ExecutorService will not shut down immediately it will no longer accept new tasks.All the tasks submitted before calling the shutdown method are executed.

executorService.shutdown();

There is another shutdown method called shutdownNow() which shuts down the ExecutorService immediately. This will stop all executing tasks and skip all submitted but non processing tasks. There is no guarantee given to the executing tasks.

executorService.shutdownNow();

The ExecutorService awaitTermination() method will block the thread calling it until the ExecutorService has shutdown completely or until a given time out occurs. Its usually called after shutdown() or shutdownNow() method.

executorService.shutdown();
executorService.awaitTermination();

References:- Oracle Docs

That’s all about ExecutorService .I hope you enjoyed reading this article.Happy Coding 🙂

ThreadPoolExecutor and ScheduledThreadPoolExecutor

ThreadPoolExecutor

ThreadPoolExecutor implements ExecutorService .It executes each submitted tasks using one of its internally pooled threads.Thread pools provide improved performance when executing large number of asynchronous tasks.This class provides many adjustable parameters and extensibility hooks. But usually ExecutorFactory methods are used to create thread pool.

You can configure the no of threads in the ThreadPoolExecutor using the following variables:-

  • corePoolSize
  • maximumPoolSize

The ThreadPoolExecutor automatically adjust the pool size as per the bounds set by corePoolSize and maximumPoolSize.When a new task is submitted and fewer than core pool threads are running , a new thread is created to handle the request ,even if other threads are idle.If there are more than corePoolSize threads but less than maximumPoolSize threads running, a new thread is created only if the queue is full. Typically maximum and core pool size are set at the time of construction but they can also be set dynamically using the setter methods for maximum and core pool size. If the corePoolSize and maximumPoolSize is same a fixed size thread pool is created.

The ThreadPoolExceutor has several constructors available and you can specify corePoolSize ,maximumPoolSize, keepAliveTime, timeUnit, BlockingQueue and also ThreadFactory and RejectedExceutionHandle

ThreadPoolExecutor Example

Output

ScheduledThreadPoolExecutor

ScheduledThreadPoolExceutor can additionally schedule commands to run after a given delay or to execute periodically. This class is preferable when multiple threads are needed or when the additional capabilities of ThreadPoolExecutor is required.

Delayed tasks are executed no sooner than they are enabled, but without any guarantee about when , after they are enabled ,they will commence.

When a submitted task is cancelled before it is run ,execution is suppressed. By default such a cancelled task is not automatically removed from the work queue until the delay lapses.This enabled further inspection and monitoring but it may also lead to unbounded retention of cancelled tasks. To avoid this you can set setRemoveOnCancelPolicy(boolean) to true, which causes tasks to be immediately removed from the work queue at the time of cancellation. Successive execution of a tasks scheduled via scheduledAtFixedRate or scheduledWithFixedDelay do not overlap.While different executions may be performed by different threads ,the effect of prior execution happen before those of subsequent ones.

The schedulexxx() methods of ScheduledPoolExceutor accept instance of Runnable or Callable.You can get the result of computation of the Callable instance via get() method of ScheduledFuture.

Example

ScheduledThreadPoolExecutor Example

In the above example a scheduled thread pool is created with a thread pool of 5 threads . A runnable and callable task is created which is passed to the executor service .The runnable task is scheduled to run with a fixed delay of 1 second and the callable task is scheduled to execute after a delay of 3 seconds.

Output

References:- Oracle Docs

That’s all about the ThreadPoolExecutor and ScheduledThreadPoolExecutor .I hope you enjoyed reading this article.Happy Coding .