Writing to Different Log Files Example using Log4j

One of the common requirement in Java projects, that are using Log4j, and want to write logs into different files for each module (or layer) in the project. For example, if you have a an application and you may want to log the messages from the service layer to a service.log file and the log messages from the DAO layer to the DAO.log file and so on. This is very simple to achieve using Log4j. EVEN you can differentiate logs for EACH Java class with the project.



log.properties

# Root logger option
log4j.rootLogger=INFO, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/default_Logs.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}] %-5p %m%n

Now call the below method loadLog4jConfig(this) from the class for which you want to differentiate log file. A common practice is to call the below method from the constructor of the class. It will runtime generate a log file named as that of class name and will write all corresponding logs into this particular log file. 

public static void loadLog4jConfig(Object obj)

 {

 try

 {

     Class<?> thisClass = (obj.getClass());

     String CLASS_NAME = thisClass.getSimpleName();

   

     String logFileName = "logs/" + CLASS_NAME + ".log";

   

     Properties props = new Properties();

     InputStream configStream = thisClass.getResourceAsStream("/log4j.properties");

     props.load(configStream);

     configStream.close();

   

     props.setProperty("log4j.appender.file.File", logFileName);

     LogManager.resetConfiguration();

    PropertyConfigurator.configure(props);

 }

 catch (Exception e)

 {

    e.printstacktrac();

 }

 }

Note: There are so many others ways also, however the above method is the simplest way to write logs into different files.


Passing Extra Login Fields with Spring Security

In Spring Security, it just support to receive only 2 parameters i.e. user_name and password by default. Now, we have a scenario where login form includes login_type as well as a third field. We just want to pass more one parameter along with this login form.


There's a number of ways to achieve this. Most used method is by extending UsernamePasswordAuthenticationFilter class and creating your custom filters. However this is complex and long 
procedure, lot of code required.

In this article I am going to explore two easiest ways:

Method 1:


Add the following listener in web.xml.

Note: The order of listener should be first one, if are there many listener.

Step (i)
<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>
<context-param>
    <param-name>loginType</param-name>
    <param-value></param-value>
</context-param>

Step(ii)


Now add below code snippet in your java code where you want to get this additional parameter. In my case I am getting it in AuthenticationProvider's Authentication authenticate() method as below:

RequestAttributes attribs = RequestContextHolder.getRequestAttributes();

HttpServletRequest request = null;
  
if (RequestContextHolder.getRequestAttributes() != null) {
    request = ((ServletRequestAttributes) attribs).getRequest();
}
  
System.out.println("extra param : "+ request.getParameter("loginType"));

Method 2:


Another easiest way if you are using Custom AuthenticationProvider. You can just inject HttpServletRequest and retrieve your extra parameter:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired(required = false)
private HttpServletRequest request;

@Autowired
UserService userService;

@Override
public Authentication authenticate(Authentication authentication) 
{
   System.out.println("request testing= " + request.getParameter("loginType"));
}

@Override
public boolean supports(Class<?> authentication) {
 return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}


Hope You enjoy both above methods. :)

AES-128 Example in JAVA

