Java Thread Pool with Executor Framework

 

Java Thread pool manages the pool of threads which are under runnable state. Thread pools contains list of all Threads in queue which are waiting to get executed. Also Thread pool can be described as collection of Runnable Objects or instance. Thread pool will be constantly running and are checking the work query for new work or Thread to be added into the pool. If there are new work or Thread to be added into the pool and executed through Thread Pool. In Java Thread class itself provides a method, e.g. execute(Runnable r) to add a new Runnable object to the work queue and execute() method will take on executing each thread in the pool.

The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination. Suppose if you want to use 1 thread pool with only 1 thread which executes several runnables you can use the Executors.newSingleThreadExecutor() method.


public class MyRunnableClass implements Runnable {

 private int value;

 MyRunnableClass(int value) {
  this.value = value;
 }

 @Override
 public void run() {
  int total = 0;
  for (int i = 1; i < value; i++) {
   total += i;
  }
  System.out.println(Thread.currentThread().getName() + " : " + total);  
 }
}


public class ThreadPoolTest {

 public static void main(String[] args) {
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  // Total 25 threads we are creating
  for (int i = 1; i <= 25; i++) {
   Runnable worker = new MyRunnableClass(i);
   executor.execute(worker);
  }
  executor.shutdown();
  System.out.println("All Threads finished...");
 }
}


OUTPUT:


pool-1-thread-1 : 0
pool-1-thread-1 : 15
pool-1-thread-1 : 21
pool-1-thread-1 : 28
pool-1-thread-1 : 36
pool-1-thread-1 : 45
pool-1-thread-1 : 55
pool-1-thread-1 : 66
pool-1-thread-1 : 78
pool-1-thread-1 : 91
pool-1-thread-1 : 105
pool-1-thread-1 : 120
pool-1-thread-1 : 136
pool-1-thread-1 : 153
pool-1-thread-1 : 171
pool-1-thread-1 : 190
pool-1-thread-1 : 210
pool-1-thread-1 : 231
pool-1-thread-1 : 253
pool-1-thread-1 : 276
pool-1-thread-1 : 300
All Threads finished...
pool-1-thread-3 : 3
pool-1-thread-4 : 6
pool-1-thread-2 : 1
pool-1-thread-5 : 10



Semaphore in Java

 

Semaphore is an important topic and used under Multi-threading in Java. Semaphore is mainly maintains a set of permits by acquire() and release(). Each acquire() will holds the block if permits are available and it performs the Thread operation and release() the block once it completed the operation. However, no actual permit objects are used; the Semaphore just keeps a count of the number available blocks and acts accordingly. 
We can Semaphore is as same as wait and notify where often used to restrict the number of threads than can access some (physical or logical) resource.
Below are the list of methods and constructors present in Semaphore class. 

Constructors:
There are 2 types of Constructors in Semaphore class 

Semaphore(int permits)

Semaphore(int permits, boolean fair)


Methods:

void acquire()

void acquire(int permits)

void acquireUninterruptibly()

void acquireUninterruptibly(int permits)

int availablePermits()

int drainPermits()

protected Collection<Thread> getQueuedThreads()

int getQueueLength()

boolean hasQueuedThreads()

boolean isFair()

protected void reducePermits(int reduction)

void release()

void release(int permits)

String toString()

boolean tryAcquire()

boolean tryAcquire(int permits)

boolean tryAcquire(int permits, long timeout, TimeUnit unit)

boolean tryAcquire(long timeout, TimeUnit unit)


Now we will simple example for using Semaphore in multi-threading. There are 2 different threads which prints even number by 1 thread and odd numbers by other thread. Numbers should be printed in sequential order like 1,2,3,4,5... etc., using Semaphore class. 



public class SemaphoreTest implements Runnable {
 
 private static int count = 1;
 private boolean flag;
 private static Semaphore even = new Semaphore(0);
 private static Semaphore odd = new Semaphore(1);
 
 public SemaphoreTest(boolean flag){
  this.flag = flag;
 }
 
