Multithreading In Java

Thread:
  • Thread is nothing but functionality which could be executed simultaneously with the other part of the program based on the concept of one with another.
  • But where as method or a function which would be executed hierarchically with the other part of the program.
  • It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel
What is a process? difference between process and thread? 
  • A program which is under execution can be called as process.
  • Some operating systems use the term ‘task‘ to refer to a program that is being executed.
  • Thread is part of the process.
  • Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
  • I'm not sure what "hardware" vs "software" threads might be referring to. Threads are an operating environment feature, rather than a CPU feature (though the CPU typically has operations that make threads efficient).
  • Threads share the address space of the process that created it; processes have their own address space.
  • Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  • Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  • Threads have almost no overhead; processes have considerable overhead.
  • A process is a collection of code, memory, data and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.
How many ways to create thread in java: 
  • we can create threads in two ways.
  • 1. Extending Thread class.
    2. Implementing Runnable interface.

Extending Thread class:

package com.instanceofjavaforus;

public class ExtendsThread extends Thread {
 
    public void run(){
    System.out.println("thread is running...");
    }
    public static void main(String args[]){
    ExtendsThread t1=new ExtendsThread();
    t1.start();
     }
  
}

Implementing Runnable interface

package com.instanceofjavaforus;

public class RunnabelDemo  implements Runnable{
  
    public void run(){ 
    System.out.println("thread is running..."); 
    } 
    public static void main(String args[]){ 
    RunnabelDemo m1=new RunnabelDemo(); 
    Thread t1 =new Thread(m1); 
    t1.start(); 
     } 
   
}



Best Practices for Multithreading
  1. Avoid Deadlocks: Ensure that threads acquire locks in a consistent order.
  2. Use Thread Pools: Prefer ExecutorService over manually creating threads.
  3. Minimize Synchronization: Synchronize only the critical sections of your code.
  4. Use Volatile Variables: Use the volatile keyword for variables that are accessed by multiple threads.
  5. Handle Exceptions: Always handle exceptions in threads to avoid unexpected crashes.
  • java is a powerhouse application that allows programmers to make their applications be able to do multiple tasks at once in essence.Multithreading means that software to the server, is fast; but it also takes advantage of my computer and yours too for performance.It also means that Multithreading allows you to have parallelism between different programs on one machine: from where they run off more than one CPU core all the time--thus increasing efficiency even further than just using performance of one set plus productivity when running together concurrently.In this blog post, we’ll look at how to create threads and use the new C++ STD standard mutex with graphicsexamples. We will also discuss good programming practice; indeed it is essential for multithreading operations in today’s fast-paced development environment.

 What are Threads?

Multithreading allows the execution of multiple threads by a CPU (or the threading of a single core in multi-core processors), and it provides the possibility to interrupt any running thread at all times whether this one happens to be currently blocked for some reason on I/O operations or not at all A thread  is smallest unit that can be independently run within a process. In Java, multithreading allows you to run many threads at the same time--and indeed most of them might finish quickly so they won't need any additional waiting for message processing or other future work which is not needed now that so many jobs have been done.

 Why Multithreading?

Performance Improved: Because tasks are split into several threads you can take better advantage of the resources inside your CPU.
Responsiveness: Even if your program performs a lot of time-consuming tasks, it remains responsive.
Data Sharing: Threads share information and states--so this makes it easier to exchange data between them.
Background Tasks: Multithreading allows you to execute non-blocking operations in the main thread.


Exception Handling

Exception:

  • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  •  few of the subclasses of Error
  • AnnotationFormatError - Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError - Thrown to indicate that an assertion has failed.
  • LinkageError - Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
  •  There are really three important subcategories of Throwable:
  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException.
 instanceofjavaforus.blogspot.com


try block:

  • The functionality of try keyword is to identify an exception object.
  • And catch that exception object and transfer the control along with the identified exception object to the catch block by suspending the execution of the try block.
  • All the statements which are proven to generate exceptions should be place in try block.

catch Block:

  •  The functionality of catch block is to receive the exception class object that has been send by the "try".
  • And catch that exception class object and assigns that exception class object to the reference of the corresponding exception class defined in the catch block.
  • And handle the exception that has been identified by "try".
  • "try"  block identifies an exception and catch block handles the identified exception.

finally block:

  • finally blocks are the blocks which are going to get executed compulsorily irrespective of exceptions.
  • finally blocks are optional blocks.

 throw keyword:

  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined)

 throws keyword:

  •  The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.
  1. package com.instanceofjavaforus;
  2. public class ExcpetionDemo {
  3.  public static void main(String agrs[]){
  4.   try{
  5. //statements
  6. }catch(Exception e){
  7.  System.out.println(e);
  8. }
  9. finally(){
  10. //compulsorily executable statements 
  11. }
  12.   }
  13. }

 

