This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single and multi-process programming, multi-threading, processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and containment. It also summarizes high-level concurrency utilities in Java like locks, executors, concurrent collections, and atomic variables.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single process and multi-process programming, as well as multi-core and multi-threaded programming. The document also discusses processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and splitting state.
The document discusses several programming paradigms including single process, multi process, and multi-core/multi-thread. It then covers topics such as processes, threads, synchronization, and liveness issues in concurrent programming including deadlock, starvation and livelock. Processes run independently while threads share data and scheduling. Synchronization prevents interference and inconsistencies between threads accessing shared data. Liveness issues can cause programs to halt indefinitely.
This document discusses several programming paradigms and concepts related to multi-threaded programming. It covers single process vs multi process vs multi-core/multi-threaded programming. It also discusses processes, threads, synchronization mechanisms like semaphores and barriers, and concurrency issues like deadlock, starvation and livelock that can occur in multi-threaded programs.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single process and multi-process programming, as well as multi-core and multi-threaded programming. Key concepts discussed include processes, threads, synchronization, deadlocks, and high-level concurrency objects like locks, executors, and concurrent collections. The document provides examples of implementing threads using subclasses and interfaces, and communicating between threads using interrupts, joins, and guarded blocks.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single process and multi-process programming, as well as multi-core and multi-threaded programming. The document also discusses processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and splitting state.
This document discusses various programming paradigms and concurrency concepts in Java. It covers single process and multi-process programming, as well as multi-core and multi-threaded programming. Key concepts discussed include processes, threads, synchronization, deadlocks, and high-level concurrency objects like locks, executors, and concurrent collections. The document provides examples of implementing and managing threads, as well as communicating between threads using techniques like interrupts, joins, and guarded blocks.
This document discusses threads in Java programming. It defines threads as the smallest unit of program execution that can be scheduled independently. The key points covered are:
- Threads are represented by the Thread class in Java and allow for multithreaded programming.
- A thread can be created by extending the Thread class or implementing the Runnable interface.
- The life cycle of a thread includes states like new, runnable, running, blocked, and dead.
- Synchronization techniques like wait(), notify(), and synchronized blocks are used for inter-thread communication and coordination.
This document outlines the key concepts and objectives covered in Lecture 04 on threads. It introduces processes and threads, defining them as the basic units of execution in operating systems and Java programs respectively. It discusses how multi-processing systems and multi-threading programs allow concurrent execution. The lecture then covers thread fundamentals in Java, including creating and managing threads, and synchronizing access to shared resources using monitors, locks, and wait-notify mechanisms. Students are assigned workshops on the producer-consumer problem and philosophers problem to demonstrate these concurrency concepts.
This document summarizes key concepts from a lecture on threads. It defines processes and threads, explaining that threads exist within processes and allow for multithreaded execution. It covers thread fundamentals in Java, including creating threads by extending Thread or implementing Runnable, and methods like start(), sleep(), and yield(). The document also discusses synchronizing access to shared resources using monitors, and how wait-notify allows threads to pause and resume execution. Homework includes solving producer-consumer and philosophers problems using these threading concepts.
This document provides an overview of Java threading concepts including the base threading topics of thread creation methods, life cycle, priorities, and synchronization. It also covers more advanced topics such as volatile variables, race conditions, deadlocks, starvation/livelock, inter-thread communication using wait/notify, thread pools, and remote method invocation. The document includes examples and explanations of key threading mechanisms in Java like semaphores and message passing.
The document discusses multithreading in Java. It covers the basics of multithreading including main threads, thread life cycles, creating multiple threads, thread priorities, synchronization, and inter-thread communication. It describes the different states a thread can be in like ready, running, blocked, and terminated. It also discusses thread priorities, synchronization techniques using monitors and messaging, and how to implement threads using the Thread class and Runnable interface.
This document discusses concepts related to threads and concurrency in Java. It begins by defining processes and threads, explaining that processes contain threads. It then covers key threading concepts like thread pools, synchronization, and data management between threads. The document provides examples of why threads are used and best practices for writing threaded code in Java. It also discusses common threading issues like deadlocks and race conditions and how to avoid them.
The document discusses multithreading concepts like concurrency and threading, how to create and control threads including setting priorities and states, and how to safely share resources between threads using synchronization, locks, and wait/notify methods to avoid issues like deadlocks. It also covers deprecated thread methods and increased threading support in JDK 1.5.
Threads allow concurrent execution of code in Java. Each thread shares the memory of the process but must carefully control access to shared resources to avoid inconsistencies. Creating a thread involves extending the Thread class and overriding the run() method. Threads have a lifecycle and priority levels that can be set. Synchronization is used to protect access to code and data shared across threads through locking and wait/notify methods to coordinate producer-consumer communication between threads. Deadlocks can occur if multiple threads attempt to lock resources in different orders.
Multithreading allows an application to have multiple points of execution operating concurrently within the same memory space. Each point of execution is called a thread. Threads can run tasks concurrently, improving responsiveness. They share memory and can access resources simultaneously. Synchronization is needed when threads access shared data to prevent inconsistencies.
The document discusses Java threads and thread synchronization. It defines that a thread is a flow of control and sequence of executed statements. It explains that a Thread is an object that can be created by extending the Thread class or implementing the Runnable interface. The start() method creates and runs the thread, while run() defines the code for the thread to execute. Threads have a lifecycle and can be in different states like ready, running, blocked/waiting. Synchronization is used to coordinate access to shared resources using locks, and wait/notify allows threads to signal and wait for each other.
Multithreaded fundamentals
The thread class and runnable interface
Creating a thread
Creating multiple threads
Determining when a thread ends
Thread priorities
Synchronization
Using synchronized methods
The synchronized statement
Thread communication using notify(), wait() and notifyall()
Suspending , resuming and stopping threads
Java concurrency allows applications to make use of multiple processors and handle asynchronous operations through the use of threads. While concurrency provides benefits like improved performance, it also introduces risks like race conditions and deadlocks if threads access shared resources unsafely. The Java threading APIs provide tools for safely managing concurrent operations through mechanisms like synchronization, locks, and concurrent collections.
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
More Related Content
Similar to Programming - Java-Threads-and-Synchronization.ppt (20)
This document discusses various programming paradigms and concurrency concepts in Java. It covers single process and multi-process programming, as well as multi-core and multi-threaded programming. Key concepts discussed include processes, threads, synchronization, deadlocks, and high-level concurrency objects like locks, executors, and concurrent collections. The document provides examples of implementing and managing threads, as well as communicating between threads using techniques like interrupts, joins, and guarded blocks.
This document discusses threads in Java programming. It defines threads as the smallest unit of program execution that can be scheduled independently. The key points covered are:
- Threads are represented by the Thread class in Java and allow for multithreaded programming.
- A thread can be created by extending the Thread class or implementing the Runnable interface.
- The life cycle of a thread includes states like new, runnable, running, blocked, and dead.
- Synchronization techniques like wait(), notify(), and synchronized blocks are used for inter-thread communication and coordination.
This document outlines the key concepts and objectives covered in Lecture 04 on threads. It introduces processes and threads, defining them as the basic units of execution in operating systems and Java programs respectively. It discusses how multi-processing systems and multi-threading programs allow concurrent execution. The lecture then covers thread fundamentals in Java, including creating and managing threads, and synchronizing access to shared resources using monitors, locks, and wait-notify mechanisms. Students are assigned workshops on the producer-consumer problem and philosophers problem to demonstrate these concurrency concepts.
This document summarizes key concepts from a lecture on threads. It defines processes and threads, explaining that threads exist within processes and allow for multithreaded execution. It covers thread fundamentals in Java, including creating threads by extending Thread or implementing Runnable, and methods like start(), sleep(), and yield(). The document also discusses synchronizing access to shared resources using monitors, and how wait-notify allows threads to pause and resume execution. Homework includes solving producer-consumer and philosophers problems using these threading concepts.
This document provides an overview of Java threading concepts including the base threading topics of thread creation methods, life cycle, priorities, and synchronization. It also covers more advanced topics such as volatile variables, race conditions, deadlocks, starvation/livelock, inter-thread communication using wait/notify, thread pools, and remote method invocation. The document includes examples and explanations of key threading mechanisms in Java like semaphores and message passing.
The document discusses multithreading in Java. It covers the basics of multithreading including main threads, thread life cycles, creating multiple threads, thread priorities, synchronization, and inter-thread communication. It describes the different states a thread can be in like ready, running, blocked, and terminated. It also discusses thread priorities, synchronization techniques using monitors and messaging, and how to implement threads using the Thread class and Runnable interface.
This document discusses concepts related to threads and concurrency in Java. It begins by defining processes and threads, explaining that processes contain threads. It then covers key threading concepts like thread pools, synchronization, and data management between threads. The document provides examples of why threads are used and best practices for writing threaded code in Java. It also discusses common threading issues like deadlocks and race conditions and how to avoid them.
The document discusses multithreading concepts like concurrency and threading, how to create and control threads including setting priorities and states, and how to safely share resources between threads using synchronization, locks, and wait/notify methods to avoid issues like deadlocks. It also covers deprecated thread methods and increased threading support in JDK 1.5.
Threads allow concurrent execution of code in Java. Each thread shares the memory of the process but must carefully control access to shared resources to avoid inconsistencies. Creating a thread involves extending the Thread class and overriding the run() method. Threads have a lifecycle and priority levels that can be set. Synchronization is used to protect access to code and data shared across threads through locking and wait/notify methods to coordinate producer-consumer communication between threads. Deadlocks can occur if multiple threads attempt to lock resources in different orders.
Multithreading allows an application to have multiple points of execution operating concurrently within the same memory space. Each point of execution is called a thread. Threads can run tasks concurrently, improving responsiveness. They share memory and can access resources simultaneously. Synchronization is needed when threads access shared data to prevent inconsistencies.
The document discusses Java threads and thread synchronization. It defines that a thread is a flow of control and sequence of executed statements. It explains that a Thread is an object that can be created by extending the Thread class or implementing the Runnable interface. The start() method creates and runs the thread, while run() defines the code for the thread to execute. Threads have a lifecycle and can be in different states like ready, running, blocked/waiting. Synchronization is used to coordinate access to shared resources using locks, and wait/notify allows threads to signal and wait for each other.
Multithreaded fundamentals
The thread class and runnable interface
Creating a thread
Creating multiple threads
Determining when a thread ends
Thread priorities
Synchronization
Using synchronized methods
The synchronized statement
Thread communication using notify(), wait() and notifyall()
Suspending , resuming and stopping threads
Java concurrency allows applications to make use of multiple processors and handle asynchronous operations through the use of threads. While concurrency provides benefits like improved performance, it also introduces risks like race conditions and deadlocks if threads access shared resources unsafely. The Java threading APIs provide tools for safely managing concurrent operations through mechanisms like synchronization, locks, and concurrent collections.
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
In Odoo 18's Employee module, organizing your workforce into departments enhances management and reporting efficiency. Departments are a crucial organizational unit within the Employee module.
Human Anatomy and Physiology II Unit 3 B pharm Sem 2
Respiratory system
Anatomy of respiratory system with special reference to anatomy
of lungs, mechanism of respiration, regulation of respiration
Lung Volumes and capacities transport of respiratory gases,
artificial respiration, and resuscitation methods
Urinary system
Anatomy of urinary tract with special reference to anatomy of
kidney and nephrons, functions of kidney and urinary tract,
physiology of urine formation, micturition reflex and role of
kidneys in acid base balance, role of RAS in kidney and
disorders of kidney
Analysis of Quantitative Data Parametric and non-parametric tests.pptxShrutidhara2
This presentation covers the following points--
Parametric Tests
• Testing the Significance of the Difference between Means
• Analysis of Variance (ANOVA) - One way and Two way
• Analysis of Co-variance (One-way)
Non-Parametric Tests:
• Chi-Square test
• Sign test
• Median test
• Sum of Rank test
• Mann-Whitney U-test
Moreover, it includes a comparison of parametric and non-parametric tests, a comparison of one-way ANOVA, two-way ANOVA, and one-way ANCOVA.
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...parmarjuli1412
The document provides an overview of therapeutic communication, emphasizing its importance in nursing to address patient needs and establish effective relationships. THERAPEUTIC COMMUNICATION included some topics like introduction of COMMUNICATION, definition, types, process of communication, definition therapeutic communication, goal, techniques of therapeutic communication, non-therapeutic communication, few ways to improved therapeutic communication, characteristics of therapeutic communication, barrier of THERAPEUTIC RELATIONSHIP, introduction of interpersonal relationship, types of IPR, elements/ dynamics of IPR, introduction of therapeutic nurse patient relationship, definition, purpose, elements/characteristics , and phases of therapeutic communication, definition of Johari window, uses, what actually model represent and its areas, THERAPEUTIC IMPASSES and its management in 5th semester Bsc. nursing and 2nd GNM students
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
How to Create Quotation Templates Sequence in Odoo 18 SalesCeline George
In this slide, we’ll discuss on how to create quotation templates sequence in Odoo 18 Sales. Odoo 18 Sales offers a variety of quotation templates that can be used to create different types of sales documents.
How to Create a Rainbow Man Effect in Odoo 18Celine George
In Odoo 18, the Rainbow Man animation adds a playful and motivating touch to task completion. This cheerful effect appears after specific user actions, like marking a CRM opportunity as won. It’s designed to enhance user experience by making routine tasks more engaging.
Completed Sunday 6/8. For Weekend 6/14 & 15th. (Fathers Day Weekend US.) These workshops are also timeless for future students TY. No admissions needed.
A 9th FREE WORKSHOP
Reiki - Yoga
“Intuition-II, The Chakras”
Your Attendance is valued.
We hit over 5k views for Spring Workshops and Updates-TY.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters, we are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
S9/This Week’s Focus:
* A continuation of Intuition-2 Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
Thx for tuning in. Your time investment is valued. I do select topics related to our timeline and community. For those seeking upgrades or Reiki Levels. Stay tuned for our June packages. It’s for self employed/Practitioners/Coaches…
Review & Topics:
* Reiki Is Japanese Energy Healing used Globally.
* Yoga is over 5k years old from India. It hosts many styles, teacher versions, and it’s Mainstream now vs decades ago.
* Anything of the Holistic, Wellness Department can be fused together. My origins are Alternative, Complementary Medicine. In short, I call this ND. I am also a metaphysician. I learnt during the 90s New Age Era. I forget we just hit another wavy. It’s GenZ word of Mouth, their New Age Era. WHOA, History Repeats lol. We are fusing together.
* So, most of you have experienced your Spiritual Awakening. However; The journey wont be perfect. There will be some roller coaster events. The perks are: We are in a faster Spiritual Zone than the 90s. There’s more support and information available.
(See Presentation for all sections, THX AGAIN.)
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
Exploring Ocean Floor Features for Middle SchoolMarie
This 16 slide science reader is all about ocean floor features. It was made to use with middle school students.
You can download the PDF at thehomeschooldaily.com
Thanks! Marie
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecdrazelitouali
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
4. Definition
Objects provide a way to divide a program into independent
sections. Often, you also need to turn a program into
separate, independently running subtasks.
Each of these independent subtasks is called a thread.
A piece of code that run in concurrent with other threads.
Thread is a statically ordered sequence of instructions.
5. Motivation
Resource utilization Programs sometimes have to
wait for external operations such as input or output, and
while waiting can do no useful work. It is more efficient to
use that wait time to let another program run.
Fairness Multiple users and programs may have equal
claims on the machine's resources. It is preferable to let
them share the computer via finer-grained time slicing than
to let one program run to completion and then start
another.
Convenience Program with multiple tasks.
6. Process
A process is a self-contained running program with
its own address space.
A multitasking operating system is capable of
running more than one process (program) at a
time.
A thread is a single sequential flow of control
within a process.
A single process can thus have multiple
concurrently executing threads
So threads are lightweight processes.
8. Java Thread Memory Model
Memory that can be shared between threads is
called shared memory or heap memory. All instance
fields, static fields and array elements are stored
in heap memory.
Local variables, method parameters and catched
exception parameters are never shared between
threads and stored in local stack and registers.
9. Threads compared with Processes
Processes are typically independent, while threads exist as subsets
of a process
Processes carry considerable state information, whereas multiple
threads within a process share state as well as memory and other
resources
Processes have separate address spaces, whereas threads share
their address space
Processes interact only through system-provided
inter-process communication mechanisms.
Context switching between threads in the same process is typically
faster than context switching between processes.
12. Thread Life Cycle
New state: The thread is
considered not alive.
Runnable (Ready-to-run) state: A
thread start its life. On this state
a thread is waiting for a turn on
the processor.
Running state: the thread is
currently executing
Dead state: its run() method
completes.
Blocked: is waiting the resources
that are hold by another thread.
14. Thread Creation
Two ways:
Extending the java.lang.Thread Class
Implementing the java.lang.Runnable Interface
Which to choose:
If you extend the Thread Class, that means that subclass
cannot extend any other Class, but if you implement
Runnable interface then you can do this.
And the class implementing the Runnable interface can
avoid the full overhead of Thread class which can be
excessive.
Else use Thread
15. Priority
The priority of a thread tells the scheduler how
important this thread is.
The thread scheduler can use the thread
priorities to determine the execution schedule of
threads.
Priorities are integer values
Thread.MIN_PRIORITY: 1
Thread.MAX_PRIORITY: 10
Thread.NORM_PRIORITY: 5
16. Joining
One thread may call join( ) on another thread to
wait for the second thread to complete before
proceeding.
17. Yielding
Causes the currently executing thread to pause
and allow other threads to execute.
This hint (and it is a hint—there’s no guarantee
your implementation will listen to it) takes the
form of the yield() method.
In general, yield() is useful only in rare situations
and you can’t rely on it to do any serious tuning of
your application
18. Sleeping
Causes the currently executing thread to pause for a given
number of milliseconds.
When you call sleep( ), it must be placed inside a try block
because it’s possible for sleep( ) to be interrupted before it
times out.
It just stops the execution of the thread for a while.
There is no guaranty that thread will resume the execution
after the given number of milliseconds.
Not to use in real-time application.
19. Interrupting
Interruption is a mechanism whereby a thread that is
waiting (or sleeping) can be made to prematurely stop
waiting.
In general, InterruptedException is thrown when another
thread interrupts the thread calling the blocking method.
The other thread interrupts the blocking/sleeping thread by
calling interrupt() on it.
20. Daemon Thread
A “daemon” thread is one that is supposed to
provide a general service in the background as
long as the program is running.
Thus, when all of the non-daemon threads
complete, the program is terminated. Conversely,
if there are any non daemon threads still running,
the program doesn’t terminate.
23. Improperly accessing
resources
Consider the example where one task generates
only even numbers.
Scenario 1: Single Threaded Program
Scenario 2: Multi Threaded Program
Problem is not that the object goes through a
state that violates invariance, but that methods
can be called by threads while the object is in that
intermediate unstable state.
24. Colliding over resources
If one thread tries to read the data and other
thread tries to update the same data, it leads to
inconsistent state.
A race condition occurs when the order of
execution of two or more threads may affect
some variable or outcome in the program.
Race conditions can be considered harmless
provided end result is correct. Otherwise needs to
be handled.
25. Resolving shared resource conflict
Solution: Serialize access to shared resources
Semaphore: Semaphore is an object containing a
value and two operations and used for
communication between threads.
Java has built-in support to prevent collisions over
resources in the form of the synchronized
keyword.
It works much like the Semaphore.
26. Resolving shared resource
conflict…
Mutex: A mechanism in which a piece of code is running at a time
by means of a lock (also called Monitor or Lock).
Locks in Java are reentrant. Reentrancy means that locks are
acquired on a per-thread basis rather than per-invocation basis.
Synchronization: When one object pass a message to another
object then both objects are in synchronized state. Synchronization
needs if multiple objects passes the message to specific object.
Atomic Operation: An atomic operation is one that cannot be
interrupted by the thread scheduler.
Volatile Variable: Every time the variable is used it must be read
from main memory. Similarly, every time the variable is written, the
value must be stored in main memory.
27. Synchronization (Cont…)
Only methods (or blocks) can be synchronized, Classes and variable
cannot be synchronized.
If two threads wants to execute a synchronized method in a class,
and both threads are using the same instance of the class to invoke
the method then only one thread can execute the method at a time.
If you need to synchronize one method in a class, synchronize all of
them, but this is not necessary.
You can synchronize a block of code rather than a method.
Constructors cannot be synchronized. Code inside the constructors
can be synchronized.
Rule zero of concurrent programming: never make any assumptions.
28. Critical Sections
Piece of code that must be executed by one thread at a time
Must have solution that guarantees:
Mutual exclusion (correctness)
Absence of deadlock/unnecessary delay (no hang up)
Randomly entry (fairness)
This is also called a synchronized block.
30. Inter-Thread Communication
When multiple threads are running inside an application,
most of them will need to communicate with each other in
some form.
Threads can communicate each other using wait() and
notify()/notifyAll() methods without any race condition.
Wait-and-notify must be used in conjunction with the
synchronized lock to prevent a race condition.
Methods wait(), notify() and notifyAll() are part of the base
class Object and not part of Thread, as is sleep(). Why???
31. Inter-Thread Communication
(Cont…)
sleep() does not release the lock when it is called
but method wait() does release the lock.
The only place you can call wait( ), notify( ) or
notifyAll( ) is within a synchronized method.
Restaurant Example: The waitperson must wait for the
chef to prepare a meal. When the chef has a meal ready, the
chef notifies the waitperson, who then gets the meal and
goes back to waiting.
The chef represents the producer, and the waitperson
represents the consumer.
33. Deadlock
In general, want to be careful about performing
any operations that might take a long time while
holding a lock.
It is possible for one thread to get stuck waiting
for another thread, which in turn waits for
another thread, etc., until the chain leads back to
a thread waiting on the first one.
34. Deadlock (Cont…)
Example 1
Thread1() { Thread2() {
synchronized(a) { synchronized(b) {
synchronized(b) { synchronized(a) {
… …
} }
} }
} }
// Thread1 holds lock for a, waits for b
// Thread2 holds lock for b, waits for a
35. Deadlock (Cont…)
Example 2
void moveMoney (Account a, Account b, int amount) {
Synchronized (a) {
synchronized (b) {
a.debit (amount);
b.credit (amount);
}
}
}
Thread1() { moveMoney(a,b,10); }
// holds lock for a, waits for b
Thread2() { moveMoney(b,a,100); }
// holds lock for b, waits for a
37. Other Stuff
The proper way to stop
Interrupting a blocked thread
Thread groups
ThreadLocal & InheritableThreadLocal
New Java API for Concurrency
38. Other Stuff
The proper way to stop
Thread class’ method stop( ), suspend( ), and resume( ) are
deprecated.
stop() method doesn’t release the locks. So use a flag to tell the
thread when to terminate itself by exiting its run( ) method.
suspend() and resume() methods used to suspending and
resuming threads. Dangerous, can lead to deadlock.
Instead, use wait(), suspend/resume threads, and
notifyAll()
39. Interrupting a blocked
thread
There are times when a thread blocks—such as
when it is waiting for input—and it cannot poll a
flag as it does in the previous example. In these
cases, you can use the Thread.interrupt( ) method
to break out of the blocked code.
As a general guideline, the use of interrupt()
should be reserved for situations where you want
to interrupt a thread to signal it to die gracefully.
40. Thread Group
A Thread Group holds a collection of threads.
Threads in a thread group can be dealt with as a
group.
May want to interrupt all threads in a
group
“Thread groups are best viewed as an unsuccessful experiment,
and you may simply ignore their existence.”
Joshua Bloch
Software Architect
Oracle (Sun Microsystems)
41. ThreadLocal & InheritableThreadLocal
Another methods for Inter-thread
Communication.
join() method of Thread.
A thread can also stream data through a pipe to another thread
using the classes PipedInputStream, PipedOutputStream,
PipedReader and PipedWriter.
Threads can also use thread-specific variables that keep a different
value for different threads by using the classes ThreadLocal and
InheritableThreadLocal.
New Java Concurrent API
42. ThreadLocal
ThreadLocal storage define a mechanism so that variable is
local to thread itself.
Other threads that define the same variable create their
own copy of the variable. This means that thread local
variables cannot be used to share state between threads.
public class ThreadLocal<T>
{
protected T initialValue ( );
public T get( );
public void set (T value);
public void remove( );
…
}
43. InheritableThreadLocal
InheritableThreadLocal is a subclass of
ThreadLocal and allows a thread-specific
value to be inherited from the parent
thread to the child thread.
There are not any public methods on
InheritableThreadLocal. It has one
protected method childValue();
44. New Java API for Concurrency
Time out…
Discuss later
46. Assignment
Modify Restaurant.java so that multiple Customers will place order
requests with WaitPersons, who give the requests to the Chefs,
who fulfill the orders and notify the appropriate WaitPerson, who
gives it to the appropriate Customer.
Solve the Dining Philosophers Problem.
Use the classes PipedInputStream, PipedOutputStream,
PipedReader and PipedWriter for Inter-Thread Communication.