Concurrency 1 Chapter

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Concurrency

 SOLID principles are object-oriented design concepts relevant to software


development.
 SOLID is an acronym for five other class-design principles: Single Responsibility
Principle, Open-Closed Principle, Liskov Substitution Principle, 
 Interface Segregation Principle, and Dependency Inversion Principle.

 SOLID is a structured design approach that ensures your software is modular and easy
to maintain, understand, debug, and refactor.
 Following SOLID also helps save time and effort in both development and
maintenance.
 SOLID prevents your code from becoming rigid and fragile, which helps you build
long-lasting software.
1.1 Single responsibility principle

• Every class in Java should have a single job to do.


• To be precise, there should only be one reason to change a class.
• Here’s an example of a Java class that does not follow the single
responsibility principle (SRP):
• public class vehicle{
• public void PrintDetails(){}
• public double calculateValue(){}
• public void addVehicleToDB(){}
•}
Open-closed principle
• Software entities (e.g., classes, modules, functions) should be open for
an extension, but closed for modification.

Liskov substitution principle

The Liskov Substitution Principle (LSP) applies to inheritance


hierarchies such that derived classes must be completely substitutable
for their base classes.
Interface segregation principle
The Interface Segregation Principle (ISP) states that clients should
not
be forced to depend upon interface members they do not use.
In other words, do not force any client to implement an interface that is
irrelevant to them.

Dependency inversion principle

The Dependency Inversion Principle (DIP) states that we should


depend on abstractions (interfaces and abstract classes) instead of
concrete implementations (classes). The abstractions should not depend
on details; instead, the details should depend on abstractions.
1.2 Commonly used Constructors of Thread class:

Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class
public void run(): is used to perform action for a thread
public void join(): waits for a thread to die
public int getId(): returns the id of the thread
public Thread.State getState(): returns the state of the thread
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
• 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);  
• t1.start();  
•  }  
• }  
1.3 Creating Thread
• Thread a line of execution within a program.
• Each program can have multiple associated threads.
• Each thread has a priority which is used by thread scheduler to determine
which thread must run first. 
• Java provides a thread class that has various method calls inorder to manage the
behavior of threads.
• Public class Thread
extends object
implements Runnable
Thread class provide constructors and methods to create and perform operations on
a thread.
Thread class extends Object class and implements Runnable interface
Starting a thread:

• start() method of Thread class is used to start a newly created thread.


It performs 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.
• class Multi extends Thread{  
• public void run(){  
• System.out.println("thread is running...");  
• }  
• public static void main(String args[]){  
• Multi t=new Multi();  
• t.start();  
•  }  
• }  
• 1.4 Thread .sleep method
The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException.
Example
• class TestSleepMethod1 extends Thread{  
•  public void run(){  
•   for(int i=1;i<5;i++){  
try{ Thread .sleep (500);
}
catch(InterruptedException e)
{System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();  
   
  t1.start();  
  t2.start();  
 }  
}  
1.5 Wait, notify and notifyAll methods
wait() causes current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
in other words, this method behaves exactly as if it simply performs the
call wait(0).
The current thread must own this object's monitor.
The wait() method is defined in Object class which is the super most
class in Java. This method tells the calling thread (Current thread) to
give up the lock and go to sleep until some other thread enters the same
monitor and calls notify() or notifyAll(). It is a final method, so we
can’t override it.
How wait() method works?
The wait() method is used for interthread communication.
In Inter-thread communication, the synchronized threads can
communicate with each other.
As you know in synchronized block or method, only one thread can
enter(acquire the lock).
By use of wait() method a thread is paused(release lock) running in its
critical section and another thread can enter (acquire the lock) in the
same critical section
So that multiple threads can communicate between the thread by use of
use wait() and notify()
 You can tell one thread to stop working (By wait() method) from
another thread based upon some condition, later you can notify it to start
processing again(By notify() or notifyAll() method).
• The wait() method is tightly integrated with the synchronization
lock, using a feature not available directly from the synchronization
mechanism
• Unlike sleep() method, the wait() method, the thread goes in waiting
state and it won’t come back automatically until we call the notify()
or notifyAll()
• Let’s say a user wants to print some pages in the printer. So, we are
creating two threads, one thread for print the pages and another thread
for add the pages in the printer.

If the number of papers in the printer is less than the number of entered
input, then we will call wait() method for the thread, meanwhile,
another thread will add more pages in the printer and notify the current
thread by notify() method.
1.6 Thread Pool & Executor Service

Java Thread Pool


• Java Thread pool represents a group of worker threads that are waiting for the job and
reuse many times.
• In case of thread pool, a group of fixed size threads are created. A thread from the thread
pool is pulled out and assigned a job by the service provider. After completion of the job,
thread is contained in the thread pool again.

Advantage of Java Thread Pool


• Better performance It saves time because there is no need to create new thread.
• Real time usage
• It is used in Servlet and JSP where container creates a thread pool to process the request.
• Executor Service
Executor Service is a JDK API that simplifies running tasks in
asynchronous mode.
Generally speaking, Executor Service automatically provides a pool of
threads and an API for assigning tasks to it.
• We can assign tasks to the ExecutorService using several methods
including execute(), which is inherited from the Executor interface,
and also submit(), invokeAny() and invokeAll().

The execute() method is void and doesn't give any possibility to get
the result of a task's execution or to check the task's status (is it
running):
• 1.7 Fork Join Framework
• The core addition is a new Fork Join pool executor that is dedicated to
running instances implementing ForkJoin task.
• ForkJoin task objects support the creation of subtasks plus waiting for
the subtasks to complete.
• With those clear semantics, the executor is able to dispatch tasks
among its internal threads pool by “stealing” jobs when a task is
waiting for another task to complete and there are pending tasks to be
run.
• ForkJoin task objects feature two specific methods:
• The Fork() method: allows a ForkJoin task to be planned for
asynchronous execution.this allows a new ForkJoin task to be
launched from an existing one.
• The Join() method: allows ForkJoin task to wait for the completion of another
one.
• 1.8 Collection Parallel Stream method
• Java Parallel Streams is a feature of Java 8 and higher, meant for
utilizing multiple cores of the processor.
• Normally any java code has one stream of processing, where it is
executed sequentially.
• Whereas by using parallel streams, we can divide the code into multiple
streams that are executed in parallel on separate cores and the final result
is the combination of the individual outcomes.
• The order of execution, however, is not under our control.
• Therefore, it is advisable to use parallel streams in cases where no matter
what is the order of execution,
• the result is unaffected and the state of one element does not affect the
other as well as the source of the data also remains unaffected
• here are two ways we can create parallel streams in Java
•  Using parallel() method on a stream
• The parallel() method of the BaseStream interface returns an
equivalent parallel stream
• Using parallel Stream() on a Collection
• The parallel Stream() method of the Collection interface returns a
possible parallel stream with the collection as the source.

You might also like