The example given will accomplish below Tasks.

  • Generate symmetric key using AES-128.
  • Generate initialization vector used for CBC (Cipher Block Chaining).
  • Encrypt message using symmetric key and initialization vector.
  • Decrypt the encrypted message using symmetric key and initialization vector.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESManager {

 public static String ALGORITHM = "AES";
 // public static String AES_CBC_NoPADDING = "AES/CBC/NoPadding";
 public static String AES_CBC_PADDING = "AES/CBC/PKCS5Padding";

 public static byte[] encrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  return AESManager.encryptDecrypt(Cipher.ENCRYPT_MODE, key, IV, message);
 }

 public static byte[] decrypt(final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  return AESManager.encryptDecrypt(Cipher.DECRYPT_MODE, key, IV, message);
 }

 private static byte[] encryptDecrypt(final int mode, final byte[] key, final byte[] IV, final byte[] message) throws Exception {
  final Cipher cipher = Cipher.getInstance(AES_CBC_PADDING);
  final SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
  final IvParameterSpec ivSpec = new IvParameterSpec(IV);
  cipher.init(mode, keySpec, ivSpec);
  return cipher.doFinal(message);
 }

 public static String getHex(byte[] data, int length) {
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < length; i++) {
   String hexStr = Integer.toHexString(((int) data[i]) & 0xFF);
   if (hexStr.length() < 2) {
    sb.append("0").append(hexStr.toUpperCase());
   } else {
    sb.append(hexStr.toUpperCase());
   }
  }
  return sb.toString();
 }

}
AESClient.java: AESClient class will generate random input message and will invoke AESManager.java to encrypt & decrypt input message.
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.UUID;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AESClient {

 private static int AES_128 = 128;
 private static int AES_192 = 192;
 private static int AES_256 = 256;

 public static void main(String[] args) throws Exception {

  byte keyBytes[] = generateKey();

  String AES_KEY_HEX = AESManager.getHex(keyBytes, keyBytes.length);
  System.out.println("AES-KEY : " +AES_KEY_HEX);

  // Initialization vector
  byte IVBytes[] = generateKey();

  String randomString = UUID.randomUUID().toString().substring(0, 16);
  System.out.println("1. Original Message: " + randomString);

  byte[] cipherText = AESManager.encrypt(keyBytes, IVBytes, randomString.getBytes());
  System.out.println("2. Encrypted Text: " + Base64.getEncoder().encodeToString(cipherText));

  byte[] decryptedString = AESManager.decrypt(keyBytes, IVBytes, cipherText);
  System.out.println("3. Decrypted Message : " + new String(decryptedString));
 }

 public static byte[] generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
  KeyGenerator keyGenerator = KeyGenerator.getInstance(AESManager.ALGORITHM);
  keyGenerator.init(AES_128);
  SecretKey key = keyGenerator.generateKey();
  return key.getEncoded();
 }
}
Sample outPut:
AES-KEY : 6239A5DBBA65D0D42E6520922621A8B8
1. Original Message: 5dbf850f-3938-48
2. Encrypted Text: smV12iTwLIHNTgFRSDzG2xmzYl5yRJQ6Jo2qnqK0iqc=
3. Decrypted Message : 5dbf850f-3938-48Generate symmetric key using AES-128.

Important Note:

AES uses block size of 16 bytes (128 bits), so if you are using "AES/CBC/NoPadding", then Smaller input must be padded with zeros to 16 bytes otherwise you will get below exception:

javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes


In order to avoid padding at your end, then you have to use "AES/CBC/PKCS5Padding" as shown in above example.


GlobalPlatform Secure Channel Protocol - SCP02 and SCP03

GlobalPlatform

GlobalPlatform (GP) is a cross industrial consortium that issues specifications about smart cards.

GP Card Specification

A set of technical documentation relating to the deployment and management of multiple applications on smart card.

Secure Channel Protocol (SCP)

An SCP is used to protect bidirectional communication between Java Card and Host. It is used as Mutual authentication and provide cryptographic protection for card and host subsequent communication.

SCP provides the following three levels of  security:

  • Mutual authentication
  • Data Integrity
  • Confidentiality

Mutual authentication

Mutual authentication is achieved through the process of initiating a Secure Channel and provides assurance to both; card and host, that they are communicating with an authenticated entity. This process include the creation of new challenges and secure channel session keys. If any step in the mutual authentication process fails, the process shall be restarted, i.e. new challenges and Secure Channel Session keys shall be generated again.

Data Integrity

Data or message integrity is checked by comparing C-MAC received from off-card entity (Host) with the card internally generated C-MAC. Note that this comparison is done using same Secure Channel session key, generated in Mutual authentication step.

Data Confidentiality

The date received from host to card or card to host is not viewable by an unauthorized entity rather it is encrypted with Secure Channel session key generated during the mutual authentication process.


Secure Channel Protocol '02'


SCP02 uses Triple DES encryption algorithm in CBC mode with Initialization vector (IV) of binary zeros. As SCP02 uses 3DES in CBC mode with fixed IV of binary zeros therefore its encryption scheme is deterministic and not highly secure and thus vulnerable to a classical plaintext-recovery attacks.

