Java @ Desk

Java @ Desk

Breaking

Sunday, December 9, 2018

Class Level Locking In Java

5:59 AM 0
Class Level Locking In Java

Class level locking is synchronizing a block of code at a class level or static method itself so that even if multiple threads exists on same or different objects of class but only one thread can enter into the synchronized block or static synchronized method.

It means if 10 instances of a class exists in JVM then only one thread can acquire class level lock. In case of static methods, the lock is always applied on class.

Class level locking is achieved using below 2 options -
public void syncMethod() {
        synchronized (ClassLevelLockingImpl.class) {
  }
 }
}


public static synchronized void syncMethod() {}


As soon as thread entered Synchronized block, thread acquired class object. Thread will leave lock when it exits synchronized block and only after this another waiting thread may enter the block.

Here is the implementation of Class level lock

ClassLevelLockingClient.java - In this implementation, 2 objects are created of Thread class that has class level lock implementation and both threads are started at the same time. Since the lock is applied on a lock, only 1 thread enters into the synchronized block and other enters in wait state
package com.learning.objectclasslocking;

public class ClassLevelLockingClient {

    public static void main(String args[]) {
        int count = 0;
        ClassLevelLockingImpl objectLevelLockingOne = new ClassLevelLockingImpl();
        objectLevelLockingOne.setTime(4000);
        objectLevelLockingOne.setCount(++count);
        new Thread(objectLevelLockingOne).start();

        ClassLevelLockingImpl objectLevelLockingTwo = new ClassLevelLockingImpl();
        objectLevelLockingTwo.setTime(1000);
        objectLevelLockingTwo.setCount(++count);
        new Thread(objectLevelLockingTwo).start();

        System.out.println("Client ends");
    }
}


ClassLevelLockingImpl.java - This is a thread class that has implemented Class level lock
package com.learning.objectclasslocking;

public class ClassLevelLockingImpl implements Runnable {

    public void syncMethod() {
        synchronized (ClassLevelLockingImpl.class) {
            System.out.println("Sync Method Starts " + count);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Sync Method Ends " + count);
        }
    }

    public void run() {
        this.syncMethod();
    }

    private int count;

    private int time;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}


Output -
Client ends
Sync Method Starts 1
Sync Method Ends 1
Sync Method Starts 2
Sync Method Ends 2

Object Level Locking In Java

5:07 AM 0
Object Level Locking In Java

Object level locking is synchronizing a block of code or whole method itself so that -
1) Different Threads on Different Instance of Object - Threads on different objects may enter the synchronized block of code at the same time. This means multiple objects of same class that exists in memory has their own individual lock.

2) Different Threads Same Instance of Object - Multiple threads on same object may exists in memory but only one thread on that object instance can enter synchronized block at a time. All other threads will be in wait state.

There are two flavors of Object lock
public void syncMethod() {
        synchronized (this) {
  }
 }


public synchronized void syncMethod() { }


Here is the implementation of Case 1 - Different Threads on Different Instance of Object

ObjectLevelLockingImpl.java - Thread Class
package com.learning.objectclasslocking;

public class ObjectLevelLockingImpl implements Runnable {

    public void syncMethod() {
        synchronized (this) {
            System.out.println("Sync Method Starts " + count);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Sync Method Ends " + count);
        }
    }

    public void run() {
        this.syncMethod();
    }

    private int count;

    private int time;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}


ThreadsOnDifferentObjectLocking.java - This implementation is for Different Threads on Different Instance of Object - Threads on different objects may enter the synchronized block of code at the same time. This means multiple objects of same class that exists in memory has their own individual lock. In this class, 2 objects of class ObjectLevelLockingImpl are created and 2 threads are started at the same time. Observe the output, both the threads are able to enter the synchronized method at the same time.
package com.learning.objectclasslocking;

public class ThreadsOnDifferentObjectLocking {