Unreachable Blocks:

  • The block of statements to which the control would never reach under any case can be called as unreachable blocks.
  • Unreachable blocks are not supported by java.
  • Thus catch block mentioned with the reference of  "Exception" class should and must be alwats last catch block. Because Exception is super class of all exceptions.

  1. package com.instanceofjavaforus;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[]){
  4. try{
  5. //statements
  6. }catch(Exception e){
  7. System.out.println(e);
  8. }
  9. catch(ArithmeticException e)//unreachable block.. not supported by java. leads to error
  10. System.out.println(e);
  11.  }
  12. }

This Keyword and Instanceof operator

  • The functionality of "this" keyword is only to explicitly point the object because of which the function is currently under execution.
  • The object because of which the function is currently under execution is known as current object.
  • Thus the functionality of this is to point current class object.
This used to call constructor from another constructor:

Class Tdemo{

Tdemo(){
this(6);
System.out.println("Default constructor")
}
Tdemo(int a ){
this(1,2);
System.out.println("One argument constructor")
}

Tdemo(int a, int b ){

System.out.println("Two argument constructor")
}

public static void main(String args[]){

Tdemo obj= new Tdemo();

}
}

Output:
Two argument constructor
One argument constructor
Default constructor

Program for without this keyword:

class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
id=id;
name=name;
college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();

}

Output:
0 null null
0 null null

in the above program parameters and instance variables are same.so we by using this keyword we can solve this problem.

solution of the above problem using This keyword:

class Student{
int id;
String name;
String college;
Student(int id,String name,String college){
this.id=id;
this.name=name;
this.college=college;
}
void display(){
System.out.println(id+" "+name+" "+college);
}
public satic void main(String args[]){
Student s=new Student(1,"Indhu","TRML");
Student s1=new Student(2,"Sindhu","TRML");
s.display();
s1.sispaly();

}

Output:
1 Indhu TRML
2 Sindhu TRML

Important points of this keyword:

  • This is final variable in java.so we can't assign values to the final.
  • this=new Emp(); //Can't assign values to this.it will return compilation error.

Limitation of this keyword:

  • "this" is applicable to only to the non static methods because static methods are not executed by any object

Instance of operator:

  • Instance of operator is used to test whether that object is belong to that class type or not.
  • If that object belongs to that class it returns true .otherwise it returns false.
  • Instance of operator is also known as comparison operator.because it compares with the instance of type.
Program to instance of operator:

public class Employee{
public static void main(String args[]){
Employee e =new Employee();
System.out.println(e instanceof Employee);//true
}
}

Output:true

public class A{
public void show(){
System.out.println("This is class A");
}

public class B extends A{
public void show(){
System.out.println("This is class B");
}
public static void main(String args[]){
A a=new A();
System.out.println(a instanceof A);
System.out.println(a instanceof B);
}
}

Output:
true
false

Abstract Class and Interfaces

Abstract Class:
  • Abstract class means hiding the implementation  and showing the function definition to the user is known as Abstract class
  • Abstract classes having Abstract methods and normal methods (non abstract methods) will be there.
  • Abstract classes having methods will be anything means public ,private,protected.
    In Abstract classes  variables will be anything( public, private, protected)
    For Abstract classes we not able to create object directly.But Indirectily we can create object using sub calss object.
  • A Java abstract class should be extended using keyword “extends”.
  • A Java abstract class can have instance methods that implements a default behavior.
    If you know requirement and partially implementation you can go for Abstract classes.
    abstract  class  can extend from a class or from an abstract class.
  • Abstract class can extend only one class or one abstract class at a time. soAbstract classes can't support multiple inheritance.
  • In comparison with java Interfaces, java Abstract classes are fast.
    If you add new method to abstract class, you can provide default implementation of it. So you don’t need to change your current code.
  • Abstract classes can have constructors .
    We can run an abstract class if it has main() method.

Example Program:


abstract class A{

abstract void display();
public void show(){
S.o.p("Indhu");
}

Public class B extends A{
void display();
}
Abstract class C Extends B{
//Escaping Here
}
public static void main(String args()){
A a= new B();
a.display();
a.show();

}

Interface :

