1/38
Looks like no tags are added yet.
What are the two java concurrency APIs?
Java has two, mostly separate concurrency APIs: the older API, which is usually called block-structured concurrency or synchronization-based concurrency or even “classic concurrency,” and the newer API, which is normally referred to by its Java package name, java.util.concurrent.
Classic Concurrency - synchronized and volatile
This was the only API available until Java 5. As you might guess from the alternative name, “synchronization-based concurrency,” this is the language-level API that is built into the platform and depends upon the synchronized and volatile keywords.
It is a low-level API and can be somewhat difficult to work with, but it is very much worth understanding. It provides a solid foundation for the chapters later in the book that explain other types and aspects of concurrency.
Concurrency and multithreading in Hardware
Let’s start with some basic facts about concurrency and multithreading:
Concurrent programming is fundamentally about performance.
There are basically no good reasons for implementing a concurrent algorithm if the system you are running on has sufficient performance that a serial algorithm will work.
Modern computer systems have multiple processing cores—even mobile phones have two or four cores today.
All Java programs are multithreaded, even those that have only a single application thread.
This last point is true because the JVM is itself a multithreaded binary that can use multiple cores (e.g., for JIT compilation or garbage collection). In addition, the standard library also includes APIs that use runtime-managed concurrency to implement multithreaded algorithms for some execution tasks
Amdahl’s law
Brief Explanation
Amdahl’s Law is a foundational model used to evaluate the efficiency of parallelizing work across multiple execution units (such as threads or processes). It demonstrates that while adding more processors can speed up a task by subdividing it, the overall speedup is strictly limited by the portion of the task that cannot be parallelized and must be executed sequentially.
Bullet Points
Abstract Execution Units: The model applies universally to any execution units (threads, processes, etc.) and does not depend on specific hardware or implementation details.
The Naive Assumption: It is tempting to think that if a task takes time T1 on one processor, adding N processors will linearly reduce the time to T1 / N.
The Cost of Subdividing: Splitting work and recombining the results is not free. This communication/coordination overhead is known as the "serial part" of the calculation, represented by s (0 < s < 1).
The Ultimate Speed Limit: Because the serial part cannot be parallelized, the total completion time can never be faster than s * T1, regardless of how many processing units you add.
Best-Case Scenario: The model assumes the overhead (s) remains constant as processors (N) increase. In reality, splitting work among more processors often increases the overhead, making the constant s assumption the most optimistic scenario.
The Example in the Text
If the communication overhead (the serial part, s) of a task is 0.05 (or 5%), the task will always take at least 5% of the original single-processor time ($0.05 * T1) to complete. Even if you throw an infinite number of execution units at the problem, you can never eliminate this 5% baseline time requirement.
the easiest way to think about Amdhal’s law is
if s is between 0 and 1, then the maximum speedup that can be achieved is 1 / s. This result is somewhat depressing—it means that if the communication overhead is just 2%, the maximum speedup that can ever be achieved (even with thousands of processors working at full speed) is 50X.