    public static void main(String args[]) {
        int count = 0;
        ObjectLevelLockingImpl objectLevelLockingOne = new ObjectLevelLockingImpl();
        objectLevelLockingOne.setTime(4000);
        objectLevelLockingOne.setCount(++count);
        new Thread(objectLevelLockingOne).start();

        System.out.println("First Thread Started");

        ObjectLevelLockingImpl objectLevelLockingTwo = new ObjectLevelLockingImpl();
        objectLevelLockingTwo.setTime(1000);
        objectLevelLockingTwo.setCount(++count);
        new Thread(objectLevelLockingTwo).start();

        System.out.println("Second Thread Started");
        System.out.println("Client ends");
    }
}


Output -
First Thread Started
Second Thread Started
Client ends
Sync Method Starts 1
Sync Method Starts 2
Sync Method Ends 2
Sync Method Ends 1


ThreadsOnSameObjectLocking.java - Different Threads Same Instance of Object - Multiple threads on same object may exists in memory but only one thread on that object instance can enter synchronized block at a time. All other threads will be in wait state.
package com.learning.objectclasslocking;

public class ThreadsOnSameObjectLocking {

    public static void main(String args[]) {
        int count = 0;
        ObjectLevelLockingImpl objectLevelLockingOne = new ObjectLevelLockingImpl();
        objectLevelLockingOne.setTime(4000);
        objectLevelLockingOne.setCount(++count);

        Thread threadOne = new Thread(objectLevelLockingOne);
        threadOne.setName("Thread One");

        Thread threadTwo = new Thread(objectLevelLockingOne);
        threadTwo.setName("Thread Two");

        threadOne.start();
        threadTwo.start();
        System.out.println("Main Ends");
    }
}


Output -
Main Ends
Sync Method Starts 1
Sync Method Ends 1
Sync Method Starts 1
Sync Method Ends 1

Java Lock - java.util.concurrent.locks.Lock Real Time Example

2:01 AM 0
Java Lock Real Time Example

Lock in Java has been introduced in JDK 1.5 to enable synchronize mechanism. They are similar to synchronized blocks with additional features. Lock is an interface in Java and there are different implementations of Lock

1) ReentrantLock - It applies lock to a block of code in a method or block of code in different methods too. Unlike synchronized block that is applied to a whole method or a block of code within a method, Locks can be applied to blocks of code within 1 method or more than 1 method. Lock applied in one method can be unlocked in another method too.
2) ReentrantReadWriteLock - This implementation is used to perform locking when there are multiple readers and writers on a single source.

Lock interface has below important methods
1) lock() - This method acquires a lock on a resource. If a lock is not available then a thread waits indefinitely until the block is released.
2) unlock() - This method unlock the locked instance and allow another threads in waiting state to acquire a lock.

Good practice is to call unlock() method always in a finally block, otherwise in case of an exception after lock() method execution, it will remain in an infinite lock and cause deadlock situation.

Here is a sample implementation of the Lock Interface
LockThread.java - This is a thread which locks and unlocks the Lock instance created by client class. This implementation waits for infinite since it is using the lock() method. In the next implementation we will see lock implementation with time out.
package com.learning.locks;

import java.util.concurrent.locks.Lock;

public class LockThread implements Runnable {

    private Lock lock;

    private int count;

    private int time;

    public void run() {
        lock.lock();
        System.out.println("Thread " + this.count + " got locked");
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("Thread " + this.count + " got unlocked");
    }

    public Lock getLock() {
        return lock;
    }