SCP02 relies on the «Encrypt-and-MAC» method, which means that it compute the MAC on the plain-text, encrypt the plain-text, and then append the MAC at the end of the ciphertext as shown in below diagram:


Encrypt-and-MAC Method

Secure Channel Protocol '03'


SCP03 uses Advanced Encryption Standard (AES) encryption algorithm with randomly generated Initialization vector (IV) and Hence its encryption scheme is un-deterministic and highly secure.

SCP03 relies on the «Encrypt-then-MAC» method, which means that it Encrypt the plain-text, then compute the MAC on the ciphertext, and append the MAC to the ciphertext as shown in below diagram:


Encrypt-then-MAC Method


SCP03 provides strong security guarantees, resistance to replay, out of order delivery and algorithm substitution attacks.

SCP02 vs SCP03 Summary Table



Why we need SCP03?

As the latest Java Cards have support for RSA above 2048, AES-128, AES-192, AES-256 and Elliptic-curve cryptography (ECC) (f=256 and above), SCP02 cannot be used to encrypt above keys types and hence such keys cannot be loaded using SCP02 mechanism. As a result GlobalPlatform provided a mechanism in the form of SCP03 by which such keys can be loaded into the cards.



Note: You can read more about SCP02 in GlobalPlatform Card Specification Version 2.1.1 Appendix E, while regarding SCP03 you can refer to GlobalPlatform Card Specification Version 2.2

Installation and setup of the Java Cryptography Extension (JCE)

Encryption mechanism is governed by laws of each country and often have restrictions on the strength of the encryption. Like in the United States, all encryption over 128-bit is restricted if the data is travelling outside the country.By default, the Java JCE implements a strength policy to comply with these rules. If a stronger encryption is preferred, and adheres to the laws of the country, then the JCE needs to have access to the stronger encryption policy. In other words, if you are planning on using AES 256-bit encryption, you must install the Unlimited Strength Jurisdiction Policy Files. Without these policies, 256-bit encryption is not possible.

In case of violating above rules get the exception  org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size or default parameters

OR

"java.security.InvalidKeyException:illegal Key Size" error when invoking secured services.

The above exception usually occurs when we try to invoke the web services in a secured manner and your JVM is not provisioned for Java unlimited security jurisdiction policy.

So in order to provision for the Java unlimited security jurisdiction you must have to install Java Cryptography Extension (JCE) unlimited strength jurisdiction policy files.

Installation Steps

  • Go to the Oracle site  http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html.
  • Download the version that matches your installed JVM. Like I have Java 7 installed so download UnlimitedJCEPolicyJDK7.zip
  • Unzip the folder and replace local_policy.jar and US_export_policy.jar in the path C:\Program Files\Java\jdk1.7.0_67\jre\lib\security.  (Note: these jars will be already there so you have to overwrite them)  
  • Simply restart your application to get rid of this exception.



What is AngularJS and Why it is considered as an emerging JavaScript Framework?

AngularJS is a very powerful and most emerging JavaScript Framework.It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world.

If you want to learn AngularJS, you must have an understanding of HTML, CSS, JavaScript and AJAX, etc.

Brief History of AngularJS

AngularJS is an open source web application framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now officially supported by Google. According to official documentation of AngularJS its definition is:

"AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you currently have to write. And it all happens within the browser, making it an ideal partner with any server technology."


AngularJS Features


  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA).
  • AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.

Overall, AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain.




Advantages of AngularJS



  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer write less code and get more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
On top of everything, AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets.


Advantages of Components

The AngularJS framework can be divided into following three major parts −

  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.


AngularJS Setup

You really do not need to set up your own environment to start learning AngularJS. Reason is there is lot of AngularJS environment online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. You can modify the samples and execute it to see your expected results. However if you want to setup the environment at your local machine then you to download AngularJS library from below official site:

https://angularjs.org

The latest current stable version of angularJS is  v1.6.6.

AngularJS Example