Explaining Java’s threading model - Java’s threading model is based on the following two fundamental concepts?
Java’s threading model is based on the following two fundamental concepts:
Shared, visible-by-default mutable state
Preemptive thread scheduling by the operating system
What are the most important aspects of Java’s threading model?
Let’s consider the following most important aspects of these ideas:
Objects can be easily shared between all threads within a process.
Objects can be changed (“mutated”) by any threads that have a reference to them.
The thread scheduler (the operating system) can swap threads on and off cores at any time, more or less.
Methods must be able to be swapped out while they’re running (otherwise, a method with an infinite loop would steal the CPU forever).
This, however, runs the risk of an unpredictable thread swap, leaving a method “half-done” and an object in an inconsistent state.
Objects can be locked to protect vulnerable data.
The last point is absolutely crucial—without it there is a huge risk of changes being made in one thread not being seen correctly in other threads. In Java, the ability to lock objects is provided by the synchronized keyword in the core language.
Monitors on objects in Java
Technically, Java provides monitors on each of its objects, which combine a lock (aka mutual exclusion) with the ability to wait for a certain condition to become true.
Because every class in Java inherits from java.lang.Object, every single object you create in Java inherently comes with a hidden "monitor" (often called an intrinsic lock or monitor lock).
1. The Lock (Mutual Exclusion)
Mutual exclusion ensures that only one thread can access a block of code at a time. In Java, you activate this part of the monitor using the synchronized keyword.
Imagine a single, highly secure filing cabinet (the Object) in an office. The cabinet only has one physical key (the Lock).
If Thread A wants to open the cabinet, it must take the key.
If Thread B comes along while Thread A has the key, Thread B is physically blocked from opening the cabinet. It must wait outside until Thread A finishes and returns the key.
Java
public synchronized void doSecureWork() {
// Only one thread can execute this method on this object at a time.
// The thread automatically acquired this object's lock to get in here.
}
2. The Wait Set (Waiting for a Condition)
Sometimes, a thread successfully acquires the lock, looks inside the object, but realizes it cannot do its job yet because some condition hasn't been met (e.g., it wants to read data, but the buffer is empty).
Instead of holding onto the lock and freezing the whole program, the thread can use the object's wait/notify mechanism. These are methods built right into java.lang.Object:
wait(): The thread says, "I have the lock, but I'm missing what I need. I am going to release the lock and go to sleep in this object's 'waiting room'."
notify() / notifyAll(): Another thread gets the lock, changes the data (e.g., adds items to the buffer), and yells into the waiting room, "The data has changed! Wake up and try to get the lock again!"

What ate Design concepts in java.util.concurrent to be aware of?
The most important design forces, listed next, were catalogued by Doug Lea as he was
doing his landmark work producing java.util.concurrent:
Safety (also known as concurrent type safety)
Liveness
Performance
Reusability
Let’s look at each of these forces now.
Design concepts in java.util.concurrent - Safety
Safety is about ensuring that object instances remain self-consistent, regardless of any other operations that may be happening at the same time. If a system of objects has this property, it’s said to be safe or concurrently typesafe.
In general, one strategy for safety is to never return from a nonprivate method in an inconsistent state, and to never call any nonprivate method (and certainly not a method on any other object) while in an inconsistent state. If this practice is combined with a way of protecting the object (such as a synchronization lock or critical section) while it’s inconsistent, the system can be guaranteed to be safe.
As you might guess from the name, one way to think about concurrency is in terms of an extension to the regular concepts of object modeling and type safety. In non-concurrent code, you want to ensure that regardless of what public methods you call on an object, it’s in a well-defined and consistent state at the end of the method. The usual way to do this is to keep all of an object’s state private and expose a public API of methods that alter the object’s state only in a way that makes senses for the design domain.

