Monday, 10 June 2019

Object level and Class level locks in Java with example

        This question is also important for experienced java developers to know about type of locks in multithreading.         
        As we know that java supports multiple threads to be executed concurrently. If  two or more threads accessing the same resource at a time then conflict/inconsistent will occur. To avoid this inconsistency we are following synchronization concept i.e at a time one thread can access resource and wait for another thread to access. Using synchronized keyword to achieve the synchronization.  The synchronized keyword can be used as method level or block level.

   There are two types of locking in java in threading,

  • Object level lock
  • Class level lock

Object level lock:-

         Object level locking is about synchronizing a non-static method or non-static code block such that only one thread will execute the code block on given instance of the class. Object level locking make instance level data thread safe.

There are different ways we can lock the object in thread as below,

public class ThreadClassEx {
      
       public synchronized void syncMethod(){
             //method implementation here
       }
}

public class ThreadClassEx {
      
       public void syncMethod(){
           
              synchronized(this) {
                  //block implementation here
              }
       }
}

public class ThreadClassEx {
      
         private final Object lock = new Object();

         public void syncMethod(){
           
                   synchronized(lock) {
                           //block implementation here
                   }
          }
}


Class level lock:-

         Class level locking is about a synchronizing a static method or block so that it can be accessed by only one thread for whole class. If you have 100 instances of class, only one thread will be able to access only one method or block of any one instance at a time.

        This should always be done to make static data thread safe.

Various ways of class level locking is as follows,

public class ThreadClassEx {

      public synchronized static void syncMethod(){
               //method implementation here
      }
}

public class ThreadClassEx {

      public void syncMethod(){
         
            synchronized(ThreadClassEx.class) {
               //block implementation here
            }
      }
}

public class ThreadClassEx {

      private final static Object lock = new Object();

      public void syncMethod(){
         
            synchronized(lock) {
               //block implementation here
            }
      }
}

Thank you for visiting blog.


Related Posts:-
1) Producer Consumer Problem - Solution using wait and notify In Java
2) Thread join() method example in Java
3) Difference between the Runnable and Callable interface in Java
4) Explain Thread life cycle and difference between wait() and sleep() method.
5) How many ways to create a thread in Java? Which one Prefer and why?
6) Producer Consumer Problem - Solution using BlockingQueue in Java

Wednesday, 5 June 2019

How to Create Custom Immutable Class with mutable object references in Java?

       We discussed in previous post about How to create the Immutable object in Java.  We discussed the all steps or rules we need to follow while creating immutable class in java. But if any field in the custom immutable class contains reference to any other mutable class then it will break immutable behavior. The reference class can be from imported jar files or any other imported application class and we can not access/control that mutable class. In this post, we will discuss how to make/convert mutable reference to immutable so that the complete class will become immutable.

      In the below example, Employee class is immutable but filed Address is mutable, it's another java class . 

Employee.java,
package com.practice;

public final class Employee {
 
        private final String empName;
        private final int age;
        private final Address address;
 
        public Employee(String name, int age, Address address) {
                super();
                this.empName = name;
                this.age = age;
                this.address = address;
        }

        public String getEmpName() {
                return empName;
        }

        public int getAge() {
                return age;
        }

         public Address getAddress() {
                return address;
         }

}

        In the above code, empName and age fields are immutable, we can not change the value but Address field it's reference of another java class and we can not have access or to modify the Address class.Here Address field is mutable, so we can restrict to modify the Address object/field in Employee class.

Address.java,
package com.practice;

public class Address implements Cloneable{
 
         public String addressType;
         public String address;
         public String city;
 
         public Address(String addressType, String address, String city) {
                   super();
                   this.addressType = addressType;
                   this.address = address;
                   this.city = city;
         }
         public String getAddressType() {
                   return addressType;
         }
         public void setAddressType(String addressType) {
                   this.addressType = addressType;
         }
         public String getAddress() {
                   return address;
         }
         public void setAddress(String address) {
                    this.address = address;
         }
         public String getCity() {
                    return city;
         }
         public void setCity(String city) {
                    this.city = city;
         }

         public Object clone() throws CloneNotSupportedException {  
                  return super.clone();  
         }

        @Override
        public String toString() {
                 return "Address Type - "+addressType+", address - "+address+", city - "+city;
        }
}

         In the below main class, you can create the Employee object using constructor, pass all parameters i.e empName, age and address. In the next line again we can set the addressType, address and city into the Address object. Now you try to access the address field from employee object it will get change. So in this case it will break the immutable behavior.

MainClass.java,
package com.practice;

public class MainClass {
 
         public static void main(String[] args) {
  
                   Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));
  
                   Address address = emp.getAddress();
  
                   System.out.println(address);
  
                   address.setAddress("Jayanagar");
                   address.setAddressType("Office");
                   address.setCity("Sangli");
  
                   System.out.println(emp.getAddress());  
         }

}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Office, address - Jayanagar, city - Sangli


Solution : -

The best solution is to modify the getAddress method in employee class, and instead of returning original Address object, we will return deep cloned copy of that instance. But one condition Address class must implements cloneable interface.

Modified employee class is as follow,

Employee.java,
package com.practice;

public final class Employee {
 
         private final String empName;
         private final int age;
         private final Address address;
 
         public Employee(String name, int age, Address address) {
                  super();
                  this.empName = name;
                  this.age = age;
                  this.address = address;
         }

         public String getEmpName() {
                  return empName;
         }

         public int getAge() {
                  return age;
         }

         public Address getAddress() throws CloneNotSupportedException {
                  return (Address) address.clone();
         }

}

Now we can check to execute main class,

MainClass.java,
package com.practice;

public class MainClass {
 
         public static void main(String[] args) {
  
                   Employee emp = new Employee("Mahesh", 34, new Address("Home", "JP Nagar", "Bangalore"));
  
                   Address address = emp.getAddress();
  
                   System.out.println(address);
  
                   address.setAddress("Jayanagar");
                   address.setAddressType("Office");
                   address.setCity("Sangli");
  
                   System.out.println(emp.getAddress());  
         }

}

Output:-
Address Type - Home, address - JP Nagar, city - Bangalore
Address Type - Home, address - JP Nagar, city - Bangalore


Related Posts:-
1) String Interview Questions and Answers
2) Why String is immutable or final in java?
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Builder Design Pattern in Java
5) What is call by value and call by reference in Java ?

Thursday, 30 May 2019

Java program to find second largest number in an array

       This is familiar interview question for the middle level developers. Interviewer will check the coding logic of the candidate and best solution(performance level).

       In this question, there are two solutions to find the second largest number in the given array.

1) Using Sort - This is simple one, you have to sort the array in descending order and return the second element from the sorted array. Time complexity of this approach is O(nlogn)

2) Single Loop using Traversal :- Use single for loop,Inside for loop find the largest number and second condition to find the second largest number using first largest number.
Time complexity of this approach is O(n). This is the better solution compared to first one.

Let's see the below example to find the second largest number in an array,

SecondLargestNumber.java,

package com.test;

public class SecondLargestNumber {
 
         public static void main(String[] args) {
  
                  int[] arr = {2, 3, 4, 10, 28, 38, 88, 10};
  
                  int firstLargeNum = 0;

                  int secondLargeNum = 0;

                  for (int i = 0; i<arr.length; i++) {

                         if (arr[i] > firstLargeNum) {

                                  secondLargeNum = firstLargeNum;

                                  firstLargeNum = arr[i];

                         } else if(arr[i] > secondLargeNum && arr[i] != firstLargeNum) {

                                  secondLargeNum = arr[i];

                         }
                  }

                  System.out.println("Second Largest Number is - "+secondLargeNum);
          }

}

Output:-
Second Largest Number is - 38.


Related Posts:--
1) Java Code to Print the Numbers as Pyramid - Examples
2) Java Program to find the Missing Number in an Array
3) Java program to print the first n prime numbers
4)  Java Program to check the given number is a palindrome or not
5) Write a Java program to print the Floyd's triangle

Saturday, 25 May 2019

What is call by value and call by reference in Java ?

     This also one of the important question for experienced Java developers. In this post, we need understand what is call by value(pass by value) and call by reference .  

     Call by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments of the method are always passed by value. 

     With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.

Read Top Java Blogs - Feedspot Top 40 Java Blogs

Is Java call by value or call by reference ?

    Java doesn't pass method arguments by reference; it passes them by value. So Java uses or supports call by value.

     In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in the call by reference, the modification done to the parameter passed are persistent and changes are reflected in the caller's scope. The below example explains the call by value and call by reference with output.


Call by value example:-

   The following code shows an example of call by value. The values of the arguments will remain the same even after the method invocation.

PassByValueExample.java,

package com.test;

public class PassByValueExample {
 
       public static void main(String[] args) {
             int x = 10;
             System.out.println("Value of x before calling method changeValue() - " +x);
             changeValue(x);
             System.out.println("Value of x after calling method changeValue() - " +x);
       }

       public static void changeValue(int x) {
              x = 12;
              System.out.println("Value of x inside method - "+x);
       }
}

Output:-
Value of x before calling method changeValue() - 10
Value of x inside method - 12
Value of x after calling method changeValue() - 10

In the above output, the value of x after invoking the method, will remain same, it doesn't impact on original value.


Call by reference example:-

    The following code is the example of call by reference where List reference passed as an argument of  method. The elements of list will get change when we modify the element in the calling method.

PassByReferenceExample.java

package com.test;

import java.util.ArrayList;
import java.util.List;

public class PassByReferenceExample {

       public static void main(String[] args) {
               List<String> list = new ArrayList<String>();
               list.add("A");
               System.out.println("List before calling method - "+list);
               addElement(list);
               System.out.println("List after calling method - "+list);
       }

       public static void addElement(List<String> list) {
               list.add("B");
               System.out.println("List elements inside method - "+list);
       }
}

Output:-
List before calling method - [A]
List elements inside method - [A, B]
List after calling method - [A, B]


Related Posts:-
1) String Interview Questions and Answers
2) Exception Handling Interview questions and answers
3) Difference between Loose Coupling and Tight Coupling in Java With Examples.
4) Interface and Abstract Class Interview Questions and Answers

Friday, 24 May 2019

Builder Design Pattern in Java

        The  Design Pattern is an important question for the experienced(4+ exp) candidates.  For freshers interviewer will check the Singleton or Factory design pattern knowledge but when comes to experience we need to know other design patterns also. In the current post, we will discuss one of the important design pattern i.e Builder Design Pattern. 

Read Top Java blogs, Feedspot Top 40 Java Blogs

What is Builder Design Pattern? 

According to wikipedia definition:-

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

It is used to construct a complex object step by step and the final step will return the object.

When to use ?

 Following are the conditions where we can use builder design pattern,

  • When multiple representation of objects are required.
  • Number of parameter required in constructor is more than manageable(more than 4 or 5)
  • Object creation contains optional parameter.

Guidelines to create the Builder Design Pattern:-

1) Create a static builder class inside the class whose object is to be build by the builder. EmployeeBuilder class is a static class created as in the example.

2) Builder class should have public constructor  with required parameters and outside class should have private constructor. All fields of class should be private.

3) Needs to write methods to get the values of optional parameters.
e.g withFieldPhone(), withFieldAddress and withFieldDateOfBirth().
In example, phone,address and dob are optional parameters.

4) Create builder method in the builder class to get the desired object.

Example:--

Employee.java,

package com.test;

public class Employee {
 
     private int id;
     private String name;
     private int age;
     private String phone;
     private String address;
     private String dob;
 
     private Employee(EmployeeBuilder builder) {
         this.id = builder.id;
         this.name = builder.name;
         this.age = builder.age;
         this.phone = builder.phone;
         this.address = builder.address;
         this.dob = builder.dob;
     }
 
     public int getId() {
         return id;
     }

     public String getName() {
         return name;
     }

     public int getAge() {
         return age;
     }

     public String getPhone() {
         return phone;
     }

     public String getAddress() {
         return address;
     }

     public String getDob() {
         return dob;
     }

     public static class EmployeeBuilder {
  
         private int id;
         private String name;
         private int age;
         private String phone;
         private String address;
         private String dob;
  
         //id, name and age are manadatory fields 
         public EmployeeBuilder(int id, String name, int age) {
             this.id = id;
             this.name = name;
             this.age = age;
         }
  
         public EmployeeBuilder withFieldPhone(String phone) {
             this.phone = phone;
             return this;
         }
  
         public EmployeeBuilder withFieldAddress(String address) {
             this.address = address;
             return this;
         }
  
         public EmployeeBuilder withFieldDateOfBirth(String dob) {
             this.dob = dob;
             return this;
         }
  
         public Employee build() {
             return new Employee(this);
         }
    }    
 
     @Override 
     public String toString() { 
         return "Id - "+id+", Name - "+name+", age - "+age+ ",address - "+ address+
          ", Phone - "+phone; 
     }
  
}

The above code is an example of Builder Design pattern, Now this we can access in below code.

BuilderDesignPatternEx.java,

package com.test;

public class BuilderDesignPatternEx {
 
     public static void main(String[] args) {
         Employee pattern = new Employee.EmployeeBuilder(10, "Kiran",10).withFieldAddress("Sonyal").build();
         System.out.println(pattern);
         //System.out.println(pattern.getName());
     }

}

Output:--

Id - 10, Name - Kiran, age - 10,address - Sonyal, Phone - null


Java built in builder design pattern examples:

StringBuilder and StringBuffer classes are internally used builder design pattern concept.

Thank you for visiting blog..

Monday, 13 May 2019

Java 8 - BiConsumer, BiFunction and BiPredicate Interface Example

        We discussed in earlier posts, Java 8 Consumer Interface, method reference and forEach() method with examples. In this page or post, we will discuss about BiConsumer, BiFunction and BiPredicate Interface with examples.

       All these Interfaces accept two input parameters and returns a result. We will discuss more details of each interface as below.

  • BiConsumer (java.util.function package)

        BiConsumer is a functional interface, has one abstract method i.e accept(), similar to a Consumer Interface. The difference between consumer and BiConsumer is Consumer interface accepts single parameter where as BiConsumer accepts two input parameters, and both doesn’t return anything.

Example:-

package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class BiConsumerExample {
 
         public static void main(String[] args) {
      
                   //Consumer example
                  Consumer<String> strConsumer = str -> System.out.println(str);
                  strConsumer.accept("Java Wolrd");
  
                  //BiConsumer example
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("Hello", "World");
                  BiConsumer<String, String> consumer = (key, value) -> System.out.println("Key - "+ key+", Value - "+value);
    
                  map.forEach(consumer);
         }

}

Output:-
Java World
Key - Hello, Value - World


  • BiFunction (java.util.function package)
         BiFunction interface is also similar to Function interface(It is also functional interface), difference is Function interface will accept one parameter but BiFunction interface accepts two parameters as a input and returns results.

Declaration:-

Interface BiFunction<T,U,R>

Here, 

T - the type of the first argument as input
U - the type of the second argument as input
R - the type of the result of the function

Example:-

package com.test;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {
 
         public static void main(String[] args) {
  
                 //Function example
                Function<Integer, Integer> printNumber = a -> a*10;
                System.out.println("Number is "+printNumber.apply(10));
  
                 //BiFunction example
                BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
                System.out.println("Summation of two number is "+add.apply(3,2));
        }

}

Output:-
Number is 100
Summation of two number is 5


  • BiPredicate (java.util.function package)

        This interface also similar to Predicate interface and it's also functional interface. Predicate interface takes one agrument as input and return boolean value. But BiPredicate interface takes two arguments as input and returns boolean data type same as Predicate interface.

Example:-

package com.test;

import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class BiPredicateExample {
 
         public static void main(String[] args) {
                
                 //Predicate example
                Predicate<String> pr = a -> a.contains("A");
                System.out.println(pr.test("Anil"));
  
                 //BiPredicate example
                BiPredicate<Integer, Integer> biPrdt = (a,b) -> a>10 && b<5;
                System.out.println(biPrdt.test(11, 2));
         }
}

Output:-
true
true


Related Posts:-
1) Java 8 forEach method with examples
2) Method References in Java 8
3) Java 8 features with examples
4) Java 8 - Consumer Interface with examples