Now let us write a simple example using AngularJS library. Let us create a simple HTML file AngularWorld.html as below:
<!doctype html>
<html>
   
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
   </head>
   
   <body ng-app = "myapp">
      
      <div ng-controller = "HelloController" >
         <h2>Welcome {{helloTo.title}} to learn AngularJS!</h2>
      </div>
      
      <script>
         angular.module("myapp", [])
         
         .controller("HelloController", function($scope) {
            $scope.helloTo = {};
            $scope.helloTo.title = "naeemgik";
         });
      </script>
      
   </body>
</html>





Now lets explain the above code line by line;



In order to include the angularJS file in your page, we have included it using CDN access like:

<head>
   <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>


Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below:

<body ng-app = "myapp">
</body>

The view part of the above example is:

<div ng-controller = "HelloController" >
   <h2>Welcome {{helloTo.title}} to learn AngularJS!</h2>
</div>

ng-controller tells AngularJS what controller to use with this view. helloTo.title tells AngularJS to write the "model" value named helloTo.title to the HTML at this location.
The controller part of the above example is:

<script>
   angular.module("myapp", [])
   
   .controller("HelloController", function($scope) {
      $scope.helloTo = {};
      $scope.helloTo.title = "naeemgik";
   });
</script>



This code registers a controller function named HelloController in the angular module named myapp. The controller function is registered in angular via the angular.module(...).controller(...) function call.



The $scope parameter passed to the controller function is the model. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.



When you execute the above sample program its out will be look like:


Welcome naeemgik to learn AngularJS!


When the page is loaded in the browser, following things happens:

HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded, the angular global object is created. Next, JavaScript which registers controller functions is executed.

Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.


Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page is now ready.


Execute shell command from Java

Sometime we need to execute shell commands from java code. Like in case where we use jar file in our java code and running that jar from shell command like java -jar <jar_name.jar> or in order to find java version from shell command like java -verison

In this tutorial I am going to write a sample program wich execute the same command from java code.


CmdTest.java

import java.io.*;

public class CmdTest
{
 

public static void main(String[] args) throws Exception
{
String arg1 = "cmd.exe";
String commandToExec = "java -version";

final String folder= System.getProperty("user.dir")+"/lib\"";
String[] command = { arg1, "/C", "cd \""+folder+"&&"+commandToExec};

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true)
{
line = r.readLine();
if (line == null)
{
break;
}

System.out.println(line);
}
}
}

Output:


java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)



8 features of java 8

JAVA 8 or JDK 1.8 is a major release of JAVA language. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided support for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API and many more.


8 New Features of Java 8



The most significant features of java 8 are below:

Lambda expression: 

It adds functional processing capability to Java. A new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.

Method references: 

Referencing functions by their names instead of invoking them directly. Using functions as parameter. Provide easy-to-read lambda expressions

Default method: 

Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.


Stream API: 

New Stream API (java.util.stream ) to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.

Date Time API: 

The Date/Time API is moved to java.time package and Joda time format is followed. Another good news is that, most classes are Thread safe and immutable.

Nashorn, JavaScript Engine: 

A Java-based engine to execute JavaScript code. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly.


New tools:

New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.

Optional Values:

Emphasis on best practices to handle null values properly. Java SE 8 introduces a new class called java.util.Optional that can alleviate some of these problems.

References: 
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

Java 8 - Lambda Expressions

Lambda expressions are introduced in Java 8 and are assumed to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and it simplifies the development very much.
A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body.

Syntax

A lambda expression is characterized by the following syntax:

parameter -> expression body

Following are the important characteristics of a lambda expression

Optional type declaration: No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.

Optional parenthesis around parameter:  No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional curly braces: No need to use curly braces in expression body if the body contains a single statement.
Optional return keyword: The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.



Lambda Expressions Example


Create the following Java program using eclipse editor

LambdaExpressionTest.java

public class LambdaExpressionTest {
public static void main(String args[]) {
LambdaExpressionTest test = new LambdaExpressionTest();

// with type declaration
MathOperation addition = (int a, int b) -> a + b;

// with out type declaration
MathOperation subtraction = (a, b) -> a - b;

// with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> {
return a * b;
};

// without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;

System.out.println("10 + 5 = " + test.operate(10, 5, addition));
System.out.println("10 - 5 = " + test.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + test.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + test.operate(10, 5, division));

// without parenthesis
GreetingService greetService1 = message -> System.out.println("Hi " + message);

// with parenthesis
GreetingService greetService2 = (message) -> System.out.println("Hi " + message);

greetService1.sayMessage("Guest");
greetService2.sayMessage("User");
}