    public void setLock(Lock lock) {
        this.lock = lock;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}


LockClient.java - 3 Threads are created that takes different times to complete processing. The thread that acquires a lock is on random basis.
package com.learning.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockClient {

    public static void main(String args[]) {
        Lock lock = new ReentrantLock();
        int lockCount = 0;

        LockThread lockThreadOne = new LockThread();
        lockThreadOne.setLock(lock);
        lockThreadOne.setCount(++lockCount);
        lockThreadOne.setTime(10000);

        LockThread lockThreadTwo = new LockThread();
        lockThreadTwo.setLock(lock);
        lockThreadTwo.setCount(++lockCount);
        lockThreadTwo.setTime(4000);

        LockThread lockThreadThree = new LockThread();
        lockThreadThree.setLock(lock);
        lockThreadThree.setCount(++lockCount);
        lockThreadThree.setTime(1000);

        new Thread(lockThreadTwo).start();
        new Thread(lockThreadOne).start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(lockThreadThree).start();
        System.out.println("All the locks initialized");

    }
}


Output -
Thread 2 got locked
All the locks initialized
Thread 1 got locked
Thread 2 got unlocked
Thread 1 got unlocked
Thread 3 got locked
Thread 3 got unlocked

Saturday, December 8, 2018

Java concurrency – CountDownLatch Real Time Example

8:27 AM 0
Java concurrency – CountDownLatch Example

CountDownLatch is the class introduced in Concurrency API in JDK 1.5. CountDownLatch allows the application to wait for the rest of the threads to get over. In a scenario, it is required a single primary thread to wait until all the thread finishes its processing. To achieve this, CountDownLatch is used.

CountDownLatch is initialized with an integer value. This integet value suggests, for how many count down it needs to wait. Every time a thread calls "countDown()" method, the initialized count reduces by 1. The moment count reaches 0, main thread resumes further.

Different Scenarios -
1) If CountDownLatch is initialized with 0, and "countDown()" is called 3 times in different or same threads - Client does not wait since the count itself is 0 during initialization.
2) If CountDownLatch is initialized with 1, and "countDown()" is called 3 times in different or same threads - Client will move forward as soon as 1st "countDown()" is called.
3) If CountDownLatch is initialized with 3, and "countDown()" is called 3 times in different or same threads - Client will move forward only after 3rd "countDown()" is called.

Real Time Scenario -
Consider a Bank that works from morning 9 AM to 3 PM. Bank will be closed only when it serves all the clients that has entered before 3 PM. Bank will remain open unless all customers leave the premises.

In this case, Bank is a CountDownLatch Main Client on which "await()" method is applied and Customers are the ones who performs "countDown()" on the latch.