 private void printEven(){
  while(true){
   try {
    even.acquire();
    System.out.println(Thread.currentThread().getName() + " : "+count++);
    Thread.sleep(100);
    odd.release();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 private void printOdd(){
  while(true){
   try {
    odd.acquire();
    System.out.println(Thread.currentThread().getName() + "  : "+count++);
    Thread.sleep(100);
    even.release();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 @Override
 public void run() {  
  if(flag){
   printEven();
  }else{
   printOdd();
  }  
 }
 
 public static void main(String[] args) {
 
  Thread evenThread = new Thread(new SemaphoreTest(true), "EVEN-THREAD");
  Thread oddThread = new Thread(new SemaphoreTest(false), "ODD-THREAD");
  evenThread.start();
  oddThread.start();
 } 
}


OUTPUT:


ODD-THREAD  : 1
EVEN-THREAD : 2
ODD-THREAD  : 3
EVEN-THREAD : 4
ODD-THREAD  : 5
EVEN-THREAD : 6
ODD-THREAD  : 7
EVEN-THREAD : 8
ODD-THREAD  : 9
EVEN-THREAD : 10
ODD-THREAD  : 11
EVEN-THREAD : 12
ODD-THREAD  : 13
EVEN-THREAD : 14
ODD-THREAD  : 15





Wrapper classes in Java


We all many know that Java is Object Oriented programming and in the world of Java everything will be considered as an Object. In that case when we see about primitive datatypes in java those are all not under any classes in Java. And also before JDK 1.5 all data structures used to store only Objects. In those cases they have came with Wrapper classes for all 8 primitive datatypes in Java. As a name represents "Wrapper" it wraps around the primitive datatype and gives the Objects. 

How these wrapping are done in Java from primitive to Wrapper class objects?
Wrapping done by using constructor of each classes. Each class will accept different types of primitive datatype or Object as a constructor parameter and those parameters are converted to Objects. All these 8 Wrapper classes comes inside java.lang package and immutable classes. Apart from these 8 Wrapper classes other wrapper classes like BigDecimal and BigInteger are not one of the primitive wrapper classes and are mutable. 

Below are the list of 8 primitive datatypes and their corresponding Wrapper classes along with their constructor parameter types.

Primitive typeWrapper classConstructor Arguments
byteBytebyte or String
shortShortshort or String
intIntegerint or String
longLonglong or String
floatFloatfloat, double or String
doubleDoubledouble or String
charCharacterchar
booleanBooleanboolean or String


Bellow is the Wrapper class hierarchy


Wrapper classes in Java

The Byte, Short, Integer, Long, Float, and Double wrapper classes are all sub-classes of the Number class. Lets see small example for converting primitive datatype to Object and from Object to primitive type. 


public class WrapperTest {
 
 public static void main(String[] args) {
  
  int _int = 1;
  byte _byte = 2;
  short _short = 3;
  long _long = 4;
  float _float = 5.5f;
  double _double = 6;
  char _char = 'a';
  boolean _boolean = true;
  
  Integer w_int = new Integer(_int); 
  Byte w_byte = new Byte(_byte);
  Short w_short = new Short(_short);
  Long w_long = new Long(_long);
  Float w_float = new Float(_float);
  Double w_double = new Double(_double);
  Character w_char = new Character(_char);
  Boolean w_boolean = new Boolean(_boolean);
  
  System.out.println("Printing Wrapper class");
  System.out.println("Integer      : "+w_int);
  System.out.println("Byte         : "+w_byte);
  System.out.println("Short        : "+w_short);
  System.out.println("Long         : "+w_long);
  System.out.println("Float        : "+w_float);
  System.out.println("Double       : "+w_double);
  System.out.println("Character    : "+w_char);
  System.out.println("Boolean      : "+w_boolean);
  
  int _int1 = w_int;
  byte _byte1 = w_byte;
  short _short1 = w_short;
  long _long1 = w_long;
  float _float1 = w_float;
  double _double1 = w_double;
  char _char1 = w_char;
  boolean _boolean1 = w_boolean;
  
  System.out.println("\nPrinting Primitive datatype from Wrapper class");
  System.out.println("int          : "+_int1);
  System.out.println("byte         : "+_byte1);
  System.out.println("short        : "+_short1);
  System.out.println("long         : "+_long1);
  System.out.println("float        : "+_float1);
  System.out.println("double       : "+_double1);
  System.out.println("char         : "+_char1);
  System.out.println("boolean      : "+_boolean1);
 }
}

OUTPUT:


Printing Wrapper class
Integer      : 1
Byte         : 2
Short        : 3
Long         : 4
Float        : 5.5
Double       : 6.0
Character    : a
Boolean      : true

Printing Primitive datatype from Wrapper class
int          : 1
byte         : 2
short        : 3
long         : 4
float        : 5.5
double       : 6.0
char         : a
boolean      : true


Difference between ArrayList and Vector in Java

 

ArrayList and Vector are the important collection classes which used in Java. And also widely asked in interview about their difference and similarities between these 2 classes. Before looking into the difference and similarities between these two classes lets discuss some of the collection classes and interface in Java Collection framework. Below hierarchy diagram will give you the brief structure of the interface and classes in Collection framework like what are all the classes derived from different interface. 


Java Collections


Similarities:

  • Both ArrayList and Vector implements List interface.
  • Both ArrayList and Vector are ordered collection and allow duplicate and null values.
  • Both ArrayList and Vector are index based and values can retried by using index, which means internally it uses array as data structure to store the values. 
  • While initializing both ArrayList and Vector size will be 10 by default.


Differences: 

  • Vector is thread-safe and ArrayList is non thread-safe, which means Vector is synchronized and ArrayList is not. Suppose if we using any multi-threading or concurrent process then Vector will be best suited and other ways ArrayList will be best.
  • Performance wise Vector will be slow since its synchronized. 
  • Vector introduced in first version of JDK and from JDK 1.2 its merged with Java Collection framework and its implements List interface. Where as ArrayList introduced in JDK 1.2 along with Collection framework
  • By default both ArrayList and Vector increment the size automatically. The difference is ArrayList will increments its array size by half of its size, where as Vector will doubles the size of its array when its size is increased by default suppose if we didn't set the capacity Increment size.
  • Vector's capacity size increment can be set to any number when we initialize  where as ArrayList we can't. 


ArrayList initialize:

ArrayList<String> arr = new ArrayList<String>(); // Default initialCapacity = 10

ArrayList<String> arr = new ArrayList<String>(100); // initialCapacity = 100

Vector initialize:

Vector<String> vec = new Vector<String>(); // Default initialCapacity = 10

Vector<String> vec = new Vector<String>(100); // initialCapacity = 100

Vector<String> vec = new Vector<String>(100,10); // initialCapacity = 100 and capacityIncrement = 10


Reading excel sheet in Java


In our earlier tutorial we have seen how to create excel sheet using Apache POI library in Java. As same we will see how to read excel sheet file using Apache POI. We are using same Employee Details class and excel sheet which used in our earlier tutorial for this demo. So before looking into this tutorial please take a look on earlier tutorial as how we have created the Excel sheet using POI and bean class which we have used. 

POI jar file (Download latest version)


import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ReadExcel {
 
 public static void main(String[] args) {
  
  List<EmployeeDetails> list = readExcelSheet("D://test.xls");
  
  displayEmployeeDetails(list);
 }
 
 public static List<EmployeeDetails> readExcelSheet(String fileName){
  
  List<EmployeeDetails> list = new ArrayList<EmployeeDetails>();
  
  try{
   FileInputStream file = new FileInputStream(new File(fileName));
  
   //Creating Work Book
      HSSFWorkbook workBook = new HSSFWorkbook(file);
   
      //Read first sheet from Excel 
      HSSFSheet sheet = workBook.getSheetAt(0);
       
      //Reading sheet rows 
      Iterator<Row> rows = sheet.iterator();
      
      // Moving to next row to get employee details. Excluding headers 
      rows.next();
      
      while(rows.hasNext()) {
       int empId;
       String empName;
       String designation;
       
       Row row = rows.next();
          
          Iterator<Cell> cellIterator = row.cellIterator();

          empId = (int) cellIterator.next().getNumericCellValue();
          empName = cellIterator.next().getStringCellValue();
          designation = cellIterator.next().getStringCellValue();
          
          list.add(new EmployeeDetails(empId, empName, designation));          
      }   
  }catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
 
 public static void displayEmployeeDetails(List<EmployeeDetails> list){
  
  System.out.println("Employee ID \t Employee Name \t Designation");
  for(int i=0;i<list.size();i++){
   EmployeeDetails obj = list.get(i);
   System.out.print(obj.getEmpId()+"\t\t");
   System.out.print(obj.getEmpName()+"\t\t");
   System.out.print(obj.getDesignation()+"\n");
  }
 }
}

OUTPUT:


Employee ID   Employee Name   Designation
1  Raj  Software Engineer
2  Kamal  Technical Lead
3  Steve  Senior Software Engineer
4  David  Quality Engineer
5  John  Field Engineer

Creating excel sheet in Java


In this tutorial we see how to create excel sheet in Java using Apache POI library. By using Apache POI library we can create multiple Microsoft files like .xls, .ppt, .doc etc., Lets start this tutorial with creating excel sheet (.xls) file using POI jar. Before starting our program we need POI jar file which can downloaded from below link

POI jar file (Download latest version)


public class EmployeeDetails{
 
 private int empId;
 private String empName;
 private String designation;
 
 public EmployeeDetails(int empId, String empName, String designation){
  this.empId = empId;
  this.empName = empName;
  this.designation = designation;
 }
 
 public int getEmpId() {
  return empId;
 }
 public String getEmpName() {
  return empName;
 }
 public String getDesignation() {
  return designation;
 }
}




import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class CreateExcel {

 public static void main(String[] args) {
  
  List<EmployeeDetails> list = populateData();
  
  createExcelSheet(list, "D:\\test.xls");
 }
 
 public static List<EmployeeDetails> populateData(){
  List<EmployeeDetails> list = new ArrayList<EmployeeDetails>();
  try{
   list.add(new EmployeeDetails(1, "Raj", "Software Engineer"));
   list.add(new EmployeeDetails(2, "Kamal", "Technical Lead"));
   list.add(new EmployeeDetails(3, "Steve", "Senior Software Engineer"));
   list.add(new EmployeeDetails(4, "David", "Quality Engineer"));
   list.add(new EmployeeDetails(5, "John", "Field Engineer"));
  }catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
 
 public static void createExcelSheet(List<EmployeeDetails> list, String fileName){
  
  try {
   
   //Creating Work Book
   HSSFWorkbook workBook = new HSSFWorkbook();
   
   //Creating sheet
   HSSFSheet sheet = workBook.createSheet("Employee Details");
    
   
   Row row = sheet.createRow(0);
   Cell cell = row.createCell(0);
   cell.setCellValue("Employee Id");
   cell = row.createCell(1);
   cell.setCellValue("Employee Name");
   cell = row.createCell(2);
   cell.setCellValue("Designation");
   
   for(int i=0;i<list.size();i++){
    
    EmployeeDetails obj = list.get(i); 
    row = sheet.createRow(i+1);
    cell = row.createCell(0);
    cell.setCellValue(obj.getEmpId());
    cell = row.createCell(1);
    cell.setCellValue(obj.getEmpName());
    cell = row.createCell(2);
    cell.setCellValue(obj.getDesignation());
   }
   
      FileOutputStream fos = new FileOutputStream(new File(fileName));
      workBook.write(fos);
      fos.close();
      System.out.println("Excel sheet created successfully..");
       
  } catch (Exception e) {   
      e.printStackTrace();
  }  
 }
}


OUTPUT:


Creating excel sheet in Java