Design concepts in java.util.concurrent - Liveness
A live system is one in which every attempted activity eventually either progresses or fails. A system that is not live is basically stuck—it will neither progress toward success or fail.
The keyword in the definition is eventually—there is a distinction between a transient failure to progress (which isn’t that bad in isolation, even if it’s not ideal) and a permanent failure. Transient failures could be caused by a number of underlying problems, such as
Locking or waiting to acquire a lock
Waiting for input (such as network I/O)
Temporary failure of a resource
Not enough CPU time available to run the thread
Permanent failures could be due to a number of causes. Some of the most common follow:
Deadlock
Unrecoverable resource problem (such as if the network filesystem [NFS] goes away)
Missed signal
Design concepts in java.util.concurrent - Performance
The performance of a system can be quantified in a number of different ways. think of performance as being a measure of how much work a system can do with a given amount of resources.
In chapter 7, we’ll talk about performance analysis and techniques for tuning, and we’ll introduce a number of other metrics you should know about.
Design concepts in java.util.concurrent - Reusability
Reusability forms a fourth design force, because it isn’t really covered by any of the other considerations. A concurrent system that has been designed for easy reuse is sometimes very desirable, although this isn’t always easy to implement. One approach is to use a reusable toolbox (like java.util.concurrent) and build non-reusable application code on top of it.
How and why do the forces conflict & What’s the balance that you should ultimately try to achieve?
The design forces are often in opposition to each other, and this tension can be viewed as a central reason that designing good concurrent systems is difficult, as explained by the following points:
Safety stands in opposition to liveness—safety is about ensuring that bad things don’t happen, whereas liveness requires progress to be made.
Reusable systems tend to expose their internals, which can cause problems with safety.
A naïvely written safe system will typically not be very performant, because it usually resorts to heavy use of locking to provide safety guarantees.
The balance that you should ultimately try to achieve is for the code to be flexible enough to be useful for a wide range of problems, closed enough to be safe, and still reasonably live and performant. This is quite a tall order, but, fortunately, some practical techniques can help with this. Here are some of the most common in rough order of usefulness:
Restrict the external communication of each subsystem as much as possible. Data hiding is a powerful tool for aiding with safety.
Make the internal structure of each subsystem as deterministic as possible. For example, design in static knowledge of the threads and objects in each subsystem, even if the subsystems will interact in a concurrent, nondeterministic way.
Apply policy approaches that client apps must adhere to. This technique is powerful but relies on user apps cooperating, and it can be hard to debug if a badly behaved app disobeys the rules.
Document the required behavior. This is the weakest of the alternatives, but it’s sometimes necessary if the code is to be deployed in a very general context.
Sources of overhead - What to think of when developing concurrent code
Many aspects of a concurrent system can contribute to the inherent overhead:
Monitors (i.e., locks and condition variables)
Number of context switches
Number of threads
Scheduling
Locality of memory
Algorithm design
This should form the basis of a checklist in your mind. When developing concurrent code, you should ensure that you have thought about everything on this list.
In particular, the last of these—algorithm design—is an area in which developers can really distinguish themselves, because learning about algorithm design will make you a better programmer in any language.
Synchronization and locks
As you probably already know, the synchronized keyword can be applied either to a block or to a method. It indicates that before entering the block or method, a thread must acquire the appropriate lock. For example, let’s think about a method to withdraw money from a bank account, as shown next:
The method must acquire the lock belonging to the object instance (or the lock belonging to the Class object for static synchronized methods). For a block, the programmer should indicate which object’s lock is to be acquired.
Only one thread can be progressing through any of an object’s synchronized blocks or methods at once; if other threads try to enter, they’re suspended by the JVM.
Tell me some facts about synchronization and locks in Java? 9 facts
Let’s look at some basic facts about synchronization and locks in Java. Hopefully you
already have most (or all) of these at your fingertips:
Object-Only Locking: Only objects—not primitives—can be locked.
Array Component Isolation: Locking an array of objects does not lock the individual object elements contained within that array.
Method vs. Block Equivalence: A synchronized instance method is conceptually equivalent to a synchronized(this) { … } block that encloses the entire method body, (but note that they’re represented differently in bytecode).
A static synchronized method locks the Class object, because there’s no instance object to lock.
Class Object Locking Nuance: If you need to lock a Class object, evaluate whether to do so explicitly (e.g., MyClass.class) or dynamically via getClass(). The behavior of these two approaches diverges significantly when dealing with subclasses.
Inner Class Independence: Synchronization within an inner class is completely independent of the outer class's monitor lock due to how inner classes are structurally implemented by the compiler.
Signature Exclusion: The synchronized modifier is an implementation detail and does not form part of the formal method signature. Consequently, it cannot be placed on method declarations within an interface.
Unsynchronized methods don’t look at or care about the state of any locks, and they can progress while synchronized methods are running.
Java’s locks are re-entrant (able to be re-entered)—a thread holding a lock that encounters a synchronization point for the same lock (such as a synchronized method calling another synchronized method on the same object) will be allowed to continue.


The state model for a thread - What’s the states that a thread moves through during its life cycle?
A Java thread object is initially created in the NEW state. At this time, an OS thread does not yet exist (and may never exist). To create the execution thread, Thread.start() must be called. This signals the OS to actually create a thread.
The scheduler will place the new thread into the run queue and, at some later point, will find a core for it to run upon (some amount of waiting time may be involved if the machine is heavily loaded). From there, the thread can proceed by consuming its time allocation and be placed back into the run queue to await further processor time slices. This is the action of the forcible thread scheduling that we mentioned in section 5.1.1.
Throughout this scheduling process, of being placed on a core, running, and being placed back in the run queue, the Java Thread object remains in the RUNNABLE state. As well as this scheduling action, the thread itself can indicate that it isn’t able to make use of the core at this time. This can be achieved in two different ways:
The program code indicates by calling Thread.sleep() that the thread should wait for a fixed time before continuing.
The thread recognizes that it must wait until some external condition has been met and calls Object.wait().
In both cases, the thread is immediately removed from the core by the OS. However, the behavior after that point is different in each case.
In the first case (point 3.1), the thread is asking to sleep for a definite amount of time. The Java thread transitions into the TIMED_WAITING state, and the operating system sets a timer. When it expires, the sleeping thread is woken up and is ready to run again and is placed back in the run queue.
The second case (point 3.2) is slightly different. It uses the condition aspect of Java’s per-object monitors. The thread will transition into WAITING and will wait indefinitely. It will not normally wake up until the operating system signals that the condition may have been met—usually by some other thread calling Object.notify() on the current object.
As well as these two possibilities that are under the threads control, a thread can transition into the BLOCKED state because it’s waiting on I/O or to acquire a lock held by another thread.
Finally, if the OS thread corresponding to a Java Thread has ceased execution, then that thread object will have transitioned into the TERMINATED state. Let’s move on to talk about one well-known way to solve the synchronization problem: the idea of fully synchronized objects.

Fully shnchronized objects - What are the rules that the class is known to be thread-safe and will also be live if followed?
A fully synchronized class is a class that meets all of the following conditions:
All fields are always initialized to a consistent state in every constructor.
There are no public fields.
Object instances are guaranteed to be consistent after returning from any non-private method (assuming the state was consistent when the method was
called).
All methods provably terminate in bounded time.
All methods are synchronized.
No method calls another instance’s methods while in an inconsistent state.
No method calls any non-private method on the current instance while in an inconsistent state.

Deadlocks in Java
A Deadlock occurs when two or more threads are permanently blocked because each thread is holding a lock that the other thread needs to proceed, creating a circular execution dependency.
The Deadlock Trap (From Listing 5.2)
When a method is marked as public synchronized boolean transferTo(FSOAccount other, ...), Java implicitly locks the current instance (this).
Thread A locks Account a and enters the method.
Thread B locks Account b and enters the method.
While holding their locks, both threads pause (simulating a database or latency check).
Upon waking, Thread A tries to call other.deposit(), requiring the lock for Account b. It blocks.
Simultaneously, Thread B tries to call other.deposit(), requiring the lock for Account a. It blocks.
Because neither thread can proceed without the lock held by the other, and neither will release its current lock, they enter a permanent BLOCKED state.
To deal with deadlocks, one technique is to always acquire locks in the same order in every thread. In the preceding example, the first thread to start acquires them in the order A, B, whereas the second thread acquires them in the order B, A. If both threads had insisted on acquiring them in the order A, B, the deadlock would have been avoided, because the second thread would have been blocked from running at all until the first had completed and released its locks.