Here is a realtime example of CountDownLatch
CountDownLatchClient.java - It creates the CountDownLatch object with count 2 and enters in await() state for threads to call "countDown()" atleast twice. 2 threads will be created and CountDownLatchClient will wait for them to finish processing.
package com.learning.countdownlotch;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchClient {

    public static void main(String args[]) {

        final CountDownLatch latch = new CountDownLatch(2);

        CountDownThread countDownThreadOne = new CountDownThread();
        countDownThreadOne.setLatch(latch);
        countDownThreadOne.setCount(1);
        countDownThreadOne.setTime(1000);

        new Thread(countDownThreadOne).start();

        CountDownThread countDownThreadTwo = new CountDownThread();
        countDownThreadTwo.setLatch(latch);
        countDownThreadTwo.setCount(2);
        countDownThreadTwo.setTime(3000);

        new Thread(countDownThreadTwo).start();

        try {
            latch.await();
            System.out.println("Main Ends");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


CountDownThread.java - This is a thread class which calls the "countDown()" on the CountDownLatch Object
package com.learning.countdownlotch;

import java.util.concurrent.CountDownLatch;

public class CountDownThread implements Runnable {
    private CountDownLatch latch;

    private int count;

    private int time;

    public void run() {

        try {
            System.out.println("CountDownThread Starts " + getCount());
            Thread.sleep(time);
            System.out.println("CountDownThread Ends " + getCount());
            latch.countDown(); //reduce count of CountDownLatch by 1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public CountDownLatch getLatch() {
        return latch;
    }

    public void setLatch(CountDownLatch latch) {
        this.latch = latch;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}


Output -
CountDownThread Starts 1
CountDownThread Starts 2
CountDownThread Ends 1
CountDownThread Ends 2
Main Ends

Saturday, September 15, 2018

Node JS Sort npm custom ArrayList using compare method

10:16 PM 0
Node JS Sort npm custom ArrayList using compare method

Arraylist is the collection in Node JS that stores the collection of objects. In below example we have a custom collection of ArrayList objects with two properties:
1) Name
2) Age

We will implement both the sort operations, one based on age and second based on name in ascending order. A simple collection of integer or string can be sorted using the sort() method. But in case of custom objects, we need to implement the compare function that defines the sorted algorithm.

We have implemented 2 different sort methods:
1) sortListByAge
2) sortListByName

First method implements the sort compare based on Age property and second implements based on Name. Here is the complete implementation.

/*jshint esversion: 6 */ 
var DELAY = 1000;
var ArrayList = require('arraylist');

var list = new ArrayList();
list.add([{ name: 'Edward', age: 21 },
   { name: 'Sharpe', age: 37 },
   { name: 'And', age: 45 },
   { name: 'The', age: -12 },
   { name: 'Magnetic', age: 13 },
   { name: 'Zeros', age: 37 }]);

module.exports = {
 sortListByAge() {
     return new Promise((resolve) => {
       setTimeout(() => {
        list.sort(function (a, b) {
         return a.age - b.age;
       });
      console.log("Sorted List By Age : " + list); 
         resolve(list);
       }, DELAY);
     });
   },
   sortListByName() {
      return new Promise((resolve) => {
        setTimeout(() => {
         list.sort(function(a, b) {
          var nameA = a.name.toUpperCase();
          var nameB = b.name.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        console.log("Sorted List By Name : " + list); 
          resolve(list);
        }, DELAY);
      });
    },
};


When we run above service, below output is generated
1) sortListByAge - [{"name":"The","age":-12},{"name":"Magnetic","age":13},{"name":"Edward","age":21},{"name":"Sharpe","age":37},{"name":"Zeros","age":37},{"name":"And","age":45}]
2) sortListByName - [{"name":"And","age":45},{"name":"Edward","age":21},{"name":"Magnetic","age":13},{"name":"Sharpe","age":37},{"name":"The","age":-12},{"name":"Zeros","age":37}]

Sunday, July 22, 2018

Drools Decision Table Set List To Pojo

6:56 AM 0
Drools Decision Table Set List To Pojo

In this post, we will learn how to set a list of values into a pojo field in Decision Table in the ACTION part. The values are set into the list field using the comma seperated values of Strings.

Consider a pojo class Person with following properties

1) age - Number
2) applyingFor - Pan/Adhaar/Passport(String)
3) documentsList - java.util.List - Documents required for application of Pan Card or Adhaar Card or Passport. It will be a String values seperated by comma

Following are the rules that are applied

1) If age > 18 and applyingFor = 'Pan Card', then documentsList = 'Birth Certificate', 'Photo'
2) If age > 18 and applyingFor = 'Adhaar Card', then documentsList = 'Birth Certificate', 'Pan Card', 'Light Bill', 'Photo'
3) If age > 18 and applyingFor = 'Pan Card', then documentsList = 'Adhaar Card', 'Pan Card', 'Photo'

This will be configured into a decision table as shown below


As shown, list is set using - $documentCheck.setDocumentList(Arrays.asList($param));

Thursday, March 29, 2018

Find Maximum LocalDateTime From ArrayList In Java 8

11:43 PM 0
Maximum date can be fetched from the List using the Collections interface.

Collections interface provide the methods to find the maximum value out of a collection of dates.

In this case we will pass ArrayList of LocalDateTime object that contains the dates.

Below is a sample implementation that retrieves the maximum date from a ArrayList -