interface MathOperation {
int operation(int a, int b);
}

interface GreetingService {
void sayMessage(String message);
}

private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}

When you execute the program its output look like:

10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hi Guest
Hi Welcome to my blog

Important points to be considered from above example.


Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.

Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Java ExecutorService

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation.


ExecutorService Example


Here is a simple Java ExectorService example:

ExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});


executorService.shutdown();



First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.


Task Delegation


Here is a diagram illustrating a thread delegating a task to an ExecutorService for asynchronous execution:




Once the thread has delegated the task to the ExecutorService, the thread continues its own execution independent of the execution of that task.


ExecutorService Implementations


Since ExecutorService is an interface, you need to its implementations in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:

ThreadPoolExecutor
ScheduledThreadPoolExecutor


Creating an ExecutorService


How you create an ExecutorService depends on the implementation you use. However, you can use the Executors factory class to create ExecutorService instances too. Here are a few examples of creating an ExecutorService:

ExecutorService exSer1 = Executors.newSingleThreadExecutor();

ExecutorService exSer2 = Executors.newFixedThreadPool(10);


ExecutorService exSer3 = Executors.newScheduledThreadPool(10);





ExecutorService Usage


There are a few different ways to delegate tasks for execution to an ExecutorService:

execute(Runnable)
submit(Runnable)
submit(Callable)
invokeAny(...)
invokeAll(...)

I will take a look at each of these methods in the following sections.



execute(Runnable)



The execute(Runnable) method takes a java.lang.Runnable object, and executes it asynchronously. Here is an example of executing a Runnable with an ExecutorService:

ExecutorService executorService = Executors.newSingleThreadExecutor();

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});


executorService.shutdown();



There is no way of obtaining the result of the executed Runnable, if necessary. You will have to use a Callable for that (explained in the following sections).

submit(Runnable)


The submit(Runnable) method also takes a Runnable implementation, but returns a Future object. This Future object can be used to check if the Runnable as finished executing.

Here is a ExecutorService submit() example:


Future future = executorService.submit(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});

future.get();  //returns null if the task has finished correctly.



submit(Callable)


The submit(Callable) method is similar to the submit(Runnable) method except for the type of parameter it takes. The Callable instance is very similar to a Runnable except that its call() method can return a result. The Runnable.run() method cannot return a result.


The Callable's result can be obtained via the Future object returned by the submit(Callable) method. Here is an ExecutorService Callable example:


Future future = executorService.submit(new Callable(){
    public Object call() throws Exception {
        System.out.println("Asynchronous Callable");
        return "Callable Result";
    }
});


System.out.println("future.get() = " + future.get());


The above code example will output this:

Asynchronous Callable
future.get() = Callable Result


invokeAny()


The invokeAny() method takes a collection of Callable objects, or subinterfaces of Callable. Invoking this method does not return a Future, but returns the result of one of the Callable objects. You have no guarantee about which of the Callable's results you get. Just one of the ones that finish.

If one of the tasks complete (or throws an exception), the rest of the Callable's are cancelled.

Here is a code example:

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 2";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 3";
    }
});

String result = executorService.invokeAny(callables);

System.out.println("result = " + result);

executorService.shutdown();


This code example will print out the object returned by one of the Callable's in the given collection. I have tried running it a few times, and the result changes. Sometimes it is "Task 1", sometimes "Task 2" etc.


invokeAll()


The invokeAll() method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of each Callable.

Keep in mind that a task might finish due to an exception, so it may not have "succeeded". There is no way on a Future to tell the difference.

Here is a code example:


ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 2";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 3";
    }
});

List<Future<String>> futures = executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}

executorService.shutdown();


ExecutorService Shutdown

When you are done using the ExecutorService you should shut it down, so the threads do not keep running.

For instance, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.

To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.

If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.