Unit No 4 Exception Handling and Multithreading.pptx

383 views 35 slides Dec 20, 2023
Slide 1
Slide 1 of 35
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35

About This Presentation

Exception Handling and Multithreading


Slide Content

Object Oriented Programming with Java Unit No. 4: Exception Handling And Multithreading Sanjivani Rural Education Society’s Sanjivani College of Engineering, Kopargaon-423603 (An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune) NAAC ‘A’ Grade Accredited, ISO 9001:2015 Certified Department of Information Technology (UG Course: NBA Accredited ) D r . Y.S.Deshmukh Assistant Professor

Object Oriented Programming with Java Exception Handling in Java: The  Exception Handling in Java  is one of the powerful  mechanism to handle the runtime errors  so that the normal flow of the application can be maintained . What is Exception in Java? Exception is an abnormal condition . In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime . What is Exception Handling? Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException , IOException , SQLException , RemoteException , etc .

Object Oriented Programming with Java Exception Handling in Java: Advantage of Exception Handling The core advantage of exception handling is  to maintain the normal flow of the application . An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario : statement 1;   statement 2;   statement 3;   statement 4;   statement 5;//exception occurs   statement 6;   statement 7;   statement 8;   statement 9;   statement 10;  

Object Oriented Programming with Java Exception Handling in Java: Advantage of Exception Handling Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in  Java .

Object Oriented Programming with Java Exception Handling in Java: Hierarchy of Java Exception classes:

Object Oriented Programming with Java Types of Java Exceptions: There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely: Checked Exception Unchecked Exception Error

Object Oriented Programming with Java Difference between Checked and Unchecked Exceptions: 1) Checked Exception The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException , SQLException , etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException , etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. 3) Error Error is irrecoverable. Some example of errors are OutOfMemoryError , VirtualMachineError , AssertionError etc.

Object Oriented Programming with Java Java Exception Keywords: Java provides five keywords that are used to handle the exception. The following table describes each . Keyword Description try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.

Object Oriented Programming with Java Example of Java Exceptions: public   class   JavaExceptionExample {      public   static   void  main(String  args []){       try {         //code that may raise exception          int  data=100/0;      } catch ( ArithmeticException  e){ System.out.println (e);}      //rest code of the program        System.out.println ("rest of the code...");     }   }  

Object Oriented Programming with Java Common Scenarios of Java Exceptions: 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException . int  a=50/0;// ArithmeticException    2) A scenario where NullPointerException occurs If we have a null value in any  variable , performing any operation on the variable throws a NullPointerException . String s= null ;   System.out.println ( s.length ());// NullPointerException    3) A scenario where NumberFormatException occurs If the formatting of any variable or number is mismatched, it may result into NumberFormatException . Suppose we have a  string  variable that has characters; converting this variable into digit will cause NumberFormatException . String s=" abc ";   int   i = Integer.parseInt (s);// NumberFormatException   

Object Oriented Programming with Java Common Scenarios of Java Exceptions: 4) A scenario where ArrayIndexOutOfBoundsException occurs When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException . Consider the following statements. int  a[]= new   int [5];   a[10]=50; // ArrayIndexOutOfBoundsException   

Object Oriented Programming with Java Multithreading in Java: Multithreading in  Java  is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation, etc . Advantages of Java Multithreading 1) It  doesn't block the user  because threads are independent and you can perform multiple operations at the same time. 2) You  can perform many operations together, so it saves time . 3) Threads are  independent , so it doesn't affect other threads if an exception occurs in a single thread.

Object Oriented Programming with Java Multithreading in Java: Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways: Process-based Multitasking (Multiprocessing) Thread-based Multitasking (Multithreading) 1) Process-based Multitasking (Multiprocessing) Each process has an address in memory. In other words, each process allocates a separate memory area. A process is heavyweight. Cost of communication between the process is high. Switching from one process to another requires some time for saving and loading  registers , memory maps, updating lists, etc.

Object Oriented Programming with Java Multithreading in Java: 2) Thread-based Multitasking (Multithreading) Threads share the same address space. A thread is lightweight. Cost of communication between the thread is low . What is Thread in java A thread is a lightweight subprocess , the smallest unit of processing. It is a separate path of execution. Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.

Object Oriented Programming with Java Multithreading in Java:

Object Oriented Programming with Java Multithreading in Java: As shown in the Previous figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the  OS , and one process can have multiple threads. Java Thread class Java provides  Thread class  to achieve thread programming. Thread class provides  constructors  and methods to create and perform operations on a thread. Thread class extends  Object class  and implements Runnable interface.

Object Oriented Programming with Java Multithreading in Java: Life cycle of a Thread: In Java, a thread always exists in any one of the following states. These states are: New Active Blocked / Waiting Timed Waiting Terminated Explanation of Different Thread States New:  Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution. Active:  When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is  runnable , and the other is  running .

Object Oriented Programming with Java Multithreading in Java: Runnable:  A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state. A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie. Running:  When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.

Object Oriented Programming with Java Multithreading in Java: Blocked or Waiting:  Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state . Terminated:  A thread reaches the termination state because of the following reasons: When a thread has finished its job, then it exists or terminates normally. Abnormal termination:  It occurs when some unusual events such as an unhandled exception or segmentation fault. A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active after kill) the dead thread.

Object Oriented Programming with Java Multithreading in Java:

Object Oriented Programming with Java Multithreading in Java: How to create a thread in Java There are two ways to create a thread: By extending Thread class By implementing Runnable interface. Thread class: Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface. Commonly used Constructors of Thread class: Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r,String name )

Object Oriented Programming with Java Multithreading in Java: Commonly used methods of Thread class: public void run():  is used to perform action for a thread. public void start():  starts the execution of the thread.JVM calls the run() method on the thread. public void sleep(long miliseconds ):  Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join():  waits for a thread to die. public void join(long miliseconds ):  waits for a thread to die for the specified miliseconds . public int getPriority ():  returns the priority of the thread. public int setPriority ( int priority):  changes the priority of the thread. public String getName ():  returns the name of the thread. public void setName (String name):  changes the name of the thread. public Thread currentThread ():  returns the reference of currently executing thread.

Object Oriented Programming with Java Multithreading in Java: Commonly used methods of Thread class: public int getId ():  returns the id of the thread. public Thread.State getState ():  returns the state of the thread. public boolean isAlive ():  tests if the thread is alive. public void yield():  causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend():  is used to suspend the thread( depricated ). public void resume():  is used to resume the suspended thread( depricated ). public void stop():  is used to stop the thread( depricated ). public boolean isDaemon ():  tests if the thread is a daemon thread. public void setDaemon ( boolean b):  marks the thread as daemon or user thread. public void interrupt():  interrupts the thread. public boolean isInterrupted ():  tests if the thread has been interrupted. public static boolean interrupted():  tests if the current thread has been interrupted.

Object Oriented Programming with Java Multithreading in Java: Runnable interface: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run():  is used to perform action for a thread. Starting a thread: The  start() method  of Thread class is used to start a newly created thread. It performs the following tasks: A new thread starts(with new callstack ). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.

Object Oriented Programming with Java Multithreading in Java: 1) Java Thread Example by extending Thread class class  Multi  extends  Thread{   public   void  run(){   System.out.println ("thread is running...");   }   public   static   void  main(String  args []){   Multi t1= new  Multi();   t1.start();    }   }  

Object Oriented Programming with Java Multithreading in Java: 2) Java Thread Example by implementing Runnable interface class  Multi3  implements  Runnable{   public   void  run(){   System.out.println ("thread is running...");   }      public   static   void  main(String  args []){   Multi3 m1= new  Multi3();   Thread t1 = new  Thread(m1);   // Using the constructor Thread(Runnable r)   t1.start();    }   }   If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to explicitly create the Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.

Object Oriented Programming with Java Multithreading in Java: 3) Using the Thread Class: Thread(String Name) We can directly use the Thread class to spawn new threads using the constructors defined above . public   class  MyThread1   {   // Main method   public   static   void  main(String  argvs [])   {   // creating an object of the Thread class using the constructor Thread(String name)    Thread t=  new  Thread("My first thread");      // the start() method moves the thread to the active state   t.start ();   // getting the thread name by invoking the  getName () method   String  str  =  t.getName ();   System.out.println ( str );   }   }  

Object Oriented Programming with Java Multithreading in Java: 4) Using the Thread Class: Thread(Runnable r, String name) public   class  MyThread2  implements  Runnable   {     public   void  run()   {     System.out.println ("Now the thread is running ...");     }          // main method   public   static   void  main(String  argvs [])   {    // creating an object of the class MyThread2   Runnable r1 =  new  MyThread2();       // creating an object of the class Thread using Thread(Runnable r, String name)   Thread th1 =  new  Thread(r1, "My new thread");        // the start() method moves the thread to the active state   th1.start();       // getting the thread name by invoking the  getName () method   String  str  = th1.getName();   System.out.println ( str );   }     }    

Object Oriented Programming with Java Inter-thread Communication in Java: Inter-thread communication  or  Co-operation  is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed . It is implemented by following methods of  Object class : wait() notify() notifyAll ()

Object Oriented Programming with Java Inter-thread Communication in Java: 1) wait() method The wait() method causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll () method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. 2) notify() method The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. 3) notifyAll () method Wakes up all threads that are waiting on this object's monitor.

Object Oriented Programming with Java Inter-thread Communication in Java: Understanding the process of inter-thread communication

Object Oriented Programming with Java Inter-thread Communication in Java: The point to point explanation of the above diagram is as follows: Threads enter to acquire lock. Lock is acquired by on thread. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. If you call notify() or notifyAll () method, thread moves to the notified state (runnable state). Now thread is available to acquire lock. After completion of the task, thread releases the lock and exits the monitor state of the object.

Object Oriented Programming with Java Inter-thread Communication in Java: class  Customer{     int  amount=10000;          synchronized   void  withdraw( int  amount){     System.out.println ("going to withdraw...");          if ( this .amount <amount){     System.out.println ("Less balance; waiting for deposit...");     try {wait();} catch (Exception e){}     }     this .amount -=amount;     System.out.println ("withdraw completed...");     }          synchronized   void  deposit( int  amount){     System.out.println ("going to deposit...");     this .amount +=amount;     System.out.println ("deposit completed... ");     notify();     }     }    

Object Oriented Programming with Java Inter-thread Communication in Java: class  Test{     public   static   void  main(String  args []){     final  Customer c= new  Customer();     new  Thread(){     public   void  run(){ c.withdraw (15000);}     }.start();     new  Thread(){     public   void  run(){ c.deposit (10000);}     }.start();          }}    

Object Oriented Programming with Java Thank You