package com.learning;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FindMaxLocalDateTimeArrayList {

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

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  LocalDate ld = LocalDate.parse("2018-03-22T18:02:32.000Z", formatter);
  LocalDateTime ldt = LocalDateTime.of(ld, LocalDateTime.now().toLocalTime());

  List<LocalDateTime> localDateTimes = new ArrayList<>();
  localDateTimes.add(ldt);
  localDateTimes.add(LocalDateTime.of(LocalDate.parse("2018-03-25T18:02:32.000Z", formatter),
    LocalDateTime.now().toLocalTime()));
  localDateTimes.add(LocalDateTime.of(LocalDate.parse("2018-03-16T18:02:32.000Z", formatter),
    LocalDateTime.now().toLocalTime()));

  System.out.println(Collections.max(localDateTimes));
 }
}

Wednesday, March 28, 2018

Implement And Or Conditions in Drools Decision Table

3:02 AM 0
Implement And Or Conditions in Drools Decision Table

Drools rules can be defined in various formats one of which is in Decision Tables. Decision Tables rules are configured in an excel sheet in .xls format.

Decision Table is primarily used when there are rules that need to be configured for similar properties. For example, there is a rule implementation on age property of a user. Below are the examples:
If age > 18 && age < 22 then Do X
If age > 22 && age < 28 then Do Y
If age > 28 && age < 32 then Do Z
If age > 32 && age < 36 then Do A
If age > 36 && age < 48 then Do B
If age > 48 && age < 56 then Do C

If such rules are implemented in DRL files, then there will be lot of redundant code. Instead the same are configured in a decision table.

There are different components of a Decision table as mentioned below. The structure is similar to DRL file itself
1) Ruleset - Its similar to package from DRL file.
2) Import - To import comma separated Java packages that are used in rules.
3) Sequential - If set to true, rules will be fired in sequence from top to bottom.
4) Variables - One of more Global variables.
5) Functions - Functions used if any in rules.
6) Queries - Queries used if any in rules.

Rules configuration consists of below :
1) Rule Name
2) Description
3) CONDITION
4) ACTION

By default, there is a AND condition between the CONDITION columns in between the table. AND condition can also be implemented using conditions with comma seperated as shown below. OR condition is implemented using || between the conditions as shown in below screenshot Here is the snapshot of Decision Table that is used in the example.









User.java - Pojo used for rules
package com.pojo;

public class User {

 private String name;

 private String address;

 private Integer age;

 private boolean adult;

 private Integer rateOfInterest;
 
 private String bankAccounts;
 
 public String getBankAccounts() {
  return bankAccounts;
 }

 public void setBankAccounts(String bankAccounts) {
  this.bankAccounts = bankAccounts;
 }

 @Override
 public String toString() {
  return "Name - " + this.name + "\nAddress -" + this.address + "\nAge" + this.age + "\nAdult - " + this.adult
    + "\nRate Of Interest - " + this.rateOfInterest;
 }

 public Integer getRateOfInterest() {
  return rateOfInterest;
 }

 public void setRateOfInterest(Integer rateOfInterest) {
  this.rateOfInterest = rateOfInterest;
 }

 public Integer getAge() {
  return age;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public boolean isAdult() {
  return adult;
 }

 public void setAdult(boolean adult) {
  this.adult = adult;
 }
}


Client File
package com.drools;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import com.pojo.User;

public class DecisionTableClient {

 public static final void main(final String[] args) throws InterruptedException {
  KieSession kieSession = new DecisionTableClient().execute();

  User user = new User();
  user.setName("Andy");
  user.setAge(62);
  user.setAddress("Japan");
  user.setBankAccounts("Axis");
  kieSession.insert(user);
  kieSession.fireAllRules();
  System.out.println("\n");
  System.out.println(
    "User Object After Firing Rules - \n"
      + user.toString());
  kieSession.dispose();
 }

 public KieSession execute() {
  KieServices ks = KieServices.Factory.get();
  KieContainer kc = ks.getKieClasspathContainer();
  KieSession kieSession = kc.newKieSession("DecisionTableKIESession");
  return kieSession;
 }

}