SlideShare a Scribd company logo
Concurrent
Programming
05
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Today…
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Today’s Session
• Processes and Threads
• Thread Objects
• Defining and Starting a Thread
• Pausing Execution with Sleep
• Interrupts
• Joins
• The SimpleThreads Example
• Synchronization
• Thread Interference
• Memory Consistency Errors
Processes & Threads
Process
• has a self-contained execution environment
• generally has a complete, private set of basic run-time resources
• each process has its own memory space
• Inter Process Communication (IPC)
• pipes
• sockets
• Most implementations of the Java virtual machine run as a single
process
Thread
• lightweight processes
• provide an execution environment
• requires fewer resources than creating a new process
• exist within a process
• every process has at least one - main thread
• share the process's resources, including memory and
open files
Thread Objects
Thread Objects
• Each thread is associated with an instance of the class ‘Thread’.
• basic strategies for using Thread objects to create a concurrent
application.
• 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’.
• for now we will use Thread objects.
Defining & Running a Thread
• An application that creates an instance of ‘Thread’ must provide the code that will run in
that thread.
• There are two ways to do this:
• Provide a Runnable object.
• The Runnable interface defines a single method, run, meant to contain the code
executed in the thread.
• The Runnable object is passed to the Thread constructor.
• 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.
Using a Runnable Object
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Using a Subclass of Thread
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Runnable Object vs Thread
Subclass
• both invoke thread.start() to start a new thread
• creating a Runnable Object
• can subclass a class other than Thread
• separates Runnable task from Thread object
• more flexible
• applicable to high-level thread management APIs
• creating a Thread subclass
• is easier to use in simple applications
• is limited cause the task class must be a descendant of Thread
Thread Class
• The Thread class defines a number of methods useful for
thread management.
• These include static methods, which
• provide information about, or
• affect the status of,
• the thread invoking the method.
• The other methods are invoked from other threads involved
in managing the thread and Thread object.
Pausing Execution with
Sleep
• Thread.sleep causes the current thread to suspend
execution for a specified period.
• making processor time available to the other threads of an
application or other applications
• The sleep method can also be used for
• pacing (rate of movement/activity), and
• waiting for another thread
• with duties that are understood to have time requirements
Pausing Execution with
Sleep Cont.d
• Two overloaded versions of sleep are provided:
• one that specifies the sleep time to the millisecond
• and one that specifies the sleep time to the nanosecond.
• sleep times are not guaranteed to be precise
• limited by the facilities provided by the underlying OS
• sleep period can be terminated by interrupts
• In any case, you cannot assume that invoking sleep will suspend
the thread for precisely the time period specified.
Sleep Example
public class SleepMessages {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
for (int i = 0;
i < importantInfo.length;
i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
}
}
}
Sleep Example Cont.d
• This example uses sleep to print messages at four-
second intervals
• main declares that it throws InterruptedException.
• exception thrown 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
Interrupts
• 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
• 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.
Supporting Interruption
• How does a thread support its own interruption?
• depends on what it's currently doing.
• If the thread is frequently invoking methods that throw
InterruptedException, it simply returns from the run method
after it catches that exception.
• For example, suppose the central message loop in the
SleepMessages example were in the run method of a
thread's Runnable object.
• Then it might be modified as follows to support interrupts:
Supporting Interruption
Cont.d
for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
// Print a message
System.out.println(importantInfo[i]);
}
Supporting Interruption
Cont.d
• Many methods that throw InterruptedException, such as
sleep, are designed to cancel their current operation and
return immediately when an interrupt is received.
• What if a thread goes a long time without invoking a
method that throws InterruptedException?
• Then it must periodically invoke Thread.interrupted,
• which returns true if an interrupt has been received.
Supporting Interruption
Cont.d
for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}
Supporting Interruption
Cont.d
• In this simple example, the code simply tests for the interrupt and
exits the thread if one has been received.
• In more complex applications, it might make more sense to throw
an InterruptedException:
• This allows interrupt handling code to be centralized in a catch
clause.
if (Thread.interrupted()) {
throw new InterruptedException();
}
Interrupt Status Flag
• 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.
• 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.
Joins
• The join method allows one thread to wait for the completion of another.
• If t is a Thread object whose thread is currently executing,
• causes the current thread to pause execution until t's thread terminates.
• Overloads of join allow the programmer to specify a waiting period.
• similar to sleep, join is dependent on the OS for timing
• 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.
t.join();
Simple Threads Example
• SimpleThreads consists of two threads.
• The first is the main thread that every Java application has.
• main thread creates a new thread from the Runnable object,
MessageLoop, and waits for it to finish.
• If the MessageLoop thread takes too long to finish, the main thread
interrupts it.
• The MessageLoop thread prints out a series of messages.
• If interrupted before it has printed all its messages, the
MessageLoop thread prints a message and exits.
Synchronization
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:
• thread interference
• memory consistency errors.
• The tool needed to prevent these errors is synchronization.
Synchronization Cont.d
• However, synchronization can introduce thread
contention
• when two or more threads try to access the same
resource simultaneously and cause the Java runtime
to
• execute one or more threads more slowly
• or even suspend their execution.
• Starvation and livelock are forms of thread contention.
Synchronization Cont.d
• 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.
Thread Interference
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
Thread Interference Cont.d
• Counter is designed so that each invocation of increment will
add 1 to c, and each invocation of decrement will subtract 1
from c.
• However, if a Counter object is referenced from multiple
threads, interference between threads may prevent this from
happening as expected.
• Interference happens when two operations, running in different
threads, but acting on the same data, interleave.
• This means that the two operations consist of multiple steps,
and the sequences of steps overlap.
Thread Interference Cont.d
• It might not seem possible for operations on instances of Counter to interleave,
since both operations on c are single, simple statements.
• However, even simple statements can translate to multiple steps by the virtual
machine.
• We won't examine the specific steps the virtual machine takes — it is enough to
know that the single expression c++ can be decomposed into three steps:
• Retrieve the current value of c.
• Increment the retrieved value by 1.
• Store the incremented value back in c.
• The expression c-- can be decomposed the same way, except that the second
step decrements instead of increments.
Thread Interference Contd.
• If Thread A invokes increment at about the same time Thread B invokes decrement.
• If the initial value of c is 0, their interleaved actions might follow this sequence:
• Thread A: Retrieve c.
• Thread B: Retrieve c.
• Thread A: Increment retrieved value; result is 1.
• Thread B: Decrement retrieved value; result is -1.
• Thread A: Store result in c; c is now 1.
• Thread B: Store result in c; c is now -1.
• Thread A's result is lost, overwritten by Thread B.
• This particular interleaving is only one possibility.
• Under different circumstances it might be Thread B's result that gets lost, or there could be no error at all.
• Because they are unpredictable, thread interference bugs can be difficult to detect and fix.
Memory Consistence Errors
• occur when different threads have inconsistent views of what should be
the same data.
• causes are complex and beyond the scope of this tutorial.
• programmer does not need a detailed understanding of these causes.
• All that is needed is a strategy for avoiding them.
• The key to avoiding memory consistency errors is understanding the
happens-before relationship.
• This is simply a guarantee that memory writes by one specific statement
are visible to another specific statement.
• To see this, consider the following example.
Memory Consistence Errors
Cont.d
• Suppose a simple int field is defined and initialized:
• Then, shortly afterwards, thread B prints out counter:
• If the two statements had been executed in the same thread, the value printed out would be "1".
• But if the two statements are executed in separate threads, the value printed out might well be "0",
• because there's no guarantee that thread A's change to counter will be visible to thread B
• unless the programmer has established a happens-before relationship between these two
statements.
• There are several actions that create happens-before relationships.
• One of them is synchronization
int counter = 0;
System.out.println(counter);
Memory Consistence Errors
Cont.d
• We've already seen two actions that create happens-before relationships.
• When a statement invokes Thread.start,
• every statement that has a happens-before relationship with that statement
• also has a happens-before relationship with every statement executed by the new
thread.
• effects of the code that led up to the creation of the new thread are visible to the new
thread.
• When a thread terminates and causes a Thread.join in another thread to return,
• then all the statements executed by the terminated thread have a happens-before
relationship with all the statements following the successful join.
• effects of the code in the thread are now visible to the thread that performed the join.
Next…
Next Up…
• Synchronization
• Synchronized Methods
• Intrinsic Locks and Synchronization
• Atomic Access
• Liveness
• Deadlock
• Starvation and Livelock
References
• http://docs.oracle.com/javase/tutorial/essential/
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Thank you.
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg

More Related Content

What's hot (16)

Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
.Net Threading
.Net Threading.Net Threading
.Net Threading
Erik Ralston
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
xuehan zhu
 
C# Thread synchronization
C# Thread synchronizationC# Thread synchronization
C# Thread synchronization
Prem Kumar Badri
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan zhu
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Sachintha Gunasena
 
multi threading
multi threadingmulti threading
multi threading
Yaswanth Babu Gummadivelli
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
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
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Java
JavaJava
Java
Khasim Cise
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Java
JavaJava
Java
mdfkhan625
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
Tim Penhey
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
xuehan zhu
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan zhu
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Sachintha Gunasena
 
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
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
Tim Penhey
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 

Viewers also liked (19)

javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
FM - JESSIE J
FM - JESSIE JFM - JESSIE J
FM - JESSIE J
Bianca Barbosa
 
7391
73917391
7391
ivanov156635995534
 
10734
1073410734
10734
ivanov156635995534
 
10657
1065710657
10657
ivanov156635995534
 
10669
1066910669
10669
ivanov156635995534
 
Market research-v2
Market research-v2Market research-v2
Market research-v2
Vetle Andre Remme Olsen
 
High speed disperser manufacturer in india
High speed disperser manufacturer in indiaHigh speed disperser manufacturer in india
High speed disperser manufacturer in india
galaxyprocess
 