  • Interface nothing but some set of rules.
  • Interfaces having only Abstract methods.it is purely Achive Abstraction.
  • In Interfaces by default the methods will be public abstract methods.
  • In Interfaces by default the variables will be static final .
  • For Interfaces we can't create object directly or Indirectly but we can give sub class object reference to interface .
  • Java interface should be implemented using keyword “implements”. 
  • methods of a Java interface are implicitly abstract and cannot have implementations.
  • If u don't know Any requirement and any implementation you can go for Interfaces.
  • Interface can extend only from an interface
  • Interface can extend any number of interfaces at a time. so interfaces can support multiple inheritance(syntactical not implementation of multiple inheritance).
  • In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
  • if  you add new method to interface, you have to change the classes which are implementing that interface
  • Interface having no constructor.
    we can’t run an interface because they can’t have main method implementation.
Example Program:

public interface Payment
{
    void makePayment();//by default it is a abstract method
}
public class PayPal implements Payment
{
    public void makePayment()
    {
        //some logic for paypal payment
        //like paypal uses username and password for payment
    }
}
public class CreditCard implements Payment
{
    public void makePayment()
    {
        //some logic for CreditCard payment
        //like CreditCard uses card number, date of expiry etc...
    }

Final Keyword

    Final variables:

    • Any variable declare along with final modifier then those variables treated as final variable.
    •  if we declare final variables along with static will became constants.
    • while declaring itself we need to assign these final variables.
    • final int a;
    Example program: 

       class finalvariabledemo{

       final int a=10;
        public static void main(String args[]){
        finalvariabledemo obj= new finalvariabledemo();
        //obj.a=24;  this will rise compile time error
    }
    }

    Output:

    Compile time Error.

    Final Method:

    • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
    • public final void add(){
       }
       public class A{
       void add(){
       //Can't override
       }
       }

    Final Class:

    • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extends that class in anyway.
    • public final class indhu{
       }
       public class classNotAllowed extends indhu {...} //not allowed

    Static Keyword

    Static Keyword
    • Static means class level. static can be applied to variable method and block.
    • static variables , static methods , static blocks.
    • makes your program memory efficient 
    Static variables 
    • If you declare any variable as static, it is known static variable.
    • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
    • The static variable gets memory only once in class area at the time of class loading.
    Example program:

    package com.instanceofjava.snippets.basics;


    public class StaticDemo {

        // static variable - the same on all instances of a class
        static int X = 10;

        // non static variable
        int Y = 5;
       
        public static void main(String[] args) {




      StaticDemo o1= new StaticDemo();

      StaticDemo o2= new StaticDemo();


      System.out.println("o1.X = " + o1.X + " o1.Y = " + o1.Y);

      System.out.println("o2.X = " + o2.X + " o2.Y = " + o2.Y);

     

      instance1.X = 15;

      instance1.Y = 10;

     

      System.out.println("After updating X value to 15 and Y value to 10 from o1:");

      System.out.println("o1.X = " + o1.X + " o1.Y = " + o1.Y);

      System.out.println("o2.X = " + o2.X + " o2.Y = " + o2.Y);

        }

    }

    Output:

    instance1.X = 10 o1.Y = 5
    instance2.X = 10 o2.Y = 5
    After updating X value to 15 and Y value to 10 from o1:
    instance1.X = 15 o1.Y = 10
    instance2.X = 15 o2.Y = 5 



    Static methods:
    • Static method belongs to the class rather than object of a class
    • Static methods can be called without creating an object of class
    • Static method can access static data member and can change the value of static data
    • You can define as many static methods. These methods are independent, except that they may refer to each other through calls
    • Any static method can call any other static method in the same file or any static method in a Java library like Math
    Example program:

    1. class Student{  
    2.      int rollno;  
    3.      String name;  
    4.      static String college = "SBIT";  
    5.        
    6.      static void change(){  
    7.      college = "SBCE";  
    8.      }  
    9.   
    10.      Student9(int r, String n){  
    11.      rollno = r;  
    12.      name = n;  
    13.      }  
    14.   
    15.      void show(){
    16.      System.out.println(rollno+" "+name+" "+college);
    17.    }  
    18.   
    19.     public static void main(String args[]){  
    20.     Student.change();  
    21.   
    22.     Student s1 = new Student (37,"indhu");  
    23.     Student s2 = new Student (38,"sindhu");  
    24.     Student s3 = new Student (39,"swathi");  
    25.   
    26.     s1.show();  
    27.     s2.show();  
    28.     s3.show();  
    29.     }  

    OutPut:

    indhu SBCE
    sindu SBCE
    swathi SBCE

    Static Blocks:
    • Whenever class loads these static blocks will be exeuted.
    • Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
    • we can use static blocks to assign static variables.
    Example program:
    class staticBlockDemo{

        static int i;

        int j;

        

        // start of static block

        static {

            i = 20;

            System.out.println("static block called ");

        }

        // end of static block

    }

    class Main {

        public static void main(String args[]) {

            // Although we don't have an object of staticBlockDemo, static block is

            // called because i is being accessed in following statement.

            System.out.println(staticBlockDemo.i);

        }

    }



          Output:

    static block called

    20



     
    Select Menu