SlideShare a Scribd company logo
Programming Paradigms
• Single Process
• Multi Process
• Multi Core/Multi Thread
Multi Core CPU
Process
• Process
A process runs independently and isolated of
other processes. It cannot directly access
shared data in other processes. The resources
of the process are allocated to it via the
operating system, e.g. memory and CPU time.
Java Process
Objects
• ADTs, aggregate components, JavaBeans, monitors,
business objects, remote RMI objects, subsystems, ...
• May be grouped according to structure, role, ...
• Usable across multiple activities — focus on SAFETY
Activities
• Messages, call chains, threads, sessions, scenarios,
scripts, workflows, use cases, transactions, data flows,
mobile computations
Thread
• Threads are so called lightweight processes
which have their own call stack but an access
shared data. Every thread has its own memory
cache. If a thread reads shared data it stores
this data in its own memory cache. A thread
can re-read the shared data
What is The Gain
• Amdahl's Law
• It states that a small portion of the program which
cannot be parallelized will limit the overall speed-up
available from parallelization.
• A program solving a large mathematical or engineering
problem will typically consist of several parallelizable
parts and several non-parallelizable (sequential) parts.
If p is the fraction of running time a sequential program
spends on non-parallelizable parts, then
• S = 1/p
How much is the speed up
• If the sequential portion of a program accounts
for 10% of the runtime, we can get no more than
a 10× speed-up, regardless of how many
processors are added. This puts an upper limit on
the usefulness of adding more parallel execution
units. "When a task cannot be partitioned
because of sequential constraints, the application
of more effort has no effect on the schedule. The
bearing of a child takes nine months, no matter
how many women are assigned
How does Java help to Parallel
Programming
• Has Threads since its inception
• Threads have their own stack. But uses heap
of the JVM
• Has many constructs to control the
concurrency
• Programmer knowledge is very critical
JVM Process Heap
Thread Class
Constructors
• Thread(Runnable r) constructs so run() calls r.run()
• — Other versions allow names, ThreadGroup placement
Principal methods
• start() activates run() then returns to caller
• isAlive() returns true if started but not stopped
• join() waits for termination (optional timeout)
• interrupt() breaks out of wait, sleep, or join
• isInterrupted() returns interruption state
• getPriority() returns current scheduling priority
• setPriority(int priorityFromONEtoTEN) sets it
How to Implement a Thread
• Subclass Thread. The Thread class itself
implements Runnable, though its run method
does nothing. An application can subclass
Thread, providing its own implementation of
run
Thread Subclass
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Implement Runnable Interface
public class HelloRunnable implements Runnable
{
public void run() {
System.out.println("Hello from a thread!"); }
public static void main(String args[]) {
(new HelloRunnable()).start();
}
}
Pausing while executing
• Thread.sleep causes the current thread to
suspend execution for a specified period.
• This is an efficient means of making processor
time available to the other threads of an
application or other applications that might be
running on a computer system. The sleep
method can also be used for pacing
Thread Management
• To directly control thread creation and
management, simply instantiate Thread each
time the application needs to initiate an
asynchronous task.
• To abstract thread management from the rest
of your application, pass the application's
tasks to an executor.
Sleep Example
• main declares that it throws
InterruptedException. This is an exception that
sleep throws when another thread interrupts
the current thread while sleep is active. Since
this application has not defined another
thread to cause the interrupt, it doesn't
bother to catch InterruptedException.
Communicating with Thread
• Interrupts
• An interrupt is an indication to a thread that it
should stop what it is doing and do something
else. It's up to the programmer to decide
exactly how a thread responds to an interrupt,
but it is very common for the thread to
terminate. This is the usage emphasized in this
lesson.
Interrupt requirement
• A thread sends an interrupt by invoking
interrupt on the Thread object for the thread
to be interrupted. For the interrupt
mechanism to work correctly, the interrupted
thread must support its own interruption.
Interrupt Status
• The interrupt mechanism is implemented
using an internal flag known as the interrupt
status. Invoking Thread.interrupt sets this flag.
When a thread checks for an interrupt by
invoking the static method
Thread.interrupted, interrupt status is cleared.
The non-static isInterrupted method, which is
used by one thread to query the interrupt
status of another, does not change the
interrupt status flag.
Interrupted Exception and Status
• By convention, any method that exits by
throwing an InterruptedException clears
interrupt status when it does so. However, it's
always possible that interrupt status will
immediately be set again, by another thread
invoking interrupt.
Thread Collaboration
• The join method allows one thread to wait for the
completion of another. If t is a Thread object whose
thread is currently executing,
• t.join();
• causes the current thread to pause execution until t's
thread terminates. Overloads of join allow the
programmer to specify a waiting period. However, as
with sleep, join is dependent on the OS for timing, so
you should not assume that join will wait exactly as
long as you specify.
• Like sleep, join responds to an interrupt by exiting with
an InterruptedException.
Thread Interruption Example
Synchronization
• Threads communicate primarily by sharing
access to fields and the objects reference
fields refer to. This form of communication is
extremely efficient, but makes two kinds of
errors possible: thread interference and
memory consistency errors. The tool needed
to prevent these errors is synchronization.
Synchronization Mechanisms
• Thread Interference describes how errors are introduced
when multiple threads access shared data.
• Memory Consistency Errors describes errors that result
from inconsistent views of shared memory.
• Synchronized Methods describes a simple idiom that can
effectively prevent thread interference and memory
consistency errors.
• Implicit Locks and Synchronization describes a more
general synchronization idiom, and describes how
synchronization is based on implicit locks.
• Atomic Access talks about the general idea of operations
that can't be interfered with by other threads.
Synchronization Libraries
Semaphores
Maintain count of the number of threads allowed to pass
Latches
Boolean conditions that are set once, ever
Barriers
Counters that cause all threads to wait until all have
finished
Reentrant Locks
Java-style locks allowing multiple acquisition by same
thread, but that may be acquired and released as needed
Mutexes
Non-reentrant locks
Read/Write Locks
Pairs of conditions in which the readLock may be shared,
but the writeLock is exclusive
Semaphores
Conceptually serve as permit holders
• Construct with an initial number of permits (usually 0)
• require waits for a permit to be available, then takes one
• release adds a permit But in normal implementations, no actual
permits change hands.
• The semaphore just maintains the current count.
• Enables very efficient implementation
Applications
• Isolating wait sets in buffers, resource controllers
• Designs that would otherwise encounter missed signals
— Where one thread signals before the other has even
started waiting
— Semaphores ‘remember’ how many times they were signalled
Counter Using Semaphores
class BoundedCounterUsingSemaphores {
long count_ = MIN;
Sync decPermits_= new Semaphore(0);
Sync incPermits_= new Semaphore(MAX-MIN);
synchronized long value() { return count_; }
void inc() throws InterruptedException {
incPermits_.acquire();
synchronized(this) { ++count_; }
decPermits_.release();
}
void dec() throws InterruptedException {
decPermits_.acquire();
synchronized(this) { --count_; }
incPermits_.release();
}
}
Using Latches
• Conditions starting out false, but once set
true, remain true forever
• Initialization flags
• End-of-stream conditions
• Thread termination
• Event occurrence
Using Barrier Conditions
Count-based latches
• Initialize with a fixed count
• Each release monotonically decrements count
• All acquires pass when count reaches zero
Liveness
• A concurrent application's ability to execute in
a timely manner is known as its liveness. This
section describes the most common kind of
liveness problem, deadlock, and goes on to
briefly describe two other liveness problems,
starvation and livelock.
Deadlock
• Deadlock describes a situation where two or
more threads are blocked forever, waiting for
each other. Here's an example.
• Alphonse and Gaston are friends, and great
believers in courtesy. A strict rule of courtesy is
that when you bow to a friend, you must remain
bowed until your friend has a chance to return
the bow. Unfortunately, this rule does not
account for the possibility that two friends might
bow to each other at the same time.
Starvation and Livelock
• Starvation describes a situation where a thread is
unable to gain regular access to shared resources
and is unable to make progress. This happens
when shared resources are made unavailable for
long periods by "greedy" threads.
• A thread often acts in response to the action of
another thread. If the other thread's action is also
a response to the action of another thread, then
livelock may result.
Guarded Blocks
• Threads often have to coordinate their
actions. The most common coordination idiom
is the guarded block. Such a block begins by
polling a condition that must be true before
the block can proceed. There are a number of
steps to follow in order to do this correctly.
Guarded Block (cont..)
• Constant polling for Condition
• Use wait/notify method
• Immutable Objects
• Producer Consumer Example
• A Synchronized Class Example
Immutable Object
1. Don't provide "setter" methods — methods that modify fields or
objects referred to by fields.
2. Make all fields final and private.
3. Don't allow subclasses to override methods. The simplest way to
do this is to declare the class as final. A more sophisticated
approach is to make the constructor private and construct
instances in factory methods.
4. If the instance fields include references to mutable objects, don't
allow those objects to be changed:
– Don't provide methods that modify the mutable objects.
– Don't share references to the mutable objects. Never store
references to external, mutable objects passed to the constructor; if
necessary, create copies, and store references to the copies.
Similarly, create copies of your internal mutable objects when
necessary to avoid returning the originals in your methods.
High Level Concurrency Objects
• Lock objects support locking idioms that simplify many
concurrent applications.
• Executors define a high-level API for launching and
managing threads. Executor implementations provided by
java.util.concurrent provide thread pool management
suitable for large-scale applications.
• Concurrent collections make it easier to manage large
collections of data, and can greatly reduce the need for
synchronization.
• Atomic variables have features that minimize
synchronization and help avoid memory consistency errors.
• ThreadLocalRandom (in JDK 7) provides efficient generation
of pseudorandom numbers from multiple threads.
Lock Objects
• Only one thread can own a implicit Lock object at a
time. Lock objects also support a wait/notify
mechanism, through their associated Condition
objects.
• The biggest advantage of Lock objects over implicit
locks is their ability to back out of an attempt to
acquire a lock. The tryLock method backs out if the
lock is not available immediately or before a timeout
expires (if specified). The lockInterruptibly method
backs out if another thread sends an interrupt before
the lock is acquired.
Locks Illustration
Executors
• In large-scale applications, it makes sense to
separate thread management and creation from
the rest of the application. Objects that
encapsulate these functions are known as
executors.
• Executor Interfaces define the three executor
object types.
• Thread Pools are the most common kind of
executor implementation.
• Fork/Join is a framework (new in JDK 7) for taking
advantage of multiple processors.
Executor Interfaces
• The java.util.concurrent package defines three
executor interfaces:
• Executor, a simple interface that supports
launching new tasks.
• ExecutorService, a subinterface of Executor,
which adds features that help manage the
lifecycle, both of the individual tasks and of the
executor itself.
• ScheduledExecutorService, a subinterface of
ExecutorService, supports future and/or periodic
execution of tasks.
The Executor Interface
• The Executor interface provides a single
method, execute, designed to be a drop-in
replacement for a common thread-creation
idiom. If r is a Runnable object, and e is an
Executor object you can replace
• (new Thread(r)).start();
• with
• e.execute(r);
The ExecutorService Interface
• The ExecutorService interface supplements execute with
a similar, but more versatile submit method. Like
execute, submit accepts Runnable objects, but also
accepts Callable objects, which allow the task to return a
value. The submit method returns a Future object, which
is used to retrieve the Callable return value and to
manage the status of both Callable and Runnable tasks.
• ExecutorService also provides methods for submitting
large collections of Callable objects. Finally,
ExecutorService provides a number of methods for
managing the shutdown of the executor. To support
immediate shutdown, tasks should handle interrupts
correctly.
The ScheduledExecutorService
Interface
• The ScheduledExecutorService interface
supplements the methods of its parent
ExecutorService with schedule, which
executes a Runnable or Callable task after a
specified delay. In addition, the interface
defines scheduleAtFixedRate and
scheduleWithFixedDelay, which executes
specified tasks repeatedly, at defined intervals.
Thread Pools
• Using worker threads minimizes the overhead
due to thread creation. Thread objects use a
significant amount of memory, and in a large-
scale application, allocating and deallocating
many thread objects creates a significant
memory management overhead.
• Tasks are submitted to the pool via an internal
queue, which holds extra tasks whenever
there are more active tasks than threads.
Thread Pools
• newFixedThreadPool
• newCachedThreadPool
• newSingleThreadExecutor
• For customized needs one can construct
• java.util.concurrent.ThreadPoolExecutor or
java.util.concurrent.ScheduledThreadPoolExec
utor
Fork/Join
• The fork/join framework is an implementation
of the ExecutorService interface that helps you
take advantage of multiple processors. It is
designed for work that can be broken into
smaller pieces recursively. The goal is to use all
the available processing power to enhance the
performance of your application.
Basic Use
• if (my portion of the work is small enough)
– do the work directly
• else
– split my work into two pieces
– invoke the two pieces and wait for the results
• After your ForkJoinTask is ready, create one that
represents all the work to be done and pass it to
the invoke() method of a ForkJoinPool instance.
Concurrent Collections
• The java.util.concurrent package includes a
number of additions to the Java Collections
Framework
• BlockingQueue
• ConcurrentMap
• ConcurrentSkipList
• All of these collections help avoid Memory
Consistency Errors by defining a happens-before
relationship between an operation that adds an
object to the collection with subsequent
operations that access or remove that object.
Atomic Variables
• The java.util.concurrent.atomic package
defines classes that support atomic operations
on single variables. All classes have get and set
methods that work like reads and writes on
volatile variables.
Concurrent Random Numbers
• In JDK 7, java.util.concurrent includes a
convenience class, ThreadLocalRandom, for
applications that expect to use random
numbers from multiple threads or
ForkJoinTasks.
• int r = ThreadLocalRandom.current()
.nextInt(4, 77);
Designing Objects for
Concurrency
Patterns for safely representing and managing state
Immutability
• Avoiding interference by avoiding change
Locking
• Guaranteeing exclusive access
State dependence
• What to do when you can’t do anything
Containment
• Hiding internal objects
Splitting
• Separating independent aspects of objects and locks

More Related Content

What's hot

Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Young-Ho Cho
 
Enterprise manager 13c
Enterprise manager 13cEnterprise manager 13c
Enterprise manager 13c
MarketingArrowECS_CZ
 
Mutiny + quarkus
Mutiny + quarkusMutiny + quarkus
Mutiny + quarkus
Edgar Domingues
 
Java Performance Monitoring & Tuning
Java Performance Monitoring & TuningJava Performance Monitoring & Tuning
Java Performance Monitoring & Tuning
Muhammed Shakir
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
Java Collections
Java  Collections Java  Collections
DynamoDB & DAX
DynamoDB & DAXDynamoDB & DAX
DynamoDB & DAX
Amazon Web Services
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
Edureka!
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Monolithic architecture
Monolithic architectureMonolithic architecture
Monolithic architecture
SRM University Delhi-NCR sonepat
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architectureAmit Bhalla
 
Google guava
Google guavaGoogle guava
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
Juan Medina
 
Oracle backup and recovery
Oracle backup and recoveryOracle backup and recovery
Oracle backup and recoveryYogiji Creations
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruitersph7 -
 
Smooth as Silk Exadata Patching
Smooth as Silk Exadata PatchingSmooth as Silk Exadata Patching
Smooth as Silk Exadata Patching
Fahd Mirza Chughtai
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Enterprise Manager: Write powerful scripts with EMCLI
Enterprise Manager: Write powerful scripts with EMCLIEnterprise Manager: Write powerful scripts with EMCLI
Enterprise Manager: Write powerful scripts with EMCLI
Gokhan Atil
 
Spring beans
Spring beansSpring beans
Spring beans
Roman Dovgan
 

What's hot (20)

Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Enterprise manager 13c
Enterprise manager 13cEnterprise manager 13c
Enterprise manager 13c
 
Mutiny + quarkus
Mutiny + quarkusMutiny + quarkus
Mutiny + quarkus
 
Java Performance Monitoring & Tuning
Java Performance Monitoring & TuningJava Performance Monitoring & Tuning
Java Performance Monitoring & Tuning
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
DynamoDB & DAX
DynamoDB & DAXDynamoDB & DAX
DynamoDB & DAX
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Monolithic architecture
Monolithic architectureMonolithic architecture
Monolithic architecture
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
 
Google guava
Google guavaGoogle guava
Google guava
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Oracle backup and recovery
Oracle backup and recoveryOracle backup and recovery
Oracle backup and recovery
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruiters
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Smooth as Silk Exadata Patching
Smooth as Silk Exadata PatchingSmooth as Silk Exadata Patching
Smooth as Silk Exadata Patching
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Enterprise Manager: Write powerful scripts with EMCLI
Enterprise Manager: Write powerful scripts with EMCLIEnterprise Manager: Write powerful scripts with EMCLI
Enterprise Manager: Write powerful scripts with EMCLI
 
Spring beans
Spring beansSpring beans
Spring beans
 

Viewers also liked

Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
Victor Rentea
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
Marut Singh
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
Marut Singh
 
Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
Marut Singh
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
Tobias Lindaaker
 
What is concurrency
What is concurrencyWhat is concurrency
What is concurrency
lodhran-hayat
 
Java8
Java8Java8
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
Dhaval Dalal
 
Apache camel
Apache camelApache camel
Apache camel
Marut Singh
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
Ramazan AYYILDIZ
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
Alexander Pashynskiy
 
Why Transcriptome? Why RNA-Seq? ENCODE answers….
Why Transcriptome? Why RNA-Seq?  ENCODE answers….Why Transcriptome? Why RNA-Seq?  ENCODE answers….
Why Transcriptome? Why RNA-Seq? ENCODE answers….
Mohammad Hossein Banabazi
 
AngularJS2
AngularJS2AngularJS2
AngularJS2
Carlos Uscamayta
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Concurrency
ConcurrencyConcurrency
Concurrency
Isaac Liao
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 

Viewers also liked (20)

Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java8 training - class 3
Java8 training - class 3Java8 training - class 3
Java8 training - class 3
 
Java8 training - Class 1
Java8 training  - Class 1Java8 training  - Class 1
Java8 training - Class 1
 
Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
 
What is concurrency
What is concurrencyWhat is concurrency
What is concurrency
 
Java8
Java8Java8
Java8
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Apache camel
Apache camelApache camel
Apache camel
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
 
Why Transcriptome? Why RNA-Seq? ENCODE answers….
Why Transcriptome? Why RNA-Seq?  ENCODE answers….Why Transcriptome? Why RNA-Seq?  ENCODE answers….
Why Transcriptome? Why RNA-Seq? ENCODE answers….
 
AngularJS2
AngularJS2AngularJS2
AngularJS2
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 

Similar to Concurrency with java

Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Java
JavaJava
Java
JavaJava
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
JanmejayaPadhiary2
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
MuhammadBilal187526
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
ajmalhamidi1380
 

Similar to Concurrency with java (20)

Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Java threading
Java threadingJava threading
Java threading
 
multithreading
multithreadingmultithreading
multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 

More from Hoang Nguyen

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
Hoang Nguyen
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
Hoang Nguyen
 
Api crash
Api crashApi crash
Api crash
Hoang Nguyen
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
Hoang Nguyen
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
Hoang Nguyen
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
Hoang Nguyen
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
Hoang Nguyen
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
Hoang Nguyen
 
Cache recap
Cache recapCache recap
Cache recap
Hoang Nguyen
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
Hoang Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
Hoang Nguyen
 
Learning python
Learning pythonLearning python
Learning python
Hoang Nguyen
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
Hoang Nguyen
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
Hoang Nguyen
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
Hoang Nguyen
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
Hoang Nguyen
 
Object model
Object modelObject model
Object model
Hoang Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Hoang Nguyen
 

More from Hoang Nguyen (20)

Rest api to integrate with your site
Rest api to integrate with your siteRest api to integrate with your site
Rest api to integrate with your site
 
How to build a rest api
How to build a rest apiHow to build a rest api
How to build a rest api
 
Api crash
Api crashApi crash
Api crash
 
Smm and caching
Smm and cachingSmm and caching
Smm and caching
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Cache recap
Cache recapCache recap
Cache recap
 
Python your new best friend
Python your new best friendPython your new best friend
Python your new best friend
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python basics
Python basicsPython basics
Python basics
 
Programming for engineers in python
Programming for engineers in pythonProgramming for engineers in python
Programming for engineers in python
 
Learning python
Learning pythonLearning python
Learning python
 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Object model
Object modelObject model
Object model
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 

Recently uploaded

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 

Recently uploaded (20)

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 