10759
1075910759
10759
ivanov156635995534
 
LA INVESTIGACIÓN ACCIÓN EDUCATIVA
LA INVESTIGACIÓN ACCIÓN EDUCATIVALA INVESTIGACIÓN ACCIÓN EDUCATIVA
LA INVESTIGACIÓN ACCIÓN EDUCATIVA
YONY RAFAEL HUAMANI
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
jehan1987
 
Erosion and Deposition
Erosion and DepositionErosion and Deposition
Erosion and Deposition
Aia-Issah Orquiola
 
Java threads - part 3
Java threads - part 3Java threads - part 3
Java threads - part 3
Nakraynikov Oleg
 
Qué cambia en el modelo 190 en 2017
Qué cambia en el modelo 190 en 2017Qué cambia en el modelo 190 en 2017
Qué cambia en el modelo 190 en 2017
Sage España
 
High–Performance Computing
High–Performance ComputingHigh–Performance Computing
High–Performance Computing
BRAC University Computer Club
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Ad

Similar to Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects, Thread Start, Sleep, Interrupt (20)

Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Luis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
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
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
MSBTE Computer Engineering  JPR java.  multi. threading.pptxMSBTE Computer Engineering  JPR java.  multi. threading.pptx
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Luis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
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
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
MSBTE Computer Engineering  JPR java.  multi. threading.pptxMSBTE Computer Engineering  JPR java.  multi. threading.pptx
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Ad

More from Sachintha Gunasena (16)

Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Entrepreneurship and Commerce in IT - 14 - Web Marketing CommunicationsEntrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 12 - Web Payments
Entrepreneurship & Commerce in IT - 12 - Web PaymentsEntrepreneurship & Commerce in IT - 12 - Web Payments
Entrepreneurship & Commerce in IT - 12 - Web Payments
Sachintha Gunasena
 
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Concurrency Programming in Java - 03 - Essentials of Java Part 2Concurrency Programming in Java - 03 - Essentials of Java Part 2
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Sachintha Gunasena
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Entrepreneurship & Commerce in IT - 11 - Security & EncryptionEntrepreneurship & Commerce in IT - 11 - Security & Encryption
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and conceptsEntrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide webEntrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Entrepreneurship and Commerce in IT - 14 - Web Marketing CommunicationsEntrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 12 - Web Payments
Entrepreneurship & Commerce in IT - 12 - Web PaymentsEntrepreneurship & Commerce in IT - 12 - Web Payments
Entrepreneurship & Commerce in IT - 12 - Web Payments
Sachintha Gunasena
 
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Concurrency Programming in Java - 03 - Essentials of Java Part 2Concurrency Programming in Java - 03 - Essentials of Java Part 2
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Sachintha Gunasena
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Entrepreneurship & Commerce in IT - 11 - Security & EncryptionEntrepreneurship & Commerce in IT - 11 - Security & Encryption
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and conceptsEntrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide webEntrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Sachintha Gunasena
 
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Sachintha Gunasena
 
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Sachintha Gunasena
 

