Thursday, July 8, 2021

Lambda Expression

 

 

 

 
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression.

 

A lambda expression is characterized by the following syntax.

(parameters) -> expression

 Java 8 Functional Interfaces and Lambda Expressions help us in writing smaller and cleaner code by removing a lot of boiler-plate code.

 

In general programming language, a Lambda expression (or function) is an anonymous function, i.e., a function with no name and any identifier.

 

The most important feature of Lambda Expressions is that they execute in the context of their appearance. So, a similar lambda expression can be executed differently in some other context (i.e. logic will be the same but results will be different based on different parameters passed to function).

 

Example: 

 

For example, the given lambda expression takes two parameters and returns their addition.

Based on the type of a and b, the expression will be used differently. If the parameters match to Integer the expression will add the two numbers. If the parameters of type String the expression will concat the two strings.

 

 (a, b) -> a + b    

 

One more Exmple of Lambda Expressions:

 
interface IntegerOperation {

    public String addTwoInteger(Integer a, Integer b);
} 
 
public class Example {

   public static void main(String args[]) {
        // lambda expression with multiple arguments
    	Integer s = (a, b) -> a + b;
        System.out.println("Result: " + s);
    }
}

 

 

 Important Points to be noted:

1. When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. 

 a -> return a*a.


2. If there are more than 1 statments in the body then they should be enclosed in the braces like below.


(parameters) -> { statements; }





Functional Interfaces

 

 

 

If you notice the above interface code, you will notice @FunctionalInterface annotation. Functional interfaces are a new concept introduced in Java 8. An interface with exactly one abstract method becomes a Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as a Functional Interface.

Functional interfaces are new additions in java 8 which permit exactly one abstract method inside them. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces).

@FunctionalInterface annotation is a facility to avoid the accidental addition of abstract methods in the functional interfaces. You can think of it like @Override annotation and it’s best practice to use it. java.lang.Runnable with a single abstract method run() is a great example of a functional interface.

One of the major benefits of the functional interface is the possibility to use lambda expressions to instantiate them. We can instantiate an interface with an anonymous class but the code looks bulky.

 

Runnable r = new Runnable(){
            @Override
            public void run() {
                System.out.println("My Runnable");
            }};

Since functional interfaces have only one method, lambda expressions can easily provide the method implementation. We just need to provide method arguments and business logic. For example, we can write above implementation using lambda expression as:

Runnable r1 = () -> {
            System.out.println("My Runnable");
        };

If you have single statement in method implementation, we don’t need curly braces also. For example above Interface1 anonymous class can be instantiated using lambda as follows:

Interface1 i1 = (s) -> System.out.println(s);
         
i1.method1("abc");
 

So lambda expressions are a means to create anonymous classes of functional interfaces easily. There are no runtime benefits of using lambda expressions, so I will use it cautiously because I don’t mind writing a few extra lines of code.

A new package java.util.function has been added with bunch of functional interfaces to provide target types for lambda expressions and method references. Lambda expressions are a huge topic, I will write a separate article on that in the future.

 

 

Important Points to be noted in Functional Interfaces: 

1. only one abstract method is allowed in any functional interface. Second abstract method is not not permitted in a functional interface. If we remove @FunctionInterface annotation then we are allowed to add another abstract method, but it will make the interface non-functional interface.

 2. This is valid even if we are not using @FunctionalInterface annotation. It is only for informing the compiler to enforce single abstract method inside interface.

 3. Addition of default methods to the functional interface is acceptable as long as there is only one abstract method declaration:

You can follow the below example. 
 
@FunctionalInterface public interface Foo { String method(String string); default void defaultMethod() {} }
 
4.  

Java 8 new Features

 Java 8 new Features

 

 

Oracle released a new version of Java as Java 8 in March 18, 2014.

 Java 8 provides following new features:

  • Lambda expressions,
  • Method references,
  • Functional interfaces,
  • Stream API,
  • Default methods,
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
  • ForEach() method,
  • Parallel array sorting,
  • Nashorn JavaScript Engine,
  • Parallel Array Sorting,
  • Type and Repating Annotations,
  • IO Enhancements,
  • Concurrency Enhancements,
  • JDBC Enhancements etc.

 




Wednesday, June 30, 2021

Make a Basic Spring Boot Project

 Make a Basic Spring Boot Project

  

Hello All, Today we will create a new Spring boot project from the scratch. It will be a bare minimum possible project. We will add the minimum dependency in the project.

 

We will use Intellij as an IDE.

 

First we will go to below link:

 https://start.spring.io/

 

You can fill the Group, Artifact, Name, Description of the project and packaging.

 

It is shown in the below image as well.

 

After entering the above details, you will click on 'Generate' button. It will save the project on your local system.

 



Now, import the project in Intellij IDE.

 

After importing it will be like below:




Congratulations!! you have made your first very basic and simplest possible spring boot project.

 

 

Now, we will run this project.

 

Go to follwoing path in the project:

src -> main -> java -> com -> example -> learningdemo -> LearningdemoApplication.java

 

Now, click on the run icon and click on the first option to run the main method of LearningdemoApplication class.

 

 

It is shown in follwing snap:


 

 

Now, you will see the output of the project like below;



Congratulations Again !! you have run the very basic and simplest spring boot project.






 

 

 

 

Tuesday, June 29, 2021

Transaction Isolation Levels in RDBMS

 Transaction Isolation Levels in RDBMS

 
A transaction is a single unit of operation we either execute it entirely or do not execute it at all.
 
ACID properties must be followed for a transaction operation to maintain the integrity of the database.
 
 
 