Concurrency with java

  • 1. Programming Paradigms • Single Process • Multi Process • Multi Core/Multi Thread
  • 3. Process • Process A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time.
  • 4. Java Process Objects • ADTs, aggregate components, JavaBeans, monitors, business objects, remote RMI objects, subsystems, ... • May be grouped according to structure, role, ... • Usable across multiple activities — focus on SAFETY Activities • Messages, call chains, threads, sessions, scenarios, scripts, workflows, use cases, transactions, data flows, mobile computations
  • 5. Thread • Threads are so called lightweight processes which have their own call stack but an access shared data. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data
  • 6. What is The Gain • Amdahl's Law • It states that a small portion of the program which cannot be parallelized will limit the overall speed-up available from parallelization. • A program solving a large mathematical or engineering problem will typically consist of several parallelizable parts and several non-parallelizable (sequential) parts. If p is the fraction of running time a sequential program spends on non-parallelizable parts, then • S = 1/p
  • 7. How much is the speed up • If the sequential portion of a program accounts for 10% of the runtime, we can get no more than a 10× speed-up, regardless of how many processors are added. This puts an upper limit on the usefulness of adding more parallel execution units. "When a task cannot be partitioned because of sequential constraints, the application of more effort has no effect on the schedule. The bearing of a child takes nine months, no matter how many women are assigned
  • 8. How does Java help to Parallel Programming • Has Threads since its inception • Threads have their own stack. But uses heap of the JVM • Has many constructs to control the concurrency • Programmer knowledge is very critical
  • 10. Thread Class Constructors • Thread(Runnable r) constructs so run() calls r.run() • — Other versions allow names, ThreadGroup placement Principal methods • start() activates run() then returns to caller • isAlive() returns true if started but not stopped • join() waits for termination (optional timeout) • interrupt() breaks out of wait, sleep, or join • isInterrupted() returns interruption state • getPriority() returns current scheduling priority • setPriority(int priorityFromONEtoTEN) sets it
  • 11. How to Implement a Thread • Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run
  • 12. Thread Subclass public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
  • 13. Implement Runnable Interface public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloRunnable()).start(); } }
  • 14. Pausing while executing • Thread.sleep causes the current thread to suspend execution for a specified period. • This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing
  • 15. Thread Management • To directly control thread creation and management, simply instantiate Thread each time the application needs to initiate an asynchronous task. • To abstract thread management from the rest of your application, pass the application's tasks to an executor.
  • 16. Sleep Example • main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.
  • 17. Communicating with Thread • Interrupts • An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.
  • 18. Interrupt requirement • A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.
  • 19. Interrupt Status • The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.
  • 20. Interrupted Exception and Status • By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
  • 21. Thread Collaboration • The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, • t.join(); • causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify. • Like sleep, join responds to an interrupt by exiting with an InterruptedException.
  • 23. Synchronization • Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
  • 24. Synchronization Mechanisms • Thread Interference describes how errors are introduced when multiple threads access shared data. • Memory Consistency Errors describes errors that result from inconsistent views of shared memory. • Synchronized Methods describes a simple idiom that can effectively prevent thread interference and memory consistency errors. • Implicit Locks and Synchronization describes a more general synchronization idiom, and describes how synchronization is based on implicit locks. • Atomic Access talks about the general idea of operations that can't be interfered with by other threads.
  • 25. Synchronization Libraries Semaphores Maintain count of the number of threads allowed to pass Latches Boolean conditions that are set once, ever Barriers Counters that cause all threads to wait until all have finished Reentrant Locks Java-style locks allowing multiple acquisition by same thread, but that may be acquired and released as needed Mutexes Non-reentrant locks Read/Write Locks Pairs of conditions in which the readLock may be shared, but the writeLock is exclusive
  • 26. Semaphores Conceptually serve as permit holders • Construct with an initial number of permits (usually 0) • require waits for a permit to be available, then takes one • release adds a permit But in normal implementations, no actual permits change hands. • The semaphore just maintains the current count. • Enables very efficient implementation Applications • Isolating wait sets in buffers, resource controllers • Designs that would otherwise encounter missed signals — Where one thread signals before the other has even started waiting — Semaphores ‘remember’ how many times they were signalled
  • 27. Counter Using Semaphores class BoundedCounterUsingSemaphores { long count_ = MIN; Sync decPermits_= new Semaphore(0); Sync incPermits_= new Semaphore(MAX-MIN); synchronized long value() { return count_; } void inc() throws InterruptedException { incPermits_.acquire(); synchronized(this) { ++count_; } decPermits_.release(); } void dec() throws InterruptedException { decPermits_.acquire(); synchronized(this) { --count_; } incPermits_.release(); } }
  • 28. Using Latches • Conditions starting out false, but once set true, remain true forever • Initialization flags • End-of-stream conditions • Thread termination • Event occurrence
  • 29. Using Barrier Conditions Count-based latches • Initialize with a fixed count • Each release monotonically decrements count • All acquires pass when count reaches zero
  • 30. Liveness • A concurrent application's ability to execute in a timely manner is known as its liveness. This section describes the most common kind of liveness problem, deadlock, and goes on to briefly describe two other liveness problems, starvation and livelock.
  • 31. Deadlock • Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example. • Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.
  • 32. Starvation and Livelock • Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. • A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.
  • 33. Guarded Blocks • Threads often have to coordinate their actions. The most common coordination idiom is the guarded block. Such a block begins by polling a condition that must be true before the block can proceed. There are a number of steps to follow in order to do this correctly.
  • 34. Guarded Block (cont..) • Constant polling for Condition • Use wait/notify method • Immutable Objects • Producer Consumer Example • A Synchronized Class Example
  • 35. Immutable Object 1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. 2. Make all fields final and private. 3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods. 4. If the instance fields include references to mutable objects, don't allow those objects to be changed: – Don't provide methods that modify the mutable objects. – Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
  • 36. High Level Concurrency Objects • Lock objects support locking idioms that simplify many concurrent applications. • Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications. • Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization. • Atomic variables have features that minimize synchronization and help avoid memory consistency errors. • ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
  • 37. Lock Objects • Only one thread can own a implicit Lock object at a time. Lock objects also support a wait/notify mechanism, through their associated Condition objects. • The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock. The tryLock method backs out if the lock is not available immediately or before a timeout expires (if specified). The lockInterruptibly method backs out if another thread sends an interrupt before the lock is acquired.
  • 39. Executors • In large-scale applications, it makes sense to separate thread management and creation from the rest of the application. Objects that encapsulate these functions are known as executors. • Executor Interfaces define the three executor object types. • Thread Pools are the most common kind of executor implementation. • Fork/Join is a framework (new in JDK 7) for taking advantage of multiple processors.
  • 40. Executor Interfaces • The java.util.concurrent package defines three executor interfaces: • Executor, a simple interface that supports launching new tasks. • ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself. • ScheduledExecutorService, a subinterface of ExecutorService, supports future and/or periodic execution of tasks.
  • 41. The Executor Interface • The Executor interface provides a single method, execute, designed to be a drop-in replacement for a common thread-creation idiom. If r is a Runnable object, and e is an Executor object you can replace • (new Thread(r)).start(); • with • e.execute(r);
  • 42. The ExecutorService Interface • The ExecutorService interface supplements execute with a similar, but more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks. • ExecutorService also provides methods for submitting large collections of Callable objects. Finally, ExecutorService provides a number of methods for managing the shutdown of the executor. To support immediate shutdown, tasks should handle interrupts correctly.
  • 43. The ScheduledExecutorService Interface • The ScheduledExecutorService interface supplements the methods of its parent ExecutorService with schedule, which executes a Runnable or Callable task after a specified delay. In addition, the interface defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.
  • 44. Thread Pools • Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large- scale application, allocating and deallocating many thread objects creates a significant memory management overhead. • Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.
  • 45. Thread Pools • newFixedThreadPool • newCachedThreadPool • newSingleThreadExecutor • For customized needs one can construct • java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExec utor
  • 46. Fork/Join • The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.
  • 47. Basic Use • if (my portion of the work is small enough) – do the work directly • else – split my work into two pieces – invoke the two pieces and wait for the results • After your ForkJoinTask is ready, create one that represents all the work to be done and pass it to the invoke() method of a ForkJoinPool instance.
  • 48. Concurrent Collections • The java.util.concurrent package includes a number of additions to the Java Collections Framework • BlockingQueue • ConcurrentMap • ConcurrentSkipList • All of these collections help avoid Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that access or remove that object.
  • 49. Atomic Variables • The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables.
  • 50. Concurrent Random Numbers • In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom, for applications that expect to use random numbers from multiple threads or ForkJoinTasks. • int r = ThreadLocalRandom.current() .nextInt(4, 77);
  • 51. Designing Objects for Concurrency Patterns for safely representing and managing state Immutability • Avoiding interference by avoiding change Locking • Guaranteeing exclusive access State dependence • What to do when you can’t do anything Containment • Hiding internal objects Splitting • Separating independent aspects of objects and locks