Recently uploaded (20)

Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration KeySmadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdfHow to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdfLooking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWSWomen in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Making significant Software Architecture decisions
Making significant Software Architecture decisionsMaking significant Software Architecture decisions
Making significant Software Architecture decisions
Bert Jan Schrijver
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration KeySmadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdfHow to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdfLooking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWSWomen in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
Women in Tech: Marketo Engage User Group - June 2025 - AJO with AWS
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Making significant Software Architecture decisions
Making significant Software Architecture decisionsMaking significant Software Architecture decisions
Making significant Software Architecture decisions
Bert Jan Schrijver
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 

Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects, Thread Start, Sleep, Interrupt

  • 3. Today’s Session • Processes and Threads • Thread Objects • Defining and Starting a Thread • Pausing Execution with Sleep • Interrupts • Joins • The SimpleThreads Example • Synchronization • Thread Interference • Memory Consistency Errors
  • 5. Process • has a self-contained execution environment • generally has a complete, private set of basic run-time resources • each process has its own memory space • Inter Process Communication (IPC) • pipes • sockets • Most implementations of the Java virtual machine run as a single process
  • 6. Thread • lightweight processes • provide an execution environment • requires fewer resources than creating a new process • exist within a process • every process has at least one - main thread • share the process's resources, including memory and open files
  • 8. Thread Objects • Each thread is associated with an instance of the class ‘Thread’. • basic strategies for using Thread objects to create a concurrent application. • 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’. • for now we will use Thread objects.
  • 9. Defining & Running a Thread • An application that creates an instance of ‘Thread’ must provide the code that will run in that thread. • There are two ways to do this: • Provide a Runnable object. • The Runnable interface defines a single method, run, meant to contain the code executed in the thread. • The Runnable object is passed to the Thread constructor. • 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.
  • 10. Using a Runnable Object public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } }
  • 11. Using a Subclass of Thread public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
  • 12. Runnable Object vs Thread Subclass • both invoke thread.start() to start a new thread • creating a Runnable Object • can subclass a class other than Thread • separates Runnable task from Thread object • more flexible • applicable to high-level thread management APIs • creating a Thread subclass • is easier to use in simple applications • is limited cause the task class must be a descendant of Thread
  • 13. Thread Class • The Thread class defines a number of methods useful for thread management. • These include static methods, which • provide information about, or • affect the status of, • the thread invoking the method. • The other methods are invoked from other threads involved in managing the thread and Thread object.
  • 14. Pausing Execution with Sleep • Thread.sleep causes the current thread to suspend execution for a specified period. • making processor time available to the other threads of an application or other applications • The sleep method can also be used for • pacing (rate of movement/activity), and • waiting for another thread • with duties that are understood to have time requirements
  • 15. Pausing Execution with Sleep Cont.d • Two overloaded versions of sleep are provided: • one that specifies the sleep time to the millisecond • and one that specifies the sleep time to the nanosecond. • sleep times are not guaranteed to be precise • limited by the facilities provided by the underlying OS • sleep period can be terminated by interrupts • In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.
  • 16. Sleep Example public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); } } }
  • 17. Sleep Example Cont.d • This example uses sleep to print messages at four- second intervals • main declares that it throws InterruptedException. • exception thrown 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
  • 18. Interrupts • 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 • 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. Supporting Interruption • How does a thread support its own interruption? • depends on what it's currently doing. • If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception. • For example, suppose the central message loop in the SleepMessages example were in the run method of a thread's Runnable object. • Then it might be modified as follows to support interrupts:
  • 20. Supporting Interruption Cont.d for (int i = 0; i < importantInfo.length; i++) { // Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { // We've been interrupted: no more messages. return; } // Print a message System.out.println(importantInfo[i]); }
  • 21. Supporting Interruption Cont.d • Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received. • What if a thread goes a long time without invoking a method that throws InterruptedException? • Then it must periodically invoke Thread.interrupted, • which returns true if an interrupt has been received.
  • 22. Supporting Interruption Cont.d for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { // We've been interrupted: no more crunching. return; } }
  • 23. Supporting Interruption Cont.d • In this simple example, the code simply tests for the interrupt and exits the thread if one has been received. • In more complex applications, it might make more sense to throw an InterruptedException: • This allows interrupt handling code to be centralized in a catch clause. if (Thread.interrupted()) { throw new InterruptedException(); }
  • 24. Interrupt Status Flag • 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. • 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.
  • 25. Joins • The join method allows one thread to wait for the completion of another. • If t is a Thread object whose thread is currently executing, • causes the current thread to pause execution until t's thread terminates. • Overloads of join allow the programmer to specify a waiting period. • similar to sleep, join is dependent on the OS for timing • 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. t.join();
  • 26. Simple Threads Example • SimpleThreads consists of two threads. • The first is the main thread that every Java application has. • main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. • If the MessageLoop thread takes too long to finish, the main thread interrupts it. • The MessageLoop thread prints out a series of messages. • If interrupted before it has printed all its messages, the MessageLoop thread prints a message and exits.
  • 28. 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: • thread interference • memory consistency errors. • The tool needed to prevent these errors is synchronization.
  • 29. Synchronization Cont.d • However, synchronization can introduce thread contention • when two or more threads try to access the same resource simultaneously and cause the Java runtime to • execute one or more threads more slowly • or even suspend their execution. • Starvation and livelock are forms of thread contention.
  • 30. Synchronization Cont.d • 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.
  • 31. Thread Interference class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } }
  • 32. Thread Interference Cont.d • Counter is designed so that each invocation of increment will add 1 to c, and each invocation of decrement will subtract 1 from c. • However, if a Counter object is referenced from multiple threads, interference between threads may prevent this from happening as expected. • Interference happens when two operations, running in different threads, but acting on the same data, interleave. • This means that the two operations consist of multiple steps, and the sequences of steps overlap.
  • 33. Thread Interference Cont.d • It might not seem possible for operations on instances of Counter to interleave, since both operations on c are single, simple statements. • However, even simple statements can translate to multiple steps by the virtual machine. • We won't examine the specific steps the virtual machine takes — it is enough to know that the single expression c++ can be decomposed into three steps: • Retrieve the current value of c. • Increment the retrieved value by 1. • Store the incremented value back in c. • The expression c-- can be decomposed the same way, except that the second step decrements instead of increments.
  • 34. Thread Interference Contd. • If Thread A invokes increment at about the same time Thread B invokes decrement. • If the initial value of c is 0, their interleaved actions might follow this sequence: • Thread A: Retrieve c. • Thread B: Retrieve c. • Thread A: Increment retrieved value; result is 1. • Thread B: Decrement retrieved value; result is -1. • Thread A: Store result in c; c is now 1. • Thread B: Store result in c; c is now -1. • Thread A's result is lost, overwritten by Thread B. • This particular interleaving is only one possibility. • Under different circumstances it might be Thread B's result that gets lost, or there could be no error at all. • Because they are unpredictable, thread interference bugs can be difficult to detect and fix.
  • 35. Memory Consistence Errors • occur when different threads have inconsistent views of what should be the same data. • causes are complex and beyond the scope of this tutorial. • programmer does not need a detailed understanding of these causes. • All that is needed is a strategy for avoiding them. • The key to avoiding memory consistency errors is understanding the happens-before relationship. • This is simply a guarantee that memory writes by one specific statement are visible to another specific statement. • To see this, consider the following example.
  • 36. Memory Consistence Errors Cont.d • Suppose a simple int field is defined and initialized: • Then, shortly afterwards, thread B prints out counter: • If the two statements had been executed in the same thread, the value printed out would be "1". • But if the two statements are executed in separate threads, the value printed out might well be "0", • because there's no guarantee that thread A's change to counter will be visible to thread B • unless the programmer has established a happens-before relationship between these two statements. • There are several actions that create happens-before relationships. • One of them is synchronization int counter = 0; System.out.println(counter);
  • 37. Memory Consistence Errors Cont.d • We've already seen two actions that create happens-before relationships. • When a statement invokes Thread.start, • every statement that has a happens-before relationship with that statement • also has a happens-before relationship with every statement executed by the new thread. • effects of the code that led up to the creation of the new thread are visible to the new thread. • When a thread terminates and causes a Thread.join in another thread to return, • then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. • effects of the code in the thread are now visible to the thread that performed the join.
  • 39. Next Up… • Synchronization • Synchronized Methods • Intrinsic Locks and Synchronization • Atomic Access • Liveness • Deadlock • Starvation and Livelock
  • 41. Thank you. Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg