SlideShare a Scribd company logo
1 of 51
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

Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
Ā 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
Ā 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
Ā 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
Ā 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
Ā 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
Ā 
multithreading
multithreadingmultithreading
multithreadingRajkattamuri
Ā 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
Ā 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
Ā 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreadingRakesh Madugula
Ā 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
Ā 
Multithreading
MultithreadingMultithreading
MultithreadingF K
Ā 

What's hot (16)

Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Ā 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
Ā 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
Ā 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Ā 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Ā 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Ā 
multithreading
multithreadingmultithreading
multithreading
Ā 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Ā 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
Ā 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Ā 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Ā 
Java
JavaJava
Java
Ā 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ā 
Java
JavaJava
Java
Ā 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Ā 
Multithreading
MultithreadingMultithreading
Multithreading
Ā 

Similar to Concurrency with java

Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
Ā 
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.pptxsandhyakiran10
Ā 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
Ā 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
Ā 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
Ā 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
Ā 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
Ā 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
Ā 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
Ā 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptxajmalhamidi1380
Ā 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
Ā 
Operating system 27 semaphores
Operating system 27 semaphoresOperating system 27 semaphores
Operating system 27 semaphoresVaibhav Khanna
Ā 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
Ā 
Advanced python
Advanced pythonAdvanced python
Advanced pythonNovita Sari
Ā 

Similar to Concurrency with java (20)

Java threading
Java threadingJava threading
Java threading
Ā 
Java multithreading
Java multithreadingJava multithreading
Java 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
Ā 
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
Ā 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Ā 
Operating system 27 semaphores
Operating system 27 semaphoresOperating system 27 semaphores
Operating system 27 semaphores
Ā 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
Ā 
Advanced python
Advanced pythonAdvanced python
Advanced python
Ā 
Thread
ThreadThread
Thread
Ā 
Thread
ThreadThread
Thread
Ā 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
Ā 

More from Tony Nguyen

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisTony Nguyen
Ā 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceTony Nguyen
Ā 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningTony Nguyen
Ā 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningTony Nguyen
Ā 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryTony Nguyen
Ā 
Cache recap
Cache recapCache recap
Cache recapTony Nguyen
Ā 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksTony Nguyen
Ā 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheTony Nguyen
Ā 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesTony Nguyen
Ā 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsTony Nguyen
Ā 
Abstract class
Abstract classAbstract class
Abstract classTony Nguyen
Ā 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileTony Nguyen
Ā 
Object model
Object modelObject model
Object modelTony Nguyen
Ā 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsTony Nguyen
Ā 
Inheritance
InheritanceInheritance
InheritanceTony Nguyen
Ā 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaTony Nguyen
Ā 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonTony Nguyen
Ā 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with pythonTony Nguyen
Ā 
Learning python
Learning pythonLearning python
Learning pythonTony Nguyen
Ā 

More from Tony Nguyen (20)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
Ā 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
Ā 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
Ā 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
Ā 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
Ā 
Cache recap
Cache recapCache recap
Cache recap
Ā 
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
Ā 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Ā 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
Ā 
Abstract class
Abstract classAbstract class
Abstract class
Ā 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
Ā 
Object model
Object modelObject model
Object model
Ā 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Ā 
Inheritance
InheritanceInheritance
Inheritance
Ā 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
Ā 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
Ā 
Extending burp with python
Extending burp with pythonExtending burp with python
Extending burp with python
Ā 
Api crash
Api crashApi crash
Api crash
Ā 
Learning python
Learning pythonLearning python
Learning python
Ā 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
Ā 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
Ā 
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Commit University
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Ā 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
Ā 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
Ā 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
Ā 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
Ā 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
Ā 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
Ā 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
Ā 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
Ā 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
Ā 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
Ā 

Recently uploaded (20)

Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort ServiceHot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Ā 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
Ā 
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Ā 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
Ā 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
Ā 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
Ā 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
Ā 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
Ā 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Ā 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
Ā 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
Ā 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Ā 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
Ā 

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