A: Atomicity
C: Consistency
I: Isolation
D: Durability
 
 
 
 
Atomicity: Either the transaction will be execute entirely or will not be executed at all.
 
 
Consistency: When the transaction has been executed then the database will move from one consistent state to another consistent state.
 
 
Isolation: Transaction should be executed in isolation of other transactions. 
So, during the current  transaction execution, intermediate transaction results of another (concurrently running) transaction should not be available to each other.
 
Two concurrent transactions should not impact the another transaction's flow/data. Even if these 2 transactions are running concurrently, but the result should be like as they would have run sequentially.
Although, we will talk about this in detail later in this article.
 
 
Durability: After successful completion of the transaction, the changes in the database should persist. Even if the application server/system gets restarted or failed.
 
 
 
 
 
- Different isolation levels describe - how changes applied by concurrent transactions are visible to each other.
- Each isolation level prevents zero or more concurrency side effects on a transaction. Ex: dirty read, nonrepeatable-read, phantom read.



1. Dirty Read: Read the uncommitted changes of a concurrent transaction.
2. Non Repeatable Read: Get different value on re-read(in a single transaction only) of a row if a concurrent transaction updates the same row and commits.
3. Phantom Read: Get different rows after re-execution of a range query if another transaction adds or removes some rows in the range and commits.





Different Transaction Isolation Levels:

There are 5 types of isolation levels:
 
 
1. READ_UNCOMMITTED: 
- This is the lowest level isolation(not supported in Postgres, Oracle)
- We can set isolation level for method or class.
- This level suffers from all the 3 above mentioned concurrency side effects.
- This level allows for most concurrent access.
 
 
 
2. READ_COMMITTED: (Default in Postgres, SQL Server, Oracle)
- This isolation level prevents dirty read. So, any uncommitted changes in concurrent transactions have no impact on us, but if a transaction commits it's changes then we can get different results when we do re-query.



3. REPEATABLE_READ: (Default in Mysql, Oracle doesn't support)
- This isolation level prevents dirty and non-repeatable reads. So,we are not affected by uncommitted changes in concurrent transactions.
- When we re-query for a row, we don't get different result but if we re-execute the range query , we might get newly added or removed rows.
- This is the minimum required isolation level to prevent the lost update. (Lost Update happens when 2 or more concurrent transactions read and update the same row.)
- This level does not allow simultaneous access to row at all. Hence lost update can't happen.



4. SERIALIZABLE:
- This is the highest level of isolation.
- This isolation level prevents all the side effects.
- In this isolation level, lowest concurrent access rate, since this level executes concurrent calls sequentially.


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Transaction Propagation Types in Spring

Transaction Propagation Types in Spring



There are 7 types of propagation types:

1. Propagation.REQUIRED

@Transactional(propagation=Propagation.REQUIRED)

- This is default propagation type.
- If there is already an active transaction, then this propagation does not do anything and uses that transaction scope only. In another case, where there is not any active transaction, then it creates new transaction.



2. Propagation.SUPPORTS

@Transactional(propagation=Propagation.SUPPORTS)
 
- If there is already an active transaction, then this propagation does not do anything and uses that transaction scope only. Otherwise, this method runs non-transactional.



3. Propagation.MANDATORY

 @Transactional(propagation=Propagation.MANDATORY)
 
- If there is already an active transaction, then this propagation does not do anything and uses that transaction scope only. Otherwise throws an IllegalTransactionStateException.



4. Propagation.NEVER

@Transactional(propagation=Propagation.NEVER)
 
 - If there is already an active transaction, then this propagation throws an IllegalTransactionStateException.
 
 
 

5. Propagation.NOT_SUPPORTED

@Transactional(propagation=Propagation.NOT_SUPPORTED)
 
 - If there is already an active transaction, then this propagation suspends that transaction and runs non-transactional.


 

6. Propagation.REQUIRES_NEW

@Transactional(propagation=Propagation.REQUIRES_NEW)
 
 - If there is already an active transaction, then this propagation suspends that transaction and creates a new transaction.
- In another case of not having any active transaction, this creates new transaction.


 

7. Propagation.NESTED

@Transactional(propagation=Propagation.NESTED)
 
 - If there is already an active transaction, then spring marks a savepoint, so if the method throws any exception then transaction gets rollback to this savepoint.
- In another case of not having any active transaction, works as Propagation.REQUIRED.
























Saturday, February 1, 2020

What is Deposit Insurance

Bank Deposit Insurance:




If a person deposits his/her money in a bank then maximum 5 lakhs money is insured according to the new budget proposal. So, if the person wants to withdraw his/her money from the bank, then he will guaranteed get minimum of (deposited money OR insured 5 lakhs amount). 

Previously this limit was of  1 lakh. 

This scheme insures all types of bank deposits including savings, fixed and recurring with an insured bank. 

The bank deposits are insured by Deposit Insurance and Credit Guarantee Corporation (DICGC), a subsidiary of the Reserve Bank of India. The agency does not directly charge any premium from bank depositors but banks pay a nominal premium for the cover.

This 5 lakhs insurance amount includes both principle and interest amount.

This insured amount is summed up for all the branches of a bank, but not for different banks. So, if we keep money in multiple banks then from each bank we will get maximum deposit insurance of 5 lakhs.


Ex:
Bank1(branch1) : deposit amount - 2 lakhs
Bank1(branch2) : deposit amount - 4 lakhs
Bank2(branch1) : deposit amount - 7 lakhs
Bank3(branch1) : deposit amount - 3 lakhs

if all the banks bank1, bank2 and bank3 are getting closed at the same time(although it is very unlikely to happen), then from bank1 we will get guaranteed 5 lakhs. same as from bank2 and from bank3 we will get 3 lakhs.

so, total we can loose 1 lakh(from bank1), 2 lakhs(from bank2) and 0 (from bank3).




If you have any doubt or need more information about the topic, please write down in the comment section, will get clarified soon.