What’s the 4 conditions for a deadlock to manifest and why it happens
what’s the industry best practice to avoid this?
For this deadlock to manifest, four absolute conditions must be met simultaneously:
Mutual Exclusion: Only one thread can hold an account monitor lock at a time.
Hold and Wait: Thread A holds lock a while actively waiting to acquire lock b.
No Preemption: The JVM cannot forcibly strip a lock away from a thread.
Circular Wait: Thread A waits for Thread B, which is waiting for Thread A.
Industry Best-Practice Remediation1. Enforce a Strict Lock Ordering Pattern
The text recommends forcing all threads to acquire locks in the exact same resource order. By comparing unique properties (like an accountId or a system hash code), you ensure that regardless of who initiates the transfer, the system locks resources deterministically (e.g., always locking the lower ID first). This breaks the Circular Wait condition.
2. Use Explicit Timed Locks (tryLock)
Modern Java systems replace raw synchronized blocks with java.util.concurrent.locks.ReentrantLock. By using tryLock(timeout, timeunit), a thread will back off and release its own held locks if it cannot secure the secondary resource within a given timeframe, breaking the Hold and Wait condition.
How Has the Mental Model of Concurrency Shifted from Single-Core Timesharing to Modern Multi-Core Architectures?
A simple conceptual model of concurrent programming is timesharing of a CPU— that is, threads swapping on and off a single core. This classic view is shown in figure 5.5.
Today, anything as big as or larger than a mobile phone has multiple cores, so the mental model should be different, too, encompassing multiple threads all running on different cores at the same physical moment (and potentially operating on shared data). You can see this in figure 5.5. For efficiency, each thread that is running simultaneously may have its own cached copy of data being operated on.

What’s actually being synchronized? (Question based on FC22)
We asked earlier, what is it that’s being synchronized in the code in listing 5.1? The answer is: the memory representation in different threads of the object being locked. That is, after the synchronized method (or block) has completed, any and all changes that were made to the object being locked are flushed back to main memory before the lock is released, as illustrated in figure 5.6
In addition, when a synchronized block is entered, after the lock has been acquired, any changes to the locked object are read in from main memory, so the thread with the lock is synchronized to the main memory’s view of the object before the code in the locked section begins to execute.

What does the volatile keyword in java do?
synchronized vs volatile?
Core Mechanics & Memory Rules
Direct Memory Reads: A thread never reads a volatile field from a local CPU cache; it is always reread directly from main memory before use.
Instant Memory Writes: Any write to a volatile field is instantly flushed to main memory before the current bytecode instruction completes.
No Mutual Exclusion: Unlike synchronized, volatile involves no locking mechanism, meaning threads never block or wait on each other to access the field.
Liveness Safety: Because it does not introduce locks, it is completely immune to deadlocks.
Volatile vs. Synchronized
Operation Limits: volatile guarantees memory visibility for only one single operation (one read or one write). synchronized groups multiple operations into an indivisible unit.
Visibility Timing: volatile flushes changes to main memory immediately after the single instruction. synchronized only flushes data when the method exits and the lock is released.
The State-Dependency Flaw
State-Independent Writes Only: volatile is only safe to use when the new value being written does not depend on the current value (the read state).
The count++ Danger: Composite operations like ++ or -- (v=v+1) are not safe. They require a three-step cycle (Read→Modify→Write).
Race Conditions: Because volatile only protects a single step at a time, two threads can read the same stale value from main memory simultaneously, increment it locally, and write back the same number—resulting in lost updates.
The Lock Rule: If an update is state-dependent (e.g., increments or check-then-act), you must use a lock (synchronized or ReentrantLock) or use an AtomicInteger.
Performance Trade-off
Cache Bypassing: By forcing the CPU to use memory fence instructions, volatile bypasses high-performance local L1/L2 caches.
Hardware Cost: This ensures thread safety for single variables, but introduces an architectural latency cost for memory flushes on every single access.
Define the thread states and methods for a thread object
A java.lang.Thread object is just that: a Java object that lives in the heap and contains metadata about an operating system thread that either exists, used to exist, or will potentially exist in the future.
Java defines the following states for a thread object, which correspond to OS thread states on mainstream operating systems. They are closely related to the state model we saw in figure 5.2:
NEW—the Thread object has been created, but the actual OS thread has not.
RUNNABLE—The thread is available to run. The OS is responsible for scheduling it.
BLOCKED—The thread is not running; it needs to acquire a lock or is in a system call.
WAITING—The thread is not running; it has called Object.wait() or Thread.join().
TIMED_WAITING—The thread is not running; it has called Thread.sleep().
TERMINATED—The thread is not running; it has completed execution.
All threads start in the NEW state and finish in the TERMINATED state, whether the thread’s run() method exits normally or throws an exception.
NOTE: The Java thread state model does not distinguish between whether a RUNNABLE thread is actually physically executing at that precise moment or is waiting (in the run queue).
Where the actual creation of the thread is done?
What are the three groups of methods in the Thread API in Java?
The actual creation of the thread is done by the start() method, which calls into native code to actually perform the relevant system calls (e.g., clone() on Linux) to create the thread and begin code execution in the thread’s run() method.
Note: Some of the thread methods with timeouts (e.g., Thread.join() with a timeout parameter) may actually result in the thread being placed into TIMED_WAITING instead of WAITING.


How to safely interrupt a thread
When working with threads, it’s relatively common to want to safely interrupt the work a thread is doing, and methods are provided for that on the Thread object. However, they may not behave as we’d first expect. Let’s run the following code that creates a thread, hard at work, and then tries to interrupt it:
Note: We have the following two methods for checking the interrupt state: a static Thread.interrupted(), which implicitly looks at the current thread, and an instance level isInterrupted() on a thread object. The static version clears the state after checking and is what’s expected for use before throwing an InterruptedException. The instance method, on the other hand, doesn’t alter the state.

How to retain the information that our thread was interrupted?
If we want to retain the information that our thread was interrupted, we have to handle that directly ourselves. For our simple example where we need the state only later in the thread’s code, something like this would work:

how to handle exceptions that may be thrown from within a thread?
Another issue for multithreaded programming is how to handle exceptions that may be thrown from within a thread. For example, suppose that we are executing a Runnable of unknown provenance. If it throws an exception and dies, then other code may not be aware of it. Fortunately, the Thread API provides the ability to add uncaught exception handlers to a thread before starting it, like this example:

Why were original Thread methods like stop(), suspend(), and resume() deprecated and slated for removal?
The First-Mover Cost: Java 1.0 was the first mainstream language with native multithreading; its creators discovered the core architectural dangers of these methods through real-world trial and error.
The Fatal Flaw of Thread.stop(): It instantly terminates a thread by injecting an unchecked ThreadDeath exception, forcing the call stack to unwind and abruptly bypassing critical data-cleanup operations like finally blocks.
Corrupted State Leaks: Kicking a thread out of execution instantly forces it to drop all of its acquired monitor locks. If it was killed mid-update, a broken, partially modified object immediately becomes visible to other threads.
The Fatal Flaw of Thread.suspend(): It pauses a thread's execution without releasing any of its monitor locks.
Infinite Deadlock Risk: If the suspended thread holds a lock on a shared resource, every other thread attempting to access a synchronized block guarded by that lock will freeze permanently unless an external resume() signal successfully clears the bottleneck.
The Modern Standard: Forcible external control is an anti-pattern. Modern production Java relies on Cooperative Shutdowns (like checking a volatile flag or handling native Thread.interrupt() signals) so a thread can finish its unit of work and terminate itself safely.
Immutability
One technique that can be of great value is the use of immutable objects. These are objects that either have no state or that have only final fields (which must, therefore, be populated in the constructors of the objects). These are always safe and live, because their state can’t be mutated, so they can never be in an inconsistent state
One problem is that any values that are required to initialize a particular object must be passed into the constructor. This can lead to unwieldy constructor calls, with many parameters. As a result, many coders use a factory method instead. This can be as simple as using a static method on the class, instead of a constructor, to produce new objects. The constructors are usually made protected or private, so that the static factory methods are the only way of instantiating

Immutable objects obviously can’t be changed, so what happens when we want to make changes to one of them?
mmutable objects obviously can’t be changed, so what happens when we want to make changes to one of them? For example, it’s very common that if a deposit or other transaction can’t take place on a specific day, that transaction is “rolled” to the following day. (check img)

We should note a couple of things about the builder when it comes to threads?
The SAM Type Property: Technically, the builder is a SAM (Single Abstract Method) type, meaning it could compile as the target for a lambda expression.
Not a True Functional Interface: Despite its SAM structure, a builder’s purpose is to aggregate local state and construct immutable objects—not to model a function or callback.
Omission of @FunctionalInterface: Because using a builder as a lambda is a conceptual anti-pattern, the interface is intentionally not decorated with the @FunctionalInterface annotation—proving that just because syntax allows something doesn't mean you should do it.
No Thread Safety: The builder is explicitly not thread-safe. The API assumes builders will remain isolated within a single thread and never be shared across thread boundaries.
The Correct Concurrency Workflow: A single thread must handle the builder to gather all necessary state, and then call the build method to output an immutable object that can then be safely shared across multiple threads without synchronization.
Design Red Flag: If an architecture requires sharing a builder instance between different threads, it indicates a flaw in the domain model that requires structural refactoring.
Immutability of value versus reference & Final keyword
One last point about immutable objects: the final keyword applies only to the object directly pointed to. As you can see in figure 5.7, the reference to the main object can’t be assigned to point at object 3, but within the object, the reference to object 1 can be updated to point at object 2.
Another way of saying this is that a final reference can point at an object that has non-final fields. This is sometimes known as shallow immutability.
Immutability is a very powerful technique, and you should use it whenever feasible. However, sometimes it’s just not possible to develop efficiently with only immutable objects, because every change to an object’s state requires a new object to be spun up. So we’re sometimes left with the necessity of dealing with mutable objects.

What'‘s the JMM?
Modern computers don't just run your code line-by-line from main memory. To run fast, CPUs constantly reorder instructions and save variables in local core caches.
Without a strict set of rules, Thread A could update a variable, but Thread B might never see that update because it's looking at its own old cache. The JMM is the official rulebook that tells compiler makers and application developers exactly when and how memory updates are guaranteed to be visible across different threads.
What’s Happens-Before?
Happens-Before: This relationship indicates that one block of code fully completes before the other can start.
What it means: This is a guarantee of ordering and visibility. If Action A Happens-Before Action B, then everything accomplished by Action A is guaranteed to be completely finished and visible to Action B before B even starts.
Analogy: You must deposit a check (A) before the bank can let you withdraw those specific funds (B). A must fully complete and reflect in the system before B can begin.
What’s Synchronizes-With?
Synchronizes-With: An action will synchronize its view of an object with main memory before continuing.
What it means: This is the physical mechanism of updating memory maps. When a piece of code Synchronizes-With main memory, it forces a hardware handshake.
The Action: The writing thread flushes its local CPU cache out to main memory, and the reading thread immediately invalidates its own local cache, forcing it to fetch the fresh values from main memory.
The Text's Example: When a thread writes to a volatile variable, that action Synchronizes-With a later read of that variable (like in a System.out.println() statement). The write forces the data out to main memory so the read is guaranteed to see it.
In figure 5.8 you can see an example of a volatile write that Synchronizes-With a later read access (for the println()).

What' are the main rules of JMM?
An unlock operation on a monitor Synchronizes-With later locks operations.
A write to a volatile variable Synchronizes-With later reads from the variable.
If an action A Synchronizes-With action B, then A Happens-Before B.
If A comes before B in program order, within a thread, then A Happens-Before B.
The general statement of the first two rules is that “releases happen before acquires.” In other words, the locks that a thread holds when writing are released before the locks can be acquired by other operations (including reads). For example, the rules guarantee that if one thread writes a value to a volatile variable, then any thread that later reads that variable will see the value that was written (assuming no other writes have taken place).

What are the JMM rules that are about sensible behavior?
Additional rules, which are really about sensible behavior, follow:
The completion of a constructor Happens-Before the finalizer for that object starts to run (an object has to be fully constructed before it can be finalized).
An action that starts a thread Synchronizes-With the first action of the new thread.
Thread.join() Synchronizes-With the last (and all other) actions in the thread being joined.
If X Happens-Before Y and Y Happens-Before Z, then X Happens-Before Z (transitivity).
These simple rules define the whole of the platform’s view of how memory and synchronization works. Figure 5.9 illustrates the transitivity rule.
