Thursday, April 2, 2020

CyclicBarrier : Java Concurrency

CyclicBarrier 


How many of you are aware about CyclicBarrier ? Almost all Java developers. Am i right ? When my boss asked me the same, i was thinking is it related to any cycle path of national highway. Oh, later on i found that it is a concept if Java Concurrency.In this article, we will dig it more.


Introduction

It is a synchronization aid(Synchronizers) that allows a set of threads to all wait for each other to reach a common barrier point. 

CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

It is a part of the java.util.concurrent package which almost contains more than 57 numbers of classes.

CyclicBarrier is similar to CountDownLatch in Java(of course there are some differences) and allows multiple threads to wait for each other (barrier) before proceeding.




CyclicBarrier Usage

The CyclicBarrier supports a barrier action, which is a Runnable that is executed once the last thread arrives. 

There are two types of constructor available. 

public CyclicBarrier(int parties)

Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped.

Optionally, we can pass the second argument to the constructor, which is a Runnable instance. This has logic that would be run by the last thread that trips the barrier:

public CyclicBarrier(int parties, Runnable barrierAction

Example :


CyclicBarrier: Consider the same IT world scenario where manager divided modules between development teams (A and B). He goes on leave and asked both team to wait for each other to complete their respective task once both are done assign it to QA team for testing.
Here manager thread works as main thread and development team works as worker thread. Development team threads wait for other development team threads after completing their task.

Implementation

Let's consider the following scenario. 
Suppose we have two different services performs some operations and store the corresponding results in a list which should wait for each other to complete the execution. When both the services finish performing their action, the main thread starts procession the data and gives the sum of all numbers. 
public class CyclicBarrierDemo {
private CyclicBarrier cyclicBarrier;
    private List<List<Integer>> partialResults= Collections.synchronizedList(new ArrayList<>());
    private Random random = new Random();
    
    public void runSimulation() {
        cyclicBarrier = new CyclicBarrier(2, new AggregatorThread());
        Thread worker = new Thread(new ServiceOneThread());
        worker.start();
        
        Thread worker2 = new Thread(new ServiceTwoThread());
        worker2.start();
    }
    public static void main(String[] args) {
    CyclicBarrierDemo demo = new CyclicBarrierDemo();
        demo.runSimulation();
    }
    
    
    
    class AggregatorThread implements Runnable {
     
        @Override
        public void run() {
            String thisThreadName = Thread.currentThread().getName();
            System.out.println(thisThreadName + ": Computing sum of 2 service" );
            int sum = 0;
            System.out.println(partialResults);
            for (List<Integer> threadResult : partialResults) {
                System.out.print("Adding ");
                for (Integer partialResult : threadResult) {
                    System.out.print(partialResult+" ");
                    sum += partialResult;
                }
                System.out.println();
            }
            System.out.println(thisThreadName + ": Final result = " + sum);
        }
    }
    
    class ServiceOneThread implements Runnable{
    @Override
    public void run() {
    
    System.out.println("Service-1 run method");
    List<Integer> partialResult = new ArrayList<>();
    for (int i = 0; i < 10; i++) {    
    Integer num = random.nextInt(10);
    partialResult.add(num);
    }
    System.out.println("Service-1 partial results :" + partialResult);
    partialResults.add(partialResult);
    try {
    System.out.println("Service-1 is moving to sleeping state...");
    Thread.sleep(100000);
    System.out.println("Service-1 is comes up from sleeping state...");
    System.out.println("Service-1  waiting for others to reach barrier.");
    cyclicBarrier.await();
    
    } catch (InterruptedException e) {
    } catch (BrokenBarrierException e) {
    }
    }
    }
    
    
    class ServiceTwoThread implements Runnable{
    @Override
    public void run() {
    System.out.println("Service-2 run method");
    List<Integer> partialResult = new ArrayList<>();
    for (int i = 0; i < 10; i++) {    
    Integer num = random.nextInt(5);
    partialResult.add(num);
    }
    partialResults.add(partialResult);
    try {
    System.out.println("Service-2 numbers :" + partialResult);
    System.out.println("Service-2  waiting for others to reach barrier.");
    cyclicBarrier.await();
    } catch (InterruptedException e) {
    } catch (BrokenBarrierException e) {
    }
    }
    }
    
}



Output :
Service-1 run method
Service-1 partial results :[8, 0, 8, 3, 9, 2, 6, 1, 4, 2]
Service-1 is moving to sleeping state...   //see here, service-1 moved to sleep
Service-2 run method
Service-2 numbers :[2, 0, 0, 2, 3, 0, 0, 4, 2, 2]
Service-2  waiting for others to reach barrier.
Service-1 is comes up from sleeping state...
Service-1  waiting for others to reach barrier.
Thread-0: Computing sum of 2 service //main thread
[[8, 0, 8, 3, 9, 2, 6, 1, 4, 2], [2, 0, 0, 2, 3, 0, 0, 4, 2, 2]]
Adding 8 0 8 3 9 2 6 1 4 2 
Adding 2 0 0 2 3 0 0 4 2 2 
Thread-0: Final result = 58

Monday, December 16, 2019

Do you know Precision and Scale of a Number ?




You might be thinking what is this stupidity blog, I know it. 
Can you please fill the blank in this table :


Number
Precision
Scale
0.0
?
?
567.234
?
?
-56.3457
6
?
50
?
0


Ok, it is for those who know it but forget.


I was not clear about the Precision and Scale of a Number perfectly !!!
My boss looked at me surprisingly and asked me, is It? Honestly, I told yes.
Then instead of explaining to me, he told me to read it again and explain to him.
I did a wrong explanation knowingly and he agreed. i.e. he has also forgotten the same !!!


So are you with me too? This blog will help to refresh the bean which we have eaten during
our schooling !!!


 What is precision?

Precision refers to the amount of information that is conveyed by a number in terms of its digits.
i.e Precision is the total number of significant digits in a number.


What is Scale?

 - Scale is the number of digits to the right of the decimal point.


So now the above table will be like :


Number
Precision
Scale
0.0
1
1
567.234
6
3
-56.3457
6
4
50
2
0

Where is it Used?
It is used in most of the calculations even in Database too. As a Java developer,
if you are performing any operations using BigDecimal,
you might have seen the use cases such as MathContext  & add method of BigDecimal.


In the MySql database, Decimals can be added by using the DECIMAL(M, D) data type. This requires 2 arguments.
  • M is the maximum number of digits, ranging from 1 to 65.
  • D is the number of decimal places available, ranging from 0 to 30.
Note that with D digits reserved for decimal places, there can be at most M-D digits available for the integer part. So if we use DECIMAL(6,4), the number 45.8239 would be valid, but 456.12 would not.

Wednesday, November 27, 2019

Monetary calculations in Java Using float or double !!!

Monetary calculations in Java :

Money plays an important factor in life and a Software engineer has to deal with money calculations like monetary arithmetic a lot during software development. If it is an e-commerce or banking application, then most of the calculations are on money only. But sometimes 0.01 value also makes the whole monetary arithmetic wrong.  That time we trigger our mind button and keeps on debugging, calculations manually bla bla bla !!! But in the end we sometimes weren't able to find the solutions; but actually, the solutions are dancing in-front, but we are not able to catch it.

When you deal with “money” value, always a question arises – Should I use double or float datatype to represent the monetary values?
Answer: Neither double nor float. Oh, boss!!!!! Why and what should I use ??

Why not double/float :

Let's take an example :

double amount1 =2.15;
double amount2 =1.10;
while( (amount1-amount2) !=1.05){
   System.out.println("Oh!!! Stil not true... I am getting stuck infinite lopp...but why...");
}

Output:
Infinite loop. . . .......................
............................

This code will result in an infinite loop because the result of subtraction of amount1 and amount 2 will not be 1.5 instead it would be "1.xxxxxxxxxxxxx" which make boolean condition always true.

System.out.println(2.00-1.1); // check the o/p

System.out.println(42/85); //check the o/p


Solution :

This is one of the common mistakes Java programmers make until they are familiar with BigDecimal class. We can avoid the above mistakes by using BigDecimal class as follows :


BigDecimal amount1 =new BigDecimal("2.15");
BigDecimal amount2 =new BigDecimal("1.10");
while( ! new BigDecimal((amount1.subtract(amount2).equals(new BigDecimal("1.05"))))
   System.out.println("Oh!!!  I am safe now. . .);
}

Output:
The difference of two amount is 1.05 and as the condition evaluates to false, no o/p will come.

Using Incorrect BigDecimal constructor

Another mistake Java Programmers make is using the wrong constructor of BigDecmialBigDecimal has an overloaded constructor and if you use the one which accepts double as an argument you will get the same result as you do while operating with double. So always use BigDecimal with String constructor. here is an example of using BigDecmial constructed with double values:

//Creating BigDecimal from double values
BigDecimal amount3 = new BigDecimal(2.15);
BigDecimal amount4 = new BigDecimal(1.10) ;
System.out.println("difference between 2.15 and 1.0 using BigDecmial is: " + (amount3.subtract(amount4)));

Output:
difference between 2.15 and 1.0 using double is: 1.0499999999999998
difference between 2.15 and 1.0 using BigDecmial is: 1.049999999999999822364316059974953532218933105468750

Conclusion :

  • Don’t use float and double on monetary calculation.
  • Use BigDecimal, long or int for monetary calculation.
  • Use BigDecimal with String constructor and avoid double one.
  • Use Money API (JSR-354

Note :

The performance of BigDecimal operations is slower than the performance of primitive types such as double, float .