TOPICS
Synchronization:
• Implementing synchronizationin Java to manage access to shared resources
among multiple threads.
• Using synchronized methods and blocks to ensure that a method or part of a
method can be accessed by only one thread at a time.
• Understanding the impact of synchronization on performance and how to avoid
common pitfalls.
Inter-thread Communication:
• Techniques for allowing threads to communicate effectively without causing data
inconsistencies or application crashes.
• Usage and implementation of wait(), notify(), and notifyAll() within synchronized
contexts.
• Practical use cases demonstrating how to coordinate the activities of multiple
threads through proper communication mechanisms.
2
3.
SYNCHRONIZATION IN JAVA
Definition:Synchronization in Java is a process that allows only one
thread to access a resource at a time. It is used to prevent thread
interference, ensure consistency of mutable shared data, and handle
race conditions.
3
4.
4
Purpose of Synchronization:
•To prevent data inconsistency due to simultaneous access of shared
resources.
• To manage the execution sequence of threads to ensure that critical section of
code is accessed by only one thread at a time.
How Synchronization Works:
• In Java, synchronization is achieved using the synchronized
keyword, which can be applied to methods or blocks of code.
• A synchronized method locks the object for which it is called.
• No other thread can call a synchronized method on the same
object until the first thread releases the object's lock.
• Synchronized blocks are more granular and allow locking on a
specific object rather than the entire method.
Locks and Reentrant Locks:
• Java uses an intrinsic lock or monitor lock, also known as a
mutex, to manage synchronization.
• These locks are reentrant, meaning if a synchronized method
calls another synchronized method on the same object, the
thread can continue to execute without blocking itself.
5.
Example : Asimple counter that is shared between multiple threads, and each
thread increments the counter. We need to ensure that the counter's value is
correctly updated after each increment, without any lost updates.
5
Here we are using synchronized keyword to synchronize that block
BASIC SYNCHRONIZED METHOD
SYNCHRONIZED BLOCK WITHINA
METHOD
7
Example: A scenario
where a method
performs several
tasks, but only part
of the method
needs to be
synchronized to
minimize the
performance
overhead of
synchronization.
8.
SYNCHRONIZED BLOCK WITHINA
METHOD
8
• This example uses a synchronized block instead of synchronizing the entire
method. It only locks the critical section where the count variable is modified.
• By reducing the scope of synchronization, we decrease the blocking time for
threads, which can enhance performance in situations where extensive
synchronization is a bottleneck.
9.
INTER-THREAD
COMMUNICATION IN JAVA
Definition:Inter-thread communication is a mechanism that allows
synchronized threads to communicate with each other. Communication
between threads is crucial when threads have interdependencies, such
as when one thread needs to wait for another to perform a task or
notify it to proceed.
9
10.
10
Methods for Inter-threadCommunication:
• wait(): Causes the current thread to release the lock and wait until another
thread invokes the notify() or notifyAll() method for the same object.
• notify(): Wakes up a single thread that is waiting on the object’s lock.
• notifyAll(): Wakes up all threads that are waiting on the object’s lock.
Using wait(), notify(), and notifyAll():
• These methods must be called from within a synchronized context (i.e.,
synchronized method or block).
• wait() releases the lock held on the object, allowing other threads to
execute synchronized code on the same object.
• The waiting thread remains inactive until it is notified or interrupted.
• notify() or notifyAll() must be called after changes that affect waiting
threads have been made, signaling them to resume execution.
Practical Considerations:
• Proper use of these methods can prevent deadlocks and ensure efficient
communication among threads.
• Developers must ensure that the notify() or notifyAll() methods are not
called prematurely before the relevant conditions are satisfied, as this can
lead to logical errors and stuck threads.
11.
PRODUCER-CONSUMER
MODEL
11
The Producer-Consumer modelis a classic example of a multi-
threading pattern used to manage shared resources. In this model:
• Producers create items or produce data and place them into a
shared buffer.
• Consumers take or consume these items from the buffer.
• The key challenge is ensuring that the producer does not overflow
the buffer by producing more items than the consumer can handle,
and the consumer does not try to consume from an empty buffer.
This requires synchronization and efficient inter-thread
communication to maintain balance and data integrity.
12.
WAIT(), NOTIFY(), NOTIFYALL()
Letssay
Chef(producer): Prepares meals and notifies the waiter once the meal is ready.
Waiter(consumer): Waits for meals to be prepared before serving them to
customers.
12
13.
BASIC WAIT() ANDNOTIFY()
Example: A chef prepares a meal, and a waiter serves it. The waiter must wait until the chef has
finished preparing the meal. The chef notifies the waiter when the meal is ready.
13
USAGE WITH NOTIFYALL()
Example:Multiple waiters are waiting for different meals. The chef prepares several meals and
uses notifyAll() to ensure all waiting waiters check if their specific meal is ready.
15
17
• In thefirst snippet, a single waiter and chef
interact using notify() when a meal is ready.
• In the second snippet, multiple waiters wait
for the chef to prepare any meal. When the
chef finishes a meal, notifyAll() is used to
alert all waiters, ensuring that no waiter
misses an update.
18.
18
• Effective ThreadManagement: Synchronization and inter-thread communication are foundational
elements for effective thread management in Java. These mechanisms ensure that multiple threads can
operate on shared resources without interference, preserving data integrity and system stability.
• Synchronization: By utilizing synchronized methods and blocks, Java developers can control access to
shared resources, ensuring that only one thread at a time can execute critical sections of code. This
prevents common issues such as race conditions and data corruption.
• Inter-thread Communication: Through the use of wait(), notify(), and notifyAll() methods, Java allows
threads to communicate efficiently. This communication is crucial in scenarios like the Producer-
Consumer model, where coordination between thread activities (e.g., producing and consuming
resources) is necessary for smooth operation.
• Practical Application: The practical code examples provided—ranging from simple counters to a
restaurant scenario—demonstrate how these concepts can be applied to real-world applications.
Developers can use these patterns to enhance application performance and reliability, especially in
environments where tasks are interdependent.
CONCLUSION