Author: admin

  • Java – Deadlock with Example

    Deadlock in multithreading is a situation where two or more than two are a lock, waiting for each other.

    When the first thread needs to use the same lock or wait for the object lock which is acquired by a second thread and the second thread also waits for the lock acquired by a first thread then the deadlock occurs because they are waiting for each other which is caused by synchronized keyword.

    One of the example where Deadlock occur is the Dining Philosophers problem in C.


    Example: Java program for Deadlock demonstration.

     public class NamesDeadLock 
      {  
        public static void main(String[] args) 
        {  
          String Lock1 = "Prashant";  
          String Lock2 = "Karan";
          //Following, the two different thread are created t1 and t2
            
        // here t1 tries to lock Lock1 then Lock2  
        Thread t1 = new Thread() 
        {  
          public void run() 
          {  
            synchronized (Lock1) 
            {  
            System.out.println("Thread 1: Lock1 locked");  
    
            try 
            { 
                Thread.sleep(100);
            } catch (Exception e) {}  
    
            synchronized (Lock2) 
            {  
            System.out.println("Thread 1: Locked2 locked");  
            }  
            }  
          }  
        };  
        
        // here t2 tries to lock Lock2 then Lock1  
        Thread t2 = new Thread() 
        {  
          public void run() 
          {  
            synchronized (Lock2) 
            {  
            System.out.println("Thread 2: Lock2 locked");  
    
            try 
            { 
                Thread.sleep(100);
            } catch (Exception e) {}  
    
            synchronized (Lock1)
            {  
            System.out.println("Thread 2: Lock1 locked");  
            }  
            }  
          }  
        };  
        
            
        t1.start();  
        t2.start();  
        }  
      }

    Output of Deadlock:

      Thread 1: Lock1 locked
      Thread 2: Lock2 locked 

  • Java – Inter-Thread Communication

    When two or more thread needs to exchange information between them in an application, Inter-thread communication is required. Hence, we can also call it Co-Operation.

    The methods that are used for this communication are:

    1. wait()
    2. notify()
    3. notifyAll()

    1. wait()

    This method is written as:

     public void wait()

    This causes the current thread to wait until another thread invokes the notify() method that is it waits until the object is notified.

    2. notify()

    This method is written as:

     public void notify()

    This method wakes up a single thread that is waiting on this object’s monitor.

    3. notifyAll()

    This method is written as:

     public void notifyAll()

    This method wakes up all the threads that called wait( ) on the same object.


    Example: Java program to illustrate the Inter-Thread Communication:

     class Bank
      {  
      int cash = 500;  
        
      synchronized void cashWithdraw(int cash)
      {  
        System.out.println("Going to withdraw Cash");  
        
        if(this.cash < cash)
        {  
        System.out.println("Not Enough Balance");  
        try{
        wait(); //wait method
        }catch(Exception e)
        { }  
        }  
      this.cash -= cash;  
      System.out.println("Cash Withdrawal Completed");  
      }  
        
      synchronized void cashDeposit(int cash)
      {  
        System.out.println("Processing Deposit");  
        this.cash += cash;  
        System.out.println("Deposit completed");  
        notify(); //notify method 
      }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        final Bank b = new Bank();  
    
        new Thread()
        {  
        public void run()
        {
          b.cashWithdraw(1000);
        }  
        }.start();  
    
      new Thread()
      {  
        public void run()
        {
        b.cashDeposit(10000);
        }  
      }.start();  
    
      }
      }

    Output:

      Going to withdraw Cash
      Not Enough Balance
      Processing Deposit
      Deposit completed
      Cash Withdrawal Completed

  • Java – Static Synchronization

    This method is used to achieve static synchronization which locks a class, not an object.

    Why use static synchronization?

    Consider a shared class ‘Numbers’ for two objects (obj1 and obj2). The use of the synchronized method and synchronized block cannot interfere between the objects created(th1 and th2 or th3 and th4) for shared class because the lock was on the object. But interference may occur between th1 and th3 or th2 or th4 because of the class lock, th1 contain another class and th3 contain another class.

    So to solve this interference we use Static Synchronization.

    Java program to demonstrate the use of static synchronization:

     class Numbers
      {  
       synchronized static void displaySum(int a)
       {
        for(int i=1;i<=4;i++)
        {  
         System.out.println(a+i);  
         try
         {  
        
         Thread.sleep(200);  
         }catch(Exception e)
         {
           System.out.println(e);
         }  
        }
       }  
      }  
        
      class Thread1 extends Thread
      {
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(1);  
       }  
        
      }
        
      class Thread2 extends Thread
      { 
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(10);  
       }  
      }  
        
      class Thread3 extends Thread
      {  
       Numbers n;  
       Thread3(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(100);  
       }  
      }  
        
      class Thread4 extends Thread
      {  
       Numbers n;  
       Thread4(Numbers n)
       {  
        this.n = n;  
       }
       public void run()
       {  
        n.displaySum(1000);  
       }  
      }  
            
      public class Main
      {  
        public static void main(String args[])
        {  
          Numbers obj = new Numbers();  
          Thread1 th1=new Thread1(obj);  
          Thread2 th2=new Thread2(obj); 
          Thread3 th3=new Thread3(obj);  
          Thread4 th4=new Thread4(obj); 
      
          th1.start();  
          th2.start();  
          th3.start();  
          th4.start();  
        }  
      }

    Output static synchronization:

      2
      3
      4
      5
      11
      12
      13
      14
      101
      102
      103
      104
      1001
      1002
      1003
      1004 

  • Java – Thread Synchronization

    Having multiple threads in a program may cause inconsistency and thread interference, that is the multiple threads when trying to access the same resource. One thread may try to write and another may try to read the shared resource or same file. So to achieve the use of only one resource or file at a time, we use synchronization.

    Synchronization makes sure that only one out of the multiple threads is allowed to access the resource at a given time.

    In this process, comes the Lock Concept, also known as monitors.
    Each object created in java is provided with the monitor. Only one thread may hold the lock at a time through which thread can lock or unlock.


    Synchronized method in java:

    Java contains a synchronized method to apply synchronous behaviour to the program. This method is used to lock an object for shared resources. The object automatically obtained a lock when it invokes the synchronized method and releases when the work is done.

    Syntax for Synchronized method:

    synchronized(object) 
     {
      //synchronized statement 
      // Access shared variables and other shared resources
     }

    Example of Java program without the use synchronized method:

     class Numbers
      {  
      void displaySum(int a)//method not synchronized  
      {
        for(int i=1;i<=4;i++)
        {  
        System.out.println(a+i);  
        try
        {  
    
          Thread.sleep(200);  
        }catch(Exception e)
        {
          System.out.println(e);
    
        }  
        }  
    
      }  
      }  
        
      class Thread1 extends Thread
      {  
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(1);  
       }  
      }
        
      class Thread2 extends Thread
      {  
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(20);  
       }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers();  
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      }

    Output:

      2
      21
      22
      3
      23
      4
      24
      5

    Now let see an example with the use synchronized method:

     class Numbers
      {  
      synchronized void displaySum(int a)//method synchronized   
      {
        for(int i=1;i<=4;i++)
        {  
        System.out.println(a+i);  
        try
        {  
    
          Thread.sleep(200);  
          }catch(Exception e)
        {
          System.out.println(e);
    
        }  
        }  
    
      }   
      }  
        
      class Thread1 extends Thread
      {  
       Numbers n;  
       Thread1(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(1);  
       }  
    
      }
        
      class Thread2 extends Thread
      {  
       Numbers n;  
       Thread2(Numbers n)
       {  
        this.n = n;  
       }  
       public void run()
       {  
        n.displaySum(20);  
       }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers();  
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      }

    Output:

      2
      3
      4
      5
      21
      22
      23
      2

    Synchronized block in java:

    It is also used to achieve synchronization in java which locks an object for any shared resource. It is the same as a synchronized method.

    Using Synchronized block only selected lines of code can be synchronized.

    Syntax for Synchronized block:

    synchronized (object reference) 
     {   
      //code block need to synchronized   
     }

    Example to demonstrate the use of Synchronized block in Java:

     class Numbers
      {  
      void displaySum(int a)
      {
        synchronized(this)// synchronized  block
        {
        for(int i=1;i<=4;i++)
        {  
          System.out.println(a+i);  
          try
          {  
    
          Thread.sleep(200);  
          }catch(Exception e)
          {
          System.out.println(e);
    
          }  
        }
        } 
    
      }  
      }  
        
      class Thread1 extends Thread
      {  
      Numbers n;  
      Thread1(Numbers n)
      {  
        this.n = n;  
      }  
      public void run()
      {  
        n.displaySum(1);  
      }  
    
      }
    
      class Thread2 extends Thread
      {  
      Numbers n;  
      Thread2(Numbers n)
      {  
        this.n = n;  
      }  
      public void run()
      {  
        n.displaySum(20);  
      }  
      }  
        
      public class Main
      {  
      public static void main(String args[])
      {  
        Numbers obj = new Numbers(); 
        Thread1 th1=new Thread1(obj);  
        Thread2 th2=new Thread2(obj);  
        th1.start();  
        th2.start();  
      }  
      } 

    Output:

      2
      3
      4
      5
      21
      22
      23
      24

    Note that:
    The scope of the synchronized method is higher than the synchronized block.


  • Java – Multithreading with Example

    What is Multithreading?

    The execution of multiple threads or tasks is called multithreading. The main purpose of multithreading is to achieve the simultaneous execution of more than two tasks so to maximize the use of CPU time.

    Thread is a light-weight sub-process or we can say that it is the smallest part of the process. All threads in a program have different execution paths carrying their individual tasks. This is one of the advantages of threads that threads are independent carrying their respective tasks without affecting the others.

    Thread Life Cycle:

    The life cycle of a thread means the various stages a thread goes during its lifetime.
    According to the sun, there are four states. They are: new, runnable, non-runnable, and terminated.

    For better understanding, let us consider the running state also.

    • New
    • Runnable
    • Running
    • Non-Runnable (Blocked)
    • Terminated
    • New:
      It is referred to as born thread that is it is in its new state. It won’t do anything until the start() method is invoked.
    • Runnable:
      After the start() method is invoked, the thread will be in its runnable state. But the control is under the scheduler to finish the execution.
    • Running:
      The thread is considered in its running state when it starts executing. The scheduler selects the thread and executes it in the application.
    • Non-runnable:
      In this state, the thread has to wait. When the multiple threads run in an application, one thread has to wait until the other thread gets executed.
    • Terminated:
      After the completion of the process of thread, it is in its dead state or we can say the thread is terminated.

    Thread priorities:

    In Java thread priorities determines which thread is to execute first and it depends in their priorities.
    Context Switching is switching from one state to another.

    The higher priority threads are considered to be more important in the application and the operating system executes it first. The range of priorities in java:

    • MIN_PRIORITY (a constant of 1)
    • MAX_PRIORITY (a constant of 10).
    • And default priorities: NORM_PRIORITY (a constant of 5).

    Creating a thread:

    There are two ways to create a thread:

    • By extending Thread class.
    • By implementing the Runnable interface.

    Some of the commonly used Thread class;

      public start(): start a thread by calling its run() method.
      public run(): Entry point for the thread.
      public isAlive(): Determine if a thread is still running.
      public join(): Wait for a thread to terminate.
      public getName(): It is used for Obtaining a thread’s name.
      public getPriority(): Obtain a thread’s priority.
      public sleep(): suspend a thread for a period of time.
      public int getId(): returns the id of the thread.
      public void stop(): is used to stop the thread(deprecated).


    1. By extending Thread class.

    The thread class provides methods and also constructors for creating and performing some operation on a thread. In this process, we create a class and extend java.lang.Thread class.

    • First, we override the run() method that is present in the thread class and then put the code inside it.
    • Secondly, we create an object for our class and call the start() method for the execution of a thread.

    Syntax for Thread class:

     run(): public void run( );
     start(): void start( );

    Java program of Thread class:

     class MultiThread extends Thread //extends thread
     {  
      public void run()
      {  
       System.out.println("Successful.");  
      }
     } 
     public class Main
     {
      public static void main(String args[])
      {  
       MultiThread th = new MultiThread();  
       th.start();  
      } 
     }

    Output:

     Successful. 

    2. By implementing the Runnable interface:

    If one of the class’ instance is intended to be executed by a thread then this can be achieved by implementing a Runnable interface. Implementation of java.lang. Runnable interface has one method called run().

    • Here the first step is to provide a program with a run() method that is to override this method and put the block of code or the logic inside it.
    • Secondly, the Thread object is instantiated and once the thread object is created, we can call the start() method to start the thread which will execute run() method.

    Syntax for Runnable interface:

     run(): public void run( );
     start(): void start( );

    Java program of Runnable interface:

     class MultiThread implements Runnable
     {  
      public void run()
      {  
       System.out.println("Successful");  
      }  
     }
     public class Main
     {
      public static void main(String args[])
      {  
       MultiThread mth=new MultiThread();  
       Thread th =new Thread(mth);  
       th.start();
    
       /*or we can also write this above code as
       Thread th = new Thread(new MultiThread());  
       th.start();
       */
      }
     }

    Output:

     Successful 

  • Java – Arrays

    An array is a group or the collection of data having the same data-type. Arrays are objects in Java and with the fixed size(disadvantage). Elements are arranged inside the array with index numbers starting from zero as the first elements.
    Random access of any element present in the array and code optimization feature makes it more useable.

    Types of array in java:

    • Single Dimensional Array. 
    • Multidimensional Array 

    One Dimensional Array:

    One-dimensional array in Java is an array with a bunch of values that are declared with a single index.

    Array declaration:

     data_type [] array_Name;
     or
     data_type[] array-name 
     or
     data_type array-name[]; 

    Example:

    //to store integer value
     int intArray[];
     or
     int []intArray;

    An array declaration has two components:
    The type that is the data-type of an element and the name that is given by user choice with the brackets[].

    Array initialization:

    To initialize an array new is used and it appears as follows:

    var-name = new data-type [size];

    Example:

    Array = new int[10];

    We can also set by combining declaration and initialization in the following ways:

     dataType[] arrayRefVar = new dataType[arraySize];
     or
     dataType[] arrayRefVar = {value0, value1, ..., valuek};

    Accessing an array element:

    Array elements can be accessed by using its index number, where each element is assigned by one index number.
    Example:

    age[2] = 14; // insert 14 to third element

    Example: Click here


    Multi-Dimensional Array (Jagged Array)

    Declaring an array of arrays is known as Multidimensional Array or Jagged Arrays. In simple words, it is an array of arrays. It is created by appending a square brackets “[]” for each dimension. Here data are stored in a tabular form that is in row-major order.

    Syntax:

     data-type name[size1][size2]...[sizeN];
     or
     dataType[size1][size2]...[sizeN] arrayRefVar;  
     or
     dataType [size1][size2]...[sizeN]arrayRefVar;  

    Declaration:

     int twodim[5][10][4];
     int threedim[5][10]; //data-type name[size1][size2]...[sizeN];

    Instantiate Multidimensional Array in Java:

     int[][] arr=new int[3][3];//3 row and 3 column

    Array initialization:

      arr[0][0]=1;  
      arr[0][1]=2;  
      arr[0][2]=3;  
      arr[1][0]=4;  
      arr[1][1]=5;  
      arr[1][2]=6;  
      arr[2][0]=7;  
      arr[2][1]=8;  
      arr[2][2]=9; 

    We can also declare and initialize the 2D array together:

     int arr[][]={ {1,2,3},{4,5,6},{7,8,9} };

    Example: Click here


    Passing Array to Methods:

    Similar to a variable, an array can also be passed to methods. To pass an array users need to call the array with its name and without the square roots within the method call. Let us see with an example below:

    Example: Java program to sum the array values.

     public class ArrayPassToMethodTest 
     {     
        public static void main(String args[])  
        { 
           int arr[] = {1, 5, 3, 6, 2}; 
            
           add(arr); // passing array to method add
        } 
        public static void add(int[] arr)  
        { 
           int sum = 0; 
                
           for (int i = 0; i < arr.length; i++) 
            sum+=arr[i]; 
                
           System.out.println("Value after addition: " + sum); 
        } 
     }

    Output:

     Value after addition: 17

    Returning Arrays from Methods:

    As array can be passed to methods, it can also be returned from the array.
    The following shows an example of it.

     public class ReturningArray
     {  
       public static void main(String args[])  
       { 
        int array[] = method();
        
        System.out.println("The returned array are: ");
        for (int i = 0; i < array.length; i++)
        { 
           System.out.print(array[i]+" "); 
        }
        } 
        
        public static int[] method()  
        { 
        // returning 1D array 
        return new int[]{4,5,6}; 
       } 
     }

    Output:

     The returned array are: 
     4 5 6 

    The foreach Loops:

    It is also possible to print the array using its for-each loop. for-each loop prints the array elements one by one, by holding an array element in a variable, then executing the body of the loop.

    Example of foreach loop in Java:

      public class ArrayWithForEachTest 
      {
    
        public static void main(String[] args) 
        {
          int[] arr = {1, 2, 3, 4};
          
          System.out.println("Elements in array are:");
          // Print all the array elements
          for (int element: arr)
          {
              System.out.println(element);
          }
        }
      }

    Output:

     Elements in array are:
     1
     2
     3
     4

  • Java – Multi-Dimensional Array

    Declaring an array of arrays is known as Multidimensional Array or Jagged Arrays. In simple words, it is an array of arrays. It is created by appending a square brackets “[]” for each dimension. Here data are stored in a tabular form that is in row-major order as shown in an example below.

    Syntax:

     data-type name[size1][size2]...[sizeN];
     or
     dataType[size1][size2]...[sizeN] arrayRefVar;  
     or
     dataType [size1][size2]...[sizeN]arrayRefVar;  

    Declaration:

     int twodim[5][10][4];
     int threedim[5][10]; //data-type name[size1][size2]...[sizeN];

    Instantiate Multidimensional Array in Java:

     int[][] arr=new int[3][3];//3 row and 3 column

    Array initialization:

      arr[0][0]=1;  
      arr[0][1]=2;  
      arr[0][2]=3;  
      arr[1][0]=4;  
      arr[1][1]=5;  
      arr[1][2]=6;  
      arr[2][0]=7;  
      arr[2][1]=8;  
      arr[2][2]=9; 

    We can also declare and initialize the 2D array together:

     int arr[][]={ {1,2,3},{4,5,6},{7,8,9} };

    Example of a Multidimensional array in Java:

    public class MultiDimensionalTest 
    { 
      public static void main(String args[]) 
      { 
        // declaring and initializing 2D array 
        int array[][] = { {1,2,3},{4,5,6},{7,8,9} }; 
      
        // Diplaying 2D Array
        for (int i=0; i< 3 ; i++) 
        { 
          for (int j=0; j < 3 ; j++) 
             System.out.print(array[i][j] + " "); 
      
          System.out.println(""); 
        } 
      } 
    } 

    The output of Multi-dimensional:

    1 2 3 
    4 5 6 
    7 8 9 

  • Java – One-Dimensional Array with Example

    A one-dimensional array in Java is an array with a bunch of values that are declared with a single index. Here data are stored in a single column as shown below in an example.

    Array declaration:

     data_type [] array_Name;
     or
     data_type[] array-name 
     or
     data_type array-name[]; 

    Example:

    //to store integer value
     int intArray[];
     or
     int []intArray;

    An array declaration has two components:
    The type that is the data-type of an element and the name that is given by user choice with the brackets[].

    Array initialization:

    To initialize an array new is used and it appears as follows:

    var-name = new data-type [size];

    Example:

    Array = new int[10];

    We can also set by combining declaration and initialization in the following ways:

     dataType[] arrayRefVar = new dataType[arraySize];
     or
     dataType[] arrayRefVar = {value0, value1, ..., valuek};

    Accessing an array element:

    Array elements can be accessed by using its index number, where each element is assigned by one index number.
    Example:

    age[2] = 14; // insert 14 to third element

    Example of a one-dimensional array in Java:

      public class ArrayTest
      {    
        public static void main(String args[])
        {  
          int a[]={10,22,4,7};//declaration, instantiation and initialization
            
         //displaying array  
         for(int i=0; i < a.length; i++)  
            {
            System.out.println(a[i]);
            }
        }
      }

    Output:

      10
      22
      4
      7

  • Java – Jump Statement

    In Java, Jump statements are used to interrupt loop or switch-case instantly to transfer the program control from one point to elsewhere in the program.
    Java supports three jump statements:

    • continue. 
    • break 
    • return.

    break: 

    This statement is used within the loop or switch cases to terminate that statement or the current loop is immediately stopped and resumes at the next statement followed by a terminated loop. we can also say that it helps to break out from the middle of the loop.

    Syntax of break statement:

     break; 

    continue

    It is used in loops to jump immediately to the next iteration of the loop. continue is used with while loop or do/while loop and with for loop. When continue is used inside for loop then the control immediately jumps to the increment or decrement part of the for loop. And when used inside while loop or do/while loop then the control immediately jumps to the condition part.

    Syntax of continue statement:

    continue; 

    label break statement

    Java does not support goto as it leads to unstructured programming. so instead of ‘goto‘ we can use a label break statement which works like a goto statement.

    Syntax of label:

     label:
        for()
        {
          //code
          break label;
        }

    Example of label break statement in Java:

     public class LabelTest 
     { 
      public static void main(String[] args) 
      { 
        // label for outer loop 
        outerlabel: 
        for (int i = 0; i < 10; i++) 
        { 
        for (int j = 0; j < 10; j++)
        { 
            if (j == 3) 
            {
                break outerlabel; 
            }
                
            System.out.println(" value of j = " + j); 
        } 
        } 
       } 
     }

    Output:

     value of j = 0
     value of j = 1
     value of j = 2

  • Java – continue statement with Example

    It is one of the jump statement in java. It is used in loops to jump immediately to the next iteration of the loop. continue is used with while loop or do/while loop and with for loop.

    When continue is used inside for loop then the control immediately jumps to the increment or decrement part of the for a loop. And when used inside while loop or do/while loop then the control immediately jumps to the condition part.

    Flowchart for Java continue statement:

    Continue statement in java

    Syntax of continue:

    continue; 

    Example: Java program to demonstrate the continue statement:

     public class ContinueTest 
     {
        public static void main(String args[])
        {
        for (int i=0; i<=10; i++)
        {
         if (i == 5)
         {
          continue; // skip the rest of the code
         }
    
        System.out.print(i+" ");
        }
        }
     }

    Output:

     0 1 2 3 4 6 7 8 9 10