Sunday, May 10, 2020

Design Pattern - Builder The Rescuer

Consider a situation where
- A Consuructor has too many arguments.
- We need to solve incorrect object state.
BankAccount account = new BankAccount(4456L, "Huston", "South Avenue", 100, 6);
BankAccount anotherAccount = new BankAccount(876L, "San Francisco", null, 6, 100); 

Builder comes as a savior... Here is how?

public class BankAccount {
    public static class Builder {
        private long accountNumber; //This is important, so we'll pass it to the constructor.
        private String owner;
        private String branch;
        private double balance;
        private double interestRate;
        public Builder(long accountNumber) {
            this.accountNumber = accountNumber;
        }
        public Builder withOwner(String owner){
            this.owner = owner;
            return this;  //By returning the builder each time, we can create a fluent interface.
        }
        public Builder atBranch(String branch){
            this.branch = branch;
            return this;
        }
        public Builder openingBalance(double balance){
            this.balance = balance;
            return this;
        }
        public Builder atRate(double interestRate){
            this.interestRate = interestRate;
            return this;
        }
        public BankAccount build(){
            //Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
            BankAccount account = new BankAccount();  //Since the builder is in the BankAccount class, we can invoke its private constructor.
            account.accountNumber = this.accountNumber;
            account.owner = this.owner;
            account.branch = this.branch;
            account.balance = this.balance;
            account.interestRate = this.interestRate;
            return account;
        }
    }

    private BankAccount() {
        //Constructor is now private.
    }
}
//Client
BankAccount account = new BankAccount.Builder(1234L)
            .withOwner("Marge")
            .atBranch("Springfield")
            .openingBalance(100)
            .atRate(2.5)
            .build();

Java Concurrency using Read/Write Locking

This article talks about how to achive best performance in multi-threading application.
Issue with synchronised keyword:
-  If multiple threads are accessing an object for reading data, it does not make sense to use a synchronized block or any other mutually exclusive locks.
 - Thus it offers far less level of concurrency tha non-mutually exclusive.

ReentrantReadWriteLock is an implementation of the ReadWriteLock interface .

 1. Multiple Threads can acquire multiple read Locks, but only a single Thread can acquire mutually-exclusive write Lock .Other threads requesting readLocks have to wait till the write Lock is released. A thread is allowed to degrade from write lock to read lock but not vice-versa.

 ReentrantReadWriteLock()- Creates a new ReentrantReadWriteLock with default (nonfair) ordering properties.
ReentrantReadWriteLock(boolean fair)- Creates a new ReentrantReadWriteLock with the given fairness policy.

In addition, it allows a reader/writer thread acquire a read lock/write lock multiple times recursively (reentrancy).

Fair mode in ReentrantReadWriteLock
When constructed as fair, threads contend for entry using an approximately arrival-order policy. When the currently held lock is released, either the longest-waiting single writer thread will be assigned the write lock, or if there is a group of reader threads waiting longer than all waiting writer threads, that group will be assigned the read lock.

Lock downgrading in ReentrantReadWriteLock
ReentrantReadWriteLock also allows downgrading from the write lock to a read lock. You can first acquire a write lock, then the read lock and then release the write lock. So you are effectively left with a read lock. However, upgrading from a read lock to the write lock is not possible
Condition Support (on a write Lock only)
Allowing interruption on read as well as write Locks
Sample:
  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 try {
  readWriteLock.readLock().lock();
    // multiple readers can enter this section
    // if not locked for writing, and not writers waiting
    // to lock for writing.
        }
     finally {
        readWriteLock.readLock().unlock();
   }

try {
readWriteLock.writeLock().lock();
    // only one writer can enter this section,
    // and only if no threads are currently reading.
        }
} finally {
   readWriteLock.writeLock().unlock();
}

Wednesday, May 6, 2020

Spring Batch How To Setup

This Post talks about How To Do in Spring Batch.
1. How to trigger Job with passing job paramters

@Resource
private JobLauncher sampleJobLauncher;
JobExecution execution = sampleJobLauncher.run(
<sample_Job_Object>,
new JobParametersBuilder().addString("job_param_key", "value)
.toJobParameters()
);