<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmet Yakar on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Yakar on Medium]]></description>
        <link>https://medium.com/@mr-yakar?source=rss-ef7b7e79da5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*72L8DSYTwG6DpPwCdkjp9Q.jpeg</url>
            <title>Stories by Ahmet Yakar on Medium</title>
            <link>https://medium.com/@mr-yakar?source=rss-ef7b7e79da5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:52:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mr-yakar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Every Field Is Atomic. The Balance Is Still Negative.]]></title>
            <link>https://medium.com/@mr-yakar/every-field-is-atomic-the-balance-is-still-negative-bcd22afc9c3a?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd22afc9c3a</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 12:52:10 GMT</pubDate>
            <atom:updated>2026-11-03T12:52:10.399Z</atom:updated>
            <content:encoded><![CDATA[<p>No lock anywhere, and the account still overdraws. What compare-and-set does, what it actually compares, and when it runs your code twice.</p><figure><img alt="Cover image. On the left, the word CAS and the title “Every Field Is Atomic. The Balance Is Still Negative.” On the right, a table of runs where eight threads withdraw 100 from a balance of 100. Five check-then-act runs overdrew in 4,550 to 5,683 of 10,000 rounds, with the lowest balance at -700 or -600. The cas runs overdrew in 0 of 10,000 rounds, lowest 0." src="https://cdn-images-1.medium.com/max/1024/1*LhNqiOLVIIUAzYSVZVCYvw.png" /></figure><h3>TL;DR</h3><ul><li>An AtomicLong balance, no locks, 8 threads withdrawing 100 from 100: the balance went negative in 4,550–5,683 of 10,000 rounds, down to -700. Each call was atomic. The check and the write together were not.</li><li>The same program with a compareAndSet loop: 0 overdrawn rounds, in 5 of 5 runs.</li><li>That loop is the same idea as the version column from the PostgreSQL article, one layer down: write only if nothing changed, otherwise start over.</li><li>On x86, the compiled getAndIncrement is a single instruction with no loop around it. Switch that optimization off and it becomes a compare-and-set, with a retry loop once threads compete.</li><li>updateAndGet ran its function 31,339,201–39,623,599 times for 8,000,000 updates on 8 threads. The function must have no side effects.</li><li>No lock does not mean no waiting: at 8 threads, 1.11–2.20 attempts failed for every success, one increment took 6,694 tries, and a thread dump showed nothing unusual.</li><li>LongAdder trades memory for throughput on hot counters. It has no compare-and-set and its sum() is not a snapshot, so never check a balance with it.</li><li>compareAndSet compares references: on a default JVM, 127 matches and 1000 does not. It cannot see 100 -&gt; 50 -&gt; 100 either. A stamp can.</li><li>Two fields that must change together: two AtomicLongs let 600–797 of 10,000 windows go over a limit of 10. One immutable record: 0.</li></ul><blockquote><strong><em>Environment for every output in this article:</em></strong><em> Intel Core i7–4700HQ (4 cores / 8 threads, x86–64), 16 GB DDR3–1600, Ubuntu 26.04, Amazon Corretto 25.0.4 (every demo also run on 21.0.11, same direction). Counts will differ on your machine; the direction will not. The machine-code section needs x86–64.</em></blockquote><p><strong>Source code.</strong> Every program is in the <a href="https://github.com/mryakar/article-examples">article-examples</a> repository, under cas-atomic-classes/. Each demo is one Java file with no dependencies; the README has the command for each.</p><h3>Every Field Is Atomic</h3><p>The account from the synchronized article is back. There, two locks on two accounts deadlocked. Here there is no lock at all — so no deadlock either.</p><p>The balance is an AtomicLong. A withdrawal reads it with get() and writes it with addAndGet():</p><pre>static boolean withdraw(Account from, long amount) {<br>    if (from.balance.get() &gt;= amount) {<br>        from.balance.addAndGet(-amount);<br>        return true;<br>    }<br>    return false;<br>}</pre><p>Read it line by line and nothing looks wrong. Every call on the balance is atomic.</p><p>Account &quot;A&quot; starts with 100. Eight threads try to withdraw 100 from it at the same moment, so at most one of them should succeed. The program repeats this 10,000 times and counts the rounds that end below zero. Five runs:</p><pre>overdrawn 4567/10000 rounds, lowest -700<br>overdrawn 5683/10000 rounds, lowest -700<br>overdrawn 5450/10000 rounds, lowest -700<br>overdrawn 4615/10000 rounds, lowest -600<br>overdrawn 4550/10000 rounds, lowest -600</pre><p>On JDK 25, about half of the rounds overdrew, in every run. A balance of -700 means all eight threads withdrew: 100 was there, 800 went out.</p><p>Every call on the balance was atomic. So where did the overdraft come from?</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- An AtomicLong balance, no locks, eight threads withdrawing 100 from 100 at once.</blockquote><blockquote>- Every call on the balance is atomic.</blockquote><blockquote>- The balance went negative in 4,550–5,683 of 10,000 rounds, in all 5 runs.</blockquote><blockquote>- In the worst rounds all eight withdrew, and the balance ended at -700.</blockquote><h3>What One Atomic Call Buys You</h3><p>The first Java article ended with a counter that lost updates. count++ is a read, an add and a write, and two threads can both sit inside those three steps.</p><p>Here is that counter twice. Two threads, a million increments each; only the type of the counter changes. Two of the five runs:</p><pre>volatile int : 927,485 of 2,000,000<br>AtomicInteger: 2,000,000 of 2,000,000<br>volatile int : 1,343,315 of 2,000,000<br>AtomicInteger: 2,000,000 of 2,000,000</pre><p>AtomicInteger lost nothing, in every run. Its incrementAndGet() reads, adds and writes as <strong>one indivisible step</strong>. No other thread can see or change the value halfway through.</p><p>That is the whole guarantee, but it has a limit: it covers <strong>one call</strong>. Put two atomic calls next to each other and you get two atomic steps, not one. Between them, every other thread is free to run.</p><p>That is exactly what withdraw does. get() is atomic. addAndGet() is atomic. Between them, other threads also read 100, also pass the check, and also write. Each check was true when it ran. By the time its write ran, it was no longer true.</p><p>Two atomic calls leave a gap. What closes it?</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- AtomicInteger fixes the counter from the first article: 2,000,000 of 2,000,000, every run.</blockquote><blockquote>- The same work with volatile int kept 927,485–1,343,315.</blockquote><blockquote>- The guarantee is per call. Two atomic calls in a row are not one atomic operation.</blockquote><blockquote>- The overdraft happens between the check and the write.</blockquote><h3>Compare-and-Set: The Conditional Write</h3><p>The fix is not a lock. It is a condition on the write.</p><p>compareAndSet(expectedValue, newValue) writes only if the value is still the one you expected, and tells you whether it did. In the words of the documentation, it <em>&quot;atomically sets the value to </em><em>newValue if the current value </em><em>== expectedValue.&quot;</em> Nobody waits. A thread that loses gets false back and decides what to do next.</p><p>A withdrawal becomes a loop: read the balance, check it, try to write, and start over if someone else wrote first:</p><pre>static boolean withdrawCas(Account from, long amount) {<br>    while (true) {<br>        long current = from.balance.get();<br>        if (current &lt; amount) return false;<br>        if (from.balance.compareAndSet(current, current - amount)) {<br>            return true;<br>        }<br>    }<br>}</pre><p>Several threads can still read 100 and pass the check. Only one compareAndSet finds 100 there. The ones that lose find 0, write nothing, and go around the loop again — where the check now fails.</p><figure><img alt="Animation: two threads both read a balance of 100 and both pass the check. Thread A’s compare-and-set succeeds and the balance becomes 0. Thread B’s compare-and-set fails because the balance is no longer 100. Thread B reads again, sees 0, and withdraws nothing." src="https://cdn-images-1.medium.com/max/880/1*WxmTlsTUaIU1gWjoSD1tAQ.gif" /><figcaption>The thread that loses does not write. It reads again, and this time the check says no.</figcaption></figure><p>Same program, same eight threads, same 10,000 rounds; only the body of withdraw changed. All five runs printed the same line:</p><pre>cas             overdrawn 0/10000 rounds, lowest 0</pre><p>If you read the PostgreSQL article on explicit locking, you have seen this before. It ended with <em>“a third option that belongs to neither column”</em>:</p><pre>UPDATE accounts SET <br>balance = ?, <br>version = version + 1<br>WHERE <br>id = ? AND version = ?;</pre><p>and with the line <em>“That is compare-and-set, written in SQL. Java has the same idea in hardware — and that is the next article.”</em> This is that article. The version column and compareAndSet share one idea: write only if nothing changed since you read, otherwise start over. One guards a row, the other a memory cell.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- compareAndSet writes only if the value is still the one you read. Nobody waits.</blockquote><blockquote>- A withdrawal becomes a loop: read, check, compare-and-set, start over if it failed.</blockquote><blockquote>- Same program, one loop added: 0 overdrawn rounds in 10,000, in all 5 runs.</blockquote><blockquote>- It is the same idea as the version column from the PostgreSQL article, one layer down.</blockquote><h3>One Instruction Underneath</h3><p>How can compare-and-set itself be one step? The synchronized article promised <em>&quot;compare-and-swap, and the atomic classes built on it.&quot;</em> This section looks at what those classes are built on.</p><p>On x86, compare-and-set is a single processor instruction, lock cmpxchg: compare and write in one step that no other core can split. It can still fail, so it sits inside a loop like the one above. Does every atomic class run that loop? Not the most common method. When the JIT compiles getAndIncrement(), it uses a different instruction, lock xadd, which adds and returns the old value in one step. There is nothing to compare, so nothing to try again. Switch that optimization off, and the same method goes back to lock cmpxchg:</p><pre>getAndIncrement: lock xadd, loop: no<br>intrinsic off  : lock cmpxchg, loop: no<br>off, 4 threads : lock cmpxchg, loop: yes</pre><p>Five runs, the same three lines. The loop only shows up in the compiled code when threads compete. With one thread there was no competition, and the JIT compiled the failure path as a rare exit back to slower code instead of a loop. How to print and read this machine code is in the repository’s README. You do not need it to use the class.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Compare-and-set is one CPU instruction that can fail, so it sits inside a loop.</blockquote><blockquote>- On x86, compiled getAndIncrement is one instruction with no loop around it.</blockquote><blockquote>- Switch that optimization off and it becomes a compare-and-set, with a retry loop once threads compete.</blockquote><h3>The Loop Can Run Your Code Twice</h3><p>You rarely write that loop by hand. updateAndGet(fn) writes it for you: read the value, apply your function, compare-and-set the result, start over if another thread got there first. Starting over means calling your function again. The documentation says so directly: <em>&quot;The function should be side-effect-free, since it may be re-applied when attempted updates fail due to contention among threads.&quot;</em></p><p>How often? This function counts its own calls, a million updates per thread:</p><pre>value.updateAndGet(v -&gt; {<br>    calls.incrementAndGet();   // a side effect<br>    return v + 1;<br>});</pre><pre>1 thread : 1,000,000 calls for 1,000,000 updates<br>8 threads: 39,623,599 calls for 8,000,000 updates<br>8 threads: 31,339,201 calls for 8,000,000 updates</pre><p>With one thread, every update succeeded on the first try: one call per update. With eight threads, the highest and lowest of five runs show <strong>about four to five calls for every update</strong>, on this machine. Counting the calls is itself one more shared update, so it adds to the contention. The final value was correct every time. Only the side effect multiplied.</p><p>So nothing goes inside that function except computing the new value. A log line would print several times for one update. A counter would count too much. A call to another service would be made several times.</p><p>The MVCC article had the same rule one layer up, for a database transaction: <em>“The transaction body will run more than once.”</em> Here the body is your lambda.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- updateAndGet runs the compare-and-set loop for you — including your function.</blockquote><blockquote>- With 8 threads, the function ran 31,339,201–39,623,599 times for 8,000,000 updates.</blockquote><blockquote>- With 1 thread, calls and updates were equal: 1,000,000 each.</blockquote><blockquote>- Keep the function pure: no logging, no I/O, no counters of its own.</blockquote><h3>No Lock Does Not Mean No Waiting</h3><p>The previous section counted calls to the function. This one counts the attempts themselves: a compare-and-set loop that counts its own failures and does nothing else, a million increments per thread, with 1, 2, 4 and 8 threads.</p><pre>1 thread : 0.00 failed per success, worst 1<br>2 threads: 0.72 failed per success, worst 2092<br>4 threads: 0.89 failed per success, worst 849<br>8 threads: 2.20 failed per success, worst 6694</pre><p>Each line is the fifth of five runs for that thread count. With one thread, nothing ever failed. With eight, one to two attempts failed for every one that succeeded — between 1.11 and 2.20 across the five runs. The worst single increment changes a lot between runs; in one run it took 6,694 tries.</p><p>The reason is that every thread fights over the same memory location, and only one attempt at a time can win. The first Java article showed that the hardware keeps caches in sync: one core writes, the others are told. Here all eight threads work on that one location at once.</p><p>No thread waits for a lock, but every thread waits for its turn to win. And nothing shows it. Here is a thread dump taken while eight threads spin:</p><pre>dump: RUNNABLE 8/8, waiting to lock 0, parked 0<br>dump: deadlock reported: no</pre><p>All eight are RUNNABLE. Nothing waits for a lock, nothing is parked, no deadlock. In the synchronized article, the dump pointed straight at the problem. Here there is nothing to point at. You only see this kind of contention if you count it.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- No thread waited for a lock, yet at 8 threads 1.11–2.20 attempts failed for each success.</blockquote><blockquote>- One single increment took 6,694 tries.</blockquote><blockquote>- A thread dump showed all 8 threads RUNNABLE and nothing waiting. You only see this if you count.</blockquote><h3>LongAdder: Stop Fighting Over One Cell</h3><p>If everyone fights over one cell, give them more cells. The first Java article listed <em>“</em><em>LongAdder when the counter is hot and heavily contended&quot;</em> and said it deserves an article of its own.</p><p>The idea is simple. When threads compete, a LongAdder spreads the count over several variables, so different threads update different ones. Reading it adds them up.</p><p>How much faster is that? This article has no benchmark for it, and will not guess. The documentation states the expectation: <em>“Under low update contention, the two classes have similar characteristics. But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.”</em></p><p>The price is in the read. For sum(), the documentation says: <em>&quot;The returned value is NOT an atomic snapshot; invocation in the absence of concurrent updates returns an accurate result, but concurrent updates that occur while the sum is being calculated might not be incorporated.&quot;</em> The class description already says what it is for: statistics, <em>&quot;not for fine-grained synchronization control.&quot;</em></p><p>So back to the opening: <strong>a balance is never a </strong><strong>LongAdder.</strong> It has no compare-and-set: it can add, but it cannot write only if a check still holds. And sum() can miss the updates that happen while it adds.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- LongAdder spreads a hot counter over several variables and adds them up when you read.</blockquote><blockquote>- Its documentation expects much higher throughput under heavy contention, paid in memory.</blockquote><blockquote>- It has no compare-and-set, and sum() is not a snapshot. Never use it for a value you check before acting.</blockquote><h3>What compareAndSet Actually Compares</h3><p>compareAndSet asks one question: is the value still the one I read? There are two ways the answer can mislead you.</p><p><strong>It compares references.</strong> For an AtomicReference, the write happens <em>&quot;if the current value </em><em>== expectedValue&quot;</em> — ==, not equals(). Put boxed numbers in it and try compareAndSet(127, 128) on a reference holding 127, then compareAndSet(1000, 1001) on one holding 1000:</p><pre>default JVM:   CAS(127) = true  CAS(1000) = false<br>cache 1000:    CAS(127) = true  CAS(1000) = true</pre><p>On a default JVM, 127 matched and 1000 did not. The JVM reuses one Integer object for small values, so both 127s are the same object; each 1000 is a new one. The second line is the same program with a larger cache:</p><pre>java -XX:AutoBoxCacheMax=1000 IdentityTrap cache1000</pre><p>Now 1000 matches too. The language guarantees a shared object only from -128 to 127; beyond that, it depends on the JVM. For numbers, AtomicInteger avoids the question entirely. The rule is short: <strong>pass the reference you read</strong> as the expected value, not a new value that looks equal.</p><p><strong>It cannot see history.</strong> A thread reads a balance of 100 and is about to write 70. Before it does, another thread changes the balance to 50, then back to 100. The first thread’s compareAndSet(100, 70) succeeds — the value is the same. But somebody touched it in between. &quot;Same value&quot; and &quot;nobody touched it&quot; are different statements. This is the <strong>ABA problem</strong>. For a plain number it does no harm: 70 is still the right result. It matters when the value stands for more than itself — when &quot;nothing changed since I read it&quot; is the rule you are enforcing.</p><p>AtomicStampedReference keeps an integer stamp next to the value and compares both. Every writer must move the stamp, so a change and its undo still leave a mark:</p><figure><img alt="Animation: thread A reads a balance of 100 with stamp 0 and pauses. Another thread changes the balance to 50 and back to 100, and the stamp moves to 2. A plain compareAndSet from 100 to 70 succeeds. The stamped compareAndSet fails because the stamp is 2, not 0." src="https://cdn-images-1.medium.com/max/880/1*ZjvJtY1f4UZI0roXZbq8QQ.gif" /><figcaption><em>Comparing values tells you the value is the same, not that nobody touched it.</em></figcaption></figure><pre>plain   : CAS(100 -&gt; 70) = true<br>stamped : CAS(100 -&gt; 70) = false (stamp 0, now 2)</pre><p>A version column is the same stamp. WHERE balance = ? would not notice 100 -&gt; 50 -&gt; 100. WHERE version = ? would.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- compareAndSet on an AtomicReference compares references, not equals().</blockquote><blockquote>- On a default JVM, 127 matched and 1000 did not. Pass the reference you read.</blockquote><blockquote>- It cannot see 100 -&gt; 50 -&gt; 100. AtomicStampedReference can: stamp 0 was now 2.</blockquote><blockquote>- A version column is the same stamp.</blockquote><h3>When One Variable Is Not Enough</h3><p>The package documentation states its own limit in its first sentence: <em>“A small toolkit of classes that support lock-free thread-safe programming on single variables.”</em> <strong>Single variables.</strong></p><p>Take a limiter: at most 10 requests per time window. It keeps two values — when the current window started, and how many requests it has let through. When a new window begins, both must change together.</p><p>With two AtomicLongs, each call is atomic and the decision is not. Several threads see the new window at about the same time, and each one sets the start and resets the count to zero. A reset that happens after other threads have already counted wipes their counts. The counting starts over, and more requests get through.</p><p>Eight threads send four requests each into the same window: 32 attempts, at most 10 should pass. Ten thousand windows, two of five runs, then the fix:</p><pre>two-atomics over limit in 797/10000 windows, most 32<br>two-atomics over limit in 600/10000 windows, most 31<br>one-record  over limit in 0/10000 windows, most 10</pre><p>most 32 means that in at least one window every single request got through.</p><p>The fix puts both values in one immutable record and swaps the whole thing at once:</p><pre>record Window(long start, int count) {}<br><br>public boolean tryAcquire(long now) {<br>    while (true) {<br>        Window w = window.get();<br>        Window next;<br>        if (w.start() != now) next = new Window(now, 1);<br>        else if (w.count() &gt;= LIMIT) return false;<br>        else next = new Window(now, w.count() + 1);<br>        if (window.compareAndSet(w, next)) return true;<br>    }<br>}</pre><p>The same loop as the withdrawal: read, decide, compare-and-set, start over on failure. Both values change in one write, so no thread ever sees one without the other. Note the expected value is w, the reference that was read — the rule from the previous section. A new Window with the same fields would never match.</p><p>This works because building a Window is cheap and has no side effects. If the update is expensive, every failed attempt repeats it. If it has side effects, they repeat too. Then a small lock, as in the synchronized article, is the honest answer.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Atomic classes protect one variable. Two fields that must change together are one decision.</blockquote><blockquote>- Two AtomicLongs let 600–797 of 10,000 windows go over a limit of 10, up to 32.</blockquote><blockquote>- One immutable record behind an AtomicReference: 0 windows over the limit, every run.</blockquote><blockquote>- If the update is expensive or has side effects, a small lock is the honest answer.</blockquote><h3>Lock, Atomic, or Neither</h3><ul><li><strong>One counter, few writers:</strong> AtomicInteger or AtomicLong</li><li><strong>One counter, many writers, read rarely:</strong> LongAdder</li><li><strong>Check, then write one value:</strong> a compareAndSet loop, or updateAndGet with a pure function</li><li><strong>Several values, one rule:</strong> one immutable record in an AtomicReference, or a lock</li><li><strong>Side effects in the update:</strong> a lock</li></ul><p>The synchronized article ended with <em>&quot;The fastest lock is the one you did not take&quot;</em>. That is still true, but the cost of the lock you did not take does not disappear. It moves into the loop: failed attempts, functions that run twice, contention that no thread dump shows.</p><p>Every compare-and-set loop in this article is a retry that only touches memory. The next article is about the retries that touch a database, a network and someone’s money — and what makes running them twice safe.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- One value, one rule: an atomic class. Check then write: a compare-and-set loop.</blockquote><blockquote>- Hot counters: LongAdder, never for a value you check.</blockquote><blockquote>- Several values: one immutable record, or a lock.</blockquote><h3>References</h3><p><strong>API documentation</strong></p><ul><li><em>java.util.concurrent.atomic — package summary.</em> The “single variables” sentence.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/package-summary.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/package-summary.html</a></li><li><em>AtomicInteger</em> — compareAndSet, getAndIncrement, updateAndGet and the side-effect-free rule.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicInteger.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicInteger.html</a></li><li><em>AtomicReference</em> — compareAndSet with ==.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicReference.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicReference.html</a></li><li><em>AtomicStampedReference</em> — a reference plus an integer stamp, updated together.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicStampedReference.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/AtomicStampedReference.html</a></li><li><em>LongAdder</em> — the contention and memory trade-off, and sum() as a non-snapshot.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/LongAdder.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/LongAdder.html</a></li><li><em>Integer.valueOf</em> — which boxed values are guaranteed to be shared.<br> <a href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html">https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html</a></li></ul><p><strong>Further reading</strong></p><ul><li>Brian Goetz et al., <em>Java Concurrency in Practice</em>, chapter 15 — <em>Atomic Variables and Nonblocking Synchronization.</em></li><li>Martin Kleppmann and Chris Riccomini, <em>Designing Data-Intensive Applications</em>, 2nd edition, chapter 8 — conditional writes (compare-and-set).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd22afc9c3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explicit Locking in PostgreSQL]]></title>
            <link>https://medium.com/@mr-yakar/explicit-locking-in-postgresql-6ed90ddc7e16?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed90ddc7e16</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 17:49:24 GMT</pubDate>
            <atom:updated>2026-09-16T17:49:24.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZjdVt-1OP_XrdtpB5w03w.jpeg" /></figure><p><em>Two ordinary UPDATEs are enough for a deadlock. What row locks actually do, and who decides which transaction dies.</em></p><p>TL;DR</p><ul><li>Two plain UPDATE statements are enough to deadlock. You do not have to write a single lock to get 40P01.</li><li>Table-level lock names are misleading: ROW SHARE and ROW EXCLUSIVE are <strong>table</strong> locks. Only the conflict list matters.</li><li><strong>Only </strong><strong>ACCESS EXCLUSIVE blocks a plain </strong><strong>SELECT.</strong> That is what makes ALTER TABLE, DROP, TRUNCATE and VACUUM FULL dangerous in production — and index builds safe, with CONCURRENTLY.</li><li>Row locks have four modes on two axes: shared or exclusive, key-touching or not. The middle two exist so <strong>foreign key checks do not block ordinary updates</strong>.</li><li><strong>Row locks never block readers.</strong> Only another writer on the same row waits.</li><li>The same SELECT ... FOR UPDATE behaves differently per isolation level: <strong>Read Committed adapts, Repeatable Read gives up</strong> with a serialization failure.</li><li>Deadlock here is the same problem as in Java: <strong>circular wait</strong>, fixed the same way — a consistent lock order, which in SQL is ORDER BY id FOR UPDATE.</li><li><strong>The victim is not random.</strong> Each waiting session checks for a cycle exactly once, deadlock_timeout after it starts waiting, and whoever runs that check aborts itself. Too low a timeout and your check runs <em>before</em> the cycle exists: the same deadlock took 0.2 s or 10.0 s to detect, depending only on whose timer was set to what.</li><li><strong>Advisory locks lock a number, not a row.</strong> They are reentrant, and how many times a session holds one is invisible in pg_locks.</li><li>A session-level advisory lock <strong>survives </strong><strong>ROLLBACK and survives being returned to a connection pool.</strong> That is how &quot;only one instance runs this job&quot; fails silently.</li></ul><blockquote><strong><em>Environment for every output in this article:</em></strong></blockquote><blockquote><em>- Intel Core i7–4700HQ (4 cores / 8 threads, x86–64), 16 GB DDR3–1600</em></blockquote><blockquote><em>- Ubuntu 26.04</em></blockquote><blockquote><em>- PostgreSQL 18.6 with </em><em>autovacuum off .</em></blockquote><blockquote><em>Every SQL scenario below is in the </em><strong><em>article-examples</em></strong><em> repository, under </em><em>postgres-explicit-locking/, with the steps numbered so you can run them yourself in two or three psql sessions.</em></blockquote><blockquote><em>Source: [</em><a href="https://github.com/mryakar/article-examples/tree/master/postgres-explicit-locking"><em>github.com/…</em></a><em>]</em></blockquote><h3>The Deadlock You Did Not Ask For</h3><p>Two accounts, two transactions, money moving in both directions.</p><pre>-- T1                                    -- T2<br>BEGIN;                                   BEGIN;<br>UPDATE ... SET balance-100 WHERE id=100;<br>                                         UPDATE ... SET balance-100 WHERE id=200;<br>UPDATE ... SET balance+100 WHERE id=200;  -- waits<br>                                         UPDATE ... SET balance+100 WHERE id=100;</pre><p>No LOCK TABLE, no explicit lock statement of any kind — four ordinary UPDATEs. T1&#39;s second statement blocks. Then T2 runs its second, and the database answers:</p><pre>ERROR:  40P01: deadlock detected<br>DETAIL:  Process 1583 waits for ShareLock on transaction 760; blocked by process 1584.<br>         Process 1584 waits for ShareLock on transaction 761; blocked by process 1583.<br>HINT:  See server log for query details.<br>CONTEXT:  while updating tuple (0,1) in relation &quot;accounts&quot;</pre><p>T2 is aborted. T1 wakes up, finishes, and commits — 100 | Ali | 900.00, 200 | Ayşe | 1100.00.</p><p>Nobody asked for a lock. Postgres took them anyway.</p><blockquote>In short</blockquote><blockquote>- Two UPDATEs on two rows, in opposite order, are enough to deadlock.</blockquote><blockquote>- No explicit lock was written anywhere in the code.</blockquote><blockquote>- Postgres detected the cycle and aborted one transaction with 40P01; the other committed.</blockquote><blockquote>- Which one dies, and why, comes later.</blockquote><h3>The Locks You Take Without Asking</h3><p>The names are misleading: ROW SHARE and ROW EXCLUSIVE are <strong>table-level</strong> locks. The documentation says so directly — <em>&quot;all of these lock modes are table-level locks, even if the name contains the word row; the names of the lock modes are historical.&quot;</em> They also have no behavior of their own. A mode is only a <strong>list of modes it conflicts with</strong>: two transactions cannot hold conflicting modes on the same table at once, and everything else runs.</p><pre>lock mode                taken by<br>-----------------------  -------------------------------------------<br>ACCESS SHARE             SELECT<br>ROW SHARE                SELECT ... FOR UPDATE / FOR SHARE<br>ROW EXCLUSIVE            INSERT, UPDATE, DELETE<br>SHARE UPDATE EXCLUSIVE   VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY<br>SHARE                    CREATE INDEX<br>SHARE ROW EXCLUSIVE      CREATE TRIGGER<br>EXCLUSIVE                REFRESH MATERIALIZED VIEW CONCURRENTLY<br>ACCESS EXCLUSIVE         DROP, TRUNCATE, VACUUM FULL, most ALTER TABLE</pre><p>The top three do not conflict with each other, so readers, inserters and updaters never queue at the table level; when two of them do wait, it is over a <strong>row</strong>. At the other end of the list, <strong>ACCESS EXCLUSIVE is the only mode that blocks a plain </strong><strong>SELECT:</strong></p><pre>T1: BEGIN; LOCK TABLE accounts IN ROW EXCLUSIVE MODE;<br>T2: SELECT count(*) FROM accounts;      -- does not wait<br>T2: INSERT INTO accounts ...;           -- does not wait<br><br>T1: BEGIN; LOCK TABLE accounts IN ACCESS EXCLUSIVE MODE;<br>T2: SELECT count(*) FROM accounts;      -- BLOCKED</pre><p>That second block is what makes migrations risky: the statement may be fast, but it must acquire the lock first, and while it waits behind one long-running query every new SELECT queues behind it. Index builds show both sides — CREATE INDEX takes SHARE and stops writes; CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE and does not, at the cost of two table scans and no transaction block.</p><p>One property matters for two later sections: <strong>a lock is held until the transaction ends</strong>, never released early.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Every statement takes a table-level lock, asked for or not.</blockquote><blockquote>- The names are historical: ROW EXCLUSIVE is a table lock.</blockquote><blockquote>- A lock mode has no behavior of its own — only a conflict list.</blockquote><blockquote>- SELECT, INSERT and UPDATE do not conflict at the table level.</blockquote><blockquote>- Only ACCESS EXCLUSIVE blocks a plain SELECT. That is what makes DDL dangerous.</blockquote><h3>Reserving a Row: FOR UPDATE and Its Three Siblings</h3><p>SELECT ... FOR UPDATE means: I am reading this row, I will write based on what I read, and nobody may change it in between. It is the lock for check-then-act logic. There are four such modes, on two axes — shared or exclusive, touching the key or not.</p><pre>            mode                what it reserves<br>            ------------------  ------------------------------------<br>shared      FOR KEY SHARE       only the key: no change, no delete<br>            FOR SHARE           the whole row, while I read it<br><br>exclusive   FOR NO KEY UPDATE   the row, except its key<br>            FOR UPDATE          the whole row</pre><p>Two shared modes coexist; an exclusive mode coexists with nothing. FOR UPDATE conflicts with all four, FOR KEY SHARE only with FOR UPDATE.</p><p>One cost before using FOR UPDATE over a large result set: a row lock is not kept in memory. It is <strong>written into the tuple</strong>, in the xmax field that an UPDATE or DELETE also writes. A million locked rows means a million tuple writes, each one WAL traffic and later vacuum work; there is no lock-table limit to hit because the locks are on disk. This also answers something the previous article left open — a non-zero xmax can mean the row is only locked, not deleted.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Four modes on two axes: shared or exclusive, key-touching or not.</blockquote><blockquote>- Two shared modes coexist; an exclusive mode coexists with nothing.</blockquote><blockquote>- FOR UPDATE is the one for check-then-act logic.</blockquote><blockquote>- A row lock is written into the tuple’s xmax, so a million rows cost a million writes.</blockquote><h3>Why the Middle Modes Exist</h3><p>FOR KEY SHARE and FOR NO KEY UPDATE exist because of <strong>foreign keys</strong>. Three transactions on a customers table and its child orders:</p><pre>T1: BEGIN; INSERT INTO orders(customer_id, amount) VALUES (42, 100);<br>    -- the FK check takes FOR KEY SHARE on customers(42)<br>T2: BEGIN; UPDATE customers SET name = &#39;Ali Veli&#39; WHERE id = 42;<br>    -- name is not a key -&gt; FOR NO KEY UPDATE -&gt; does NOT wait<br>T3: BEGIN; DELETE FROM customers WHERE id = 42;<br>    -- DELETE always takes FOR UPDATE -&gt; WAITS</pre><p>T2 does not wait, T3 does, and the only difference is which mode each one needs. Postgres chooses the mode by looking at what you touched: a foreign key check takes FOR KEY SHARE on the parent row, an UPDATE takes FOR UPDATE if it touches a key column and FOR NO KEY UPDATE if it does not, and a DELETE always takes FOR UPDATE.</p><p>Without the middle modes a foreign key check would have to take the exclusive one. Every INSERT into orders would lock the customer row, and every request renaming that customer would queue behind it — a bottleneck built into the schema for any row many children point to.</p><blockquote><strong>In short</strong></blockquote><blockquote>- The middle modes exist so foreign key checks do not block ordinary updates.</blockquote><blockquote>- An INSERT into a child table takes FOR KEY SHARE on the parent row.</blockquote><blockquote>- A non-key UPDATE takes FOR NO KEY UPDATE and does not conflict with it.</blockquote><blockquote>- DELETE always takes FOR UPDATE and does conflict.</blockquote><blockquote>- Postgres picks the mode from the columns you touch.</blockquote><h3>Row Locks Do Not Block Readers</h3><p>T1 locks row 100 and holds it. T2 then tries four things:</p><pre>T2: SELECT * FROM accounts WHERE id = 100;     -- does not wait, returns 1000.00<br>T2: SELECT count(*) FROM accounts;             -- does not wait<br>T2: UPDATE accounts SET ... WHERE id = 200;    -- does not wait<br>T2: UPDATE accounts SET ... WHERE id = 100;    -- BLOCKED</pre><p>Three out of four do not wait. The locked row is still readable, as the last committed version — MVCC, as described in the previous article. A lock reserves the row for <em>writing</em>, so only the fourth statement waits.</p><p>Lock granularity is therefore contention granularity. In a table of a million accounts, holding row 100 affects transactions touching row 100 and nothing else: two payments from the same account are serialized, which correctness requires, and two payments from different accounts never meet.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- A row locked FOR UPDATE is still readable by any plain SELECT, with no wait.</blockquote><blockquote>- Full scans are unaffected; only a writer on the same row waits.</blockquote><blockquote>- Lock granularity is contention granularity: different customers never touch.</blockquote><h3>FOR UPDATE Across Isolation Levels</h3><p>The waiting is identical at all three levels. The difference appears <em>after</em> the other transaction commits. T1 reads a balance of 1000.00 and holds its snapshot, T2 changes that row to 500.00 and commits, and T1 then runs SELECT ... FOR UPDATE on it:</p><pre>Read Committed    500.00, no error<br>Repeatable Read   ERROR:  could not serialize access<br>Serializable      ERROR:  could not serialize access</pre><p>The full message in both error cases is could not serialize access due to concurrent update.</p><p>Read Committed <strong>adapts</strong>: it waits for the winner, then locks the <em>new</em> version and re-evaluates the WHERE clause against it. Repeatable Read <strong>gives up</strong>, because its snapshot is frozen for the whole transaction and the row it is handed is not the row it agreed to see.</p><p>This is the locking side of a behavior the previous article showed from the other direction: at Read Committed an UPDATE ... WHERE balance &gt; 500 that loses a race re-checks its condition and skips the row silently if it no longer qualifies, reported only as UPDATE 0. FOR UPDATE prevents that. Under Serializable the reverse holds — it is usually unnecessary, because SSI already tracks the read-write dependencies, and adding locks on top gives you the waiting <em>and</em> the retries.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- All three levels wait the same way; they differ after the winner commits.</blockquote><blockquote>- Read Committed locks the new version and re-evaluates WHERE. No error.</blockquote><blockquote>- Repeatable Read and Serializable raise a serialization failure. You must retry.</blockquote><blockquote>- Pick one: pessimistic locking at Read Committed, or optimistic retry at Serializable.</blockquote><h3>The Same Problem: Circular Wait</h3><p>Now the answer to the opening. The two transactions took row locks in opposite order: T1 locked row 100 and then wanted row 200, T2 locked row 200 and then wanted row 100. Each holds what the other needs, and neither can release early, because a row lock lives until the end of its transaction.</p><figure><img alt="Two transaction boxes on the left, two row boxes on the right. Solid arrows show T1 holding row 100 and T2 holding row 200. Dashed arrows cross between them, each transaction waiting for the row the other holds. T2’s box then dims and an error line reads “deadlock detected (40P01)”." src="https://cdn-images-1.medium.com/max/880/1*wFlwekQupIJk9aMPnCmaYQ.gif" /></figure><p><em>Neither transaction mentions a lock. The </em><em>UPDATE statements took them, and the order they took them in is the bug.</em></p><p>This is the same failure as two Java threads calling synchronized on two accounts in opposite order: same cycle, same four conditions, same fix. Deadlock is a <strong>resource ordering</strong> problem, not a database or language problem. What differs is the response — PostgreSQL detects the cycle and aborts a participant, while the JVM detects it, prints it in a thread dump, and does nothing.</p><p><strong>Ordering removes it.</strong> Lock the rows in a fixed order, in one statement:</p><pre>SELECT id FROM accounts WHERE id IN (100, 200) ORDER BY id FOR UPDATE;</pre><p>Both transactions now acquire in the same direction, and the second blocks at row 100 <strong>while holding nothing</strong>:</p><figure><img alt="Two panels. On the left, T1 locks 100 then 200 while T2 locks 200 then 100, and a caption says the cycle closes. On the right, both transactions lock 100 then 200, and T2 stops at the first row holding nothing." src="https://cdn-images-1.medium.com/max/880/1*nfxrsMXcIAK3wwA7uLUTXA.gif" /></figure><p><em>The loser waits at the first row. There is no second edge for a cycle to close on.</em></p><p>That is structural, not statistical: a transaction that holds nothing cannot be waited on, so the wait-for graph cannot contain a cycle.</p><p><strong>The first surprise: ordering is not always enough.</strong> Two transactions read the same row with FOR SHARE — no conflict, both succeed. Then both try to upgrade to FOR UPDATE, and each waits for the other&#39;s shared lock:</p><pre>ERROR:  deadlock detected<br>CONTEXT:  while locking tuple (0,1) in relation &quot;accounts&quot;</pre><p>One row, same order, deadlock anyway. There is nothing to order, so the fix is the mode: <strong>take the most restrictive lock you will need, the first time you touch the row.</strong> Note the CONTEXT line too — the opening deadlock said while updating tuple, this one says while locking tuple, which tells you whether the collision was a plain write or an explicit lock request.</p><p><strong>The second surprise: the victim is not random.</strong> The usual advice is that you cannot predict which transaction is aborted, and the documentation agrees: the outcome <em>“is difficult to predict and should not be relied upon.”</em> The advice is right; the explanation behind it is usually missing.</p><p>deadlock_timeout is a <strong>per-session</strong> setting. A session that starts waiting arms a timer. When it fires, that session walks the wait-for graph, and <strong>if it finds a cycle it aborts itself</strong>. The server does not choose among candidates: the victim is whichever session ran its check while the cycle existed.</p><p>Three cases, five runs each, same deadlock every time:</p><pre>deadlock_timeout       cycle forms          victim      detected in<br>T1        T2<br>--------  --------     ------------------   ---------   -----------<br>200 ms    10 s         before T1&#39;s check    T1   5/5     0.2 s<br>10 s      200 ms       before T2&#39;s check    T2   5/5     0.2 s<br>200 ms    10 s         AFTER  T1&#39;s check    T2   5/5    10.0 s</pre><p>In the third case T1 has the 200 ms timer and is <em>not</em> the one that notices. Its check ran at 200 ms, found no cycle because the cycle did not exist yet, and never ran again; the deadlock formed at 300 ms and held both transactions until T2’s ten-second timer fired.</p><p>Each waiter checks <strong>exactly once</strong> per wait. The source shows it: ProcSleep arms DEADLOCK_TIMEOUT once before the wait loop and never re-arms it, and inside the loop CheckDeadLock runs and the flag is cleared. The reason is cost — <em>&quot;by delaying the check until we&#39;ve waited for a bit, we can avoid running the rather expensive deadlock-check code in most cases.&quot;</em></p><p>So <strong>lowering </strong><strong>deadlock_timeout can make detection later, not sooner.</strong> Your application does not change either way: catch the error and retry from the beginning, with 40001 and 40P01 on the retry list.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- The opening deadlock came from taking two row locks in opposite order — circular wait, the same failure as two Java threads locking two accounts.</blockquote><blockquote>- Lock ordering removes it structurally: the waiter waits holding nothing.</blockquote><blockquote>- It does not help when both transactions upgrade a shared lock on the same row. Take the most restrictive mode up front.</blockquote><blockquote>- The victim is whichever session runs its check while the cycle exists. Lowering deadlock_timeout can delay detection — 10.0 s instead of 0.2 s.</blockquote><h3>Locking a Number, Not a Row</h3><p>Everything so far locked data. Advisory locks lock a <strong>number</strong>: SELECT pg_advisory_lock(42). There is no row 42 and no table 42 — only your application knows what 42 means, and Postgres enforces nothing.</p><p>They exist for one pattern: <strong>only one instance in the cluster should do this.</strong> The nightly batch, the outbox relay, the scheduled job that must not run twice. Flyway takes this kind of lock before migrating; ShedLock is built on it. The variant that matters is pg_try_advisory_lock, which returns immediately instead of queueing:</p><pre>instance A:  SELECT pg_try_advisory_lock(42);   -&gt;  t     -- runs the job<br>instance B:  SELECT pg_try_advisory_lock(42);   -&gt;  f     -- skips, no wait<br>instance C:  SELECT pg_try_advisory_lock(42);   -&gt;  f     -- skips, no wait</pre><p>The obvious alternative, a job_running boolean, is worse on three counts: every set and unset writes a new row version and feeds bloat, it is slower, and a crash mid-job leaves the flag true forever. An advisory lock is released when its session ends.</p><p>There are two lifetimes:</p><pre>pg_advisory_lock(n)             -- session level<br>   released by   explicit unlock, or the session ending<br>   ROLLBACK      no effect: you still hold it<br>   unlock        required; N acquires need N releases<br><br>pg_advisory_xact_lock(n)        -- transaction level<br>   released by   end of transaction, automatically<br>   ROLLBACK      releases it<br>   unlock        not available, not needed</pre><p>The ROLLBACK row is measurable:</p><pre>A: BEGIN; SELECT pg_advisory_lock(77); ROLLBACK;<br>A: SELECT count(*) FROM pg_locks WHERE locktype=&#39;advisory&#39;;   -&gt;  1<br>B: SELECT pg_try_advisory_lock(77);                           -&gt;  f<br><br>A: BEGIN; SELECT pg_advisory_xact_lock(88); ROLLBACK;<br>A: SELECT count(*) FROM pg_locks WHERE locktype=&#39;advisory&#39;;   -&gt;  0</pre><p>The transaction was rolled back; the session-level lock is still held. The documentation states it: session-level requests <em>“do not honor transaction semantics.”</em></p><p>Two more properties matter for the next section. Advisory locks are <strong>reentrant</strong> — a session holding one always gets it again, even with others queued behind it, and each acquire needs its own release — and the count is <strong>invisible</strong>:</p><pre>A: SELECT pg_try_advisory_lock(42);  -&gt; t<br>A: SELECT pg_try_advisory_lock(42);  -&gt; t        -- same session, again<br><br>A: SELECT locktype, objid, mode FROM pg_locks WHERE locktype=&#39;advisory&#39;;<br>    locktype | objid |     mode<br>   ----------+-------+---------------<br>    advisory |    42 | ExclusiveLock              -- ONE row<br><br>A: SELECT pg_advisory_unlock(42);    -&gt; t<br>B: SELECT pg_try_advisory_lock(42);  -&gt; f        -- still held<br>A: SELECT pg_advisory_unlock(42);    -&gt; t<br>B: SELECT pg_try_advisory_lock(42);  -&gt; t        -- now it is free</pre><p>A lock held twice looks the same as a lock held once, and you cannot ask the database how many releases are outstanding.</p><p>Two limits from the documentation. Advisory locks share a fixed shared-memory pool with regular locks, sized by max_locks_per_transaction and max_connections, so one lock per user will eventually exhaust it and the server can then grant no lock at all. And in SELECT pg_advisory_lock(id) FROM foo WHERE id &gt; 12345 LIMIT 100 the LIMIT is not guaranteed to be applied before the function runs, so you can take locks you never intended and never release; put the LIMIT in a subquery. One related tool: an advisory lock means <em>one instance does this job</em>, while SELECT ... FOR UPDATE SKIP LOCKED means <em>one worker takes this item</em>.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- An advisory lock locks a number you choose; Postgres does not check what it means.</blockquote><blockquote>- Use pg_try_advisory_lock so losers skip the round instead of queueing.</blockquote><blockquote>- A session-level lock survives ROLLBACK. A transaction-level one does not.</blockquote><blockquote>- They are reentrant, and pg_locks never shows how many times one is held.</blockquote><blockquote>- Prefer pg_advisory_xact_lock unless the work spans more than one transaction.</blockquote><h3>The Ghost Lock in Your Connection Pool</h3><p>Combine the last two properties with a connection pool. A request takes a session-level advisory lock, does its work, and returns the connection — and in between the unlock is missed, through an early return, an exception, or a refactor that moved the release off the path.</p><pre>try (Connection c = pool.getConnection()) {<br>    if (tryAdvisoryLock(c, JOB_ID)) {<br>        runTheJob(c);<br>    }<br>}   // close() does NOT close the connection. It returns it to the pool.</pre><p>HikariCP does clean up on return: it rolls back an open transaction and resets autoCommit, isolation and the read-only flag. What it does not reset is <strong>session state</strong> — it sends no DISCARD ALL, and the advisory lock is session state.</p><p>Three requests through a one-connection pool, against 18.6:</p><pre>request #1 pid 2299  pg_try_advisory_lock(42) -&gt; true  =&gt; RUNS THE JOB<br>request #2 pid 2299  pg_try_advisory_lock(42) -&gt; true  =&gt; RUNS THE JOB<br>request #3 pid 2299  pg_try_advisory_lock(42) -&gt; true  =&gt; RUNS THE JOB<br>round 1  pool OPEN    advisory lock rows: 1     (expected 1)<br>round 1  pool OPEN    outsider can take it: false (expected false)<br>round 1  pool CLOSED  advisory lock rows: 0     (expected 0)</pre><figure><img alt="A connection pool box holding one connection, backend_pid 2299, with an advisory lock badge marked “never released”. Three request rows all show the same pid and all return true. Below, an instance outside the pool returns false, and a pg_locks line shows a single row with the hold count not shown." src="https://cdn-images-1.medium.com/max/880/1*x9CHweZnmsIn8djlR2XWug.gif" /></figure><p><em>Same backend process for all three requests. The guard returns true every time, and one lock row on the server is all you can see.</em></p><p>The damage runs in two directions. <strong>Outward:</strong> no other instance can take that lock, so the job they were all guarding stops running everywhere and nothing reports an error. <strong>Inward:</strong> the leaking instance passes its own guard — requests #2 and #3 got true, because advisory locks are reentrant and this is the same session. The &quot;only one instance&quot; check did not fail loudly; it returned true, and each call incremented a reference count that now needs three unlocks on a connection no request owns.</p><p>This is the same shape as a ThreadLocal left uncleared when a thread returns to its pool: a pooled resource carrying state that outlives the work it belonged to, inherited by the next unrelated task.</p><p>Diagnosis is difficult, because pg_locks shows one row whether the lock was taken once or three times. The last line above is the clearest signal: close the pool and the lock disappears, which shows it was tied to a session nobody was tracking.</p><p>The fix is to have no unlock at all. pg_advisory_xact_lock releases at the end of the transaction, on every path including the failing ones — the same three requests then return true each time, leave zero lock rows while the pool is open, and let an outsider take the lock. If the work really spans several transactions, the release belongs in a finally, with DISCARD ALL on connection return as a backstop.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- A session-level advisory lock is not released when the connection returns to the pool.</blockquote><blockquote>- The pool resets autocommit and isolation, not session state.</blockquote><blockquote>- Other instances are locked out, and the leaking instance passes its own guard, because the locks are reentrant.</blockquote><blockquote>- Same bug as a ThreadLocal left dirty on a pooled thread.</blockquote><blockquote>- Use transaction-level advisory locks unless the work spans several transactions.</blockquote><h3>Reading pg_locks</h3><p>When something is stuck, two views answer the question. Start with who is waiting:</p><pre> pid  |        state        | wait_event_type |  wait_event<br>------+---------------------+-----------------+---------------<br> 1790 | idle in transaction | Client          | ClientRead<br> 1792 | active              | Lock            | transactionid</pre><p>Process 1792 is active with wait_event_type = &#39;Lock&#39; — the victim. Process 1790 is <strong>idle in transaction</strong>: running no query, and the cause. That state is the most useful warning sign here, because no work is happening and locks are held anyway. Then the chain, from pg_locks joined to itself (the full query is in the repo; the two sides are aliased waiting and blocking):</p><pre> waiting | blocking | requested_mode | held_mode     |   locktype<br>---------+----------+----------------+---------------+---------------<br>    1792 |     1790 | ShareLock      | ExclusiveLock | transactionid</pre><p>Note the locktype: it is not a row lock. A transaction waiting for a row is recorded as waiting on the <strong>other transaction&#39;s id</strong>, a ShareLock on transactionid that is granted when that transaction ends. This is why row waits never appear as rows in pg_locks.</p><p>You do not have to write the join:</p><pre>SELECT pid, pg_blocking_pids(pid) AS blocking_pids<br>  FROM pg_stat_activity<br> WHERE cardinality(pg_blocking_pids(pid)) &gt; 0;</pre><pre> pid  | blocking_pids<br>------+---------------<br> 1792 | {1790}</pre><p>For advisory locks, WHERE locktype = &#39;advisory&#39; lists them, with the earlier caveat: the row is there, the count is not.</p><p><strong>A lock wait is unbounded by default.</strong> The documentation is explicit that a transaction seeking a lock “will wait indefinitely for conflicting locks to be released”, as long as no deadlock is detected. lock_timeout caps the waiting alone, statement_timeout caps the whole statement. Migrations want the first, so they fail fast instead of forming a queue behind a lock they cannot get.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- A waiting session shows wait_event_type = &#39;Lock&#39;; the blocker shows idle in transaction.</blockquote><blockquote>- Row lock waits are recorded on transactionid, not on the row.</blockquote><blockquote>- pg_blocking_pids() gives you the chain in one call.</blockquote><blockquote>- pg_locks will not tell you how many times an advisory lock is held.</blockquote><blockquote>- Lock waits are unbounded by default. Set lock_timeout.</blockquote><h3>Pessimistic or Optimistic — Pick One</h3><p>There are two coherent strategies, and most of the trouble comes from running half of each.</p><p><strong>Pessimistic</strong> is Read Committed, SELECT ... FOR UPDATE, and a consistent lock order. You wait, but the waiting is predictable and there are no serialization failures to handle. For a balance many transactions contend over, this is usually the right answer.</p><p><strong>Optimistic</strong> is Serializable, no explicit locks, and a retry loop around 40001 and 40P01. Nothing waits, but a hot row can produce many retries and every transaction must be safe to run twice. Serializable is the option when you cannot lock what you need to protect — an invariant across rows that do not exist yet, where predicate locks do work that FOR UPDATE cannot.</p><p>Mixing them pays both costs: you wait for locks <em>and</em> you handle serialization failures. Whichever you pick, keep transactions short, because every open transaction holds locks, widens the deadlock window and blocks cleanup.</p><p>There is a third option that belongs to neither column:</p><pre>UPDATE accounts SET balance = ?, version = version + 1<br> WHERE id = ? AND version = ?;</pre><p>No lock anywhere. Read the row, compute the new value, and write it back <strong>only if the version you read is still there</strong>. If the update affects zero rows, somebody else got there first and you start over.</p><p>That is compare-and-set, written in SQL. Java has the same idea in hardware — and that is the next article.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Pessimistic: Read Committed plus FOR UPDATE plus a lock order. Predictable waiting, no retries.</blockquote><blockquote>- Optimistic: Serializable plus a retry loop on 40001 and 40P01. No waiting, retries mandatory.</blockquote><blockquote>- Mixing the two pays both costs. Keep transactions short either way.</blockquote><blockquote>- A version column gives you compare-and-set without any lock at all.</blockquote><h3>References</h3><p><strong>PostgreSQL documentation</strong></p><ul><li><em>13.3 Explicit Locking</em><br> <a href="https://www.postgresql.org/docs/18/explicit-locking.html">https://www.postgresql.org/docs/18/explicit-locking.html</a></li><li><em>13.2 Transaction Isolation</em> <br> <a href="https://www.postgresql.org/docs/18/transaction-iso.html">https://www.postgresql.org/docs/18/transaction-iso.html</a></li><li><em>Lock Management</em> <br> <a href="https://www.postgresql.org/docs/18/runtime-config-locks.html">https://www.postgresql.org/docs/18/runtime-config-locks.html</a></li><li><em>Advisory Lock Functions (9.28.10)</em><br> <a href="https://www.postgresql.org/docs/18/functions-admin.html">https://www.postgresql.org/docs/18/functions-admin.html</a></li><li><em>pg_locks</em><br> <a href="https://www.postgresql.org/docs/18/view-pg-locks.html">https://www.postgresql.org/docs/18/view-pg-locks.html</a></li><li><em>SELECT — The Locking Clause</em> <br> <a href="https://www.postgresql.org/docs/18/sql-select.html">https://www.postgresql.org/docs/18/sql-select.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed90ddc7e16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[synchronized or ReentrantLock? Neither Prevents Deadlock]]></title>
            <link>https://medium.com/@mr-yakar/synchronized-or-reentrantlock-neither-prevents-deadlock-ae3a3b269fd9?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae3a3b269fd9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 14:44:49 GMT</pubDate>
            <atom:updated>2026-08-23T04:52:53.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A key photo." src="https://cdn-images-1.medium.com/max/1024/1*WrjtP6N1ilPsfrLpyYk8Eg.png" /></figure><p>TL;DR</p><ul><li>synchronized and ReentrantLock both give you mutual exclusion and a happens-before edge. Neither prevents deadlock.</li><li>ReentrantLock adds tryLock, timeouts, interruptible waiting, fairness, and multiple Conditions. The cost is a mandatory try/finally and an unlock() you can forget.</li><li>jstack detects deadlocks on both, but prints them differently: waiting to lock monitor for synchronized, waiting for ownable synchronizer for ReentrantLock.</li><li>Without -l, the Locked ownable synchronizers section is missing entirely. Always pass -l.</li><li><strong>A monitor plus a </strong><strong>ReadWriteLock read lock can deadlock without the JVM reporting anything.</strong> Both threads hang and the dump stays silent, because a read lock is shared and has no single owner to build a cycle from.</li><li>Four conditions produce a deadlock. Only two are breakable in Java: circular wait (lock ordering) and hold-and-wait (tryLock plus backoff).</li><li>Lock ordering finishes the demo below in 20 ms. tryLock with backoff needs 320–640 ms for a fifth of the work. Order the locks if you can.</li><li><strong>Virtual threads never appear in </strong><strong>jstack output</strong>, and a deadlock between them is reported by nothing.</li><li>JDK 21–23 pinned virtual threads inside synchronized. JEP 491 fixed that in JDK 24 and removed the jdk.tracePinnedThreads flag — which now fails silently. Advice written before that is stale.</li></ul><blockquote><strong><em>Environment for every output below:</em></strong></blockquote><blockquote><em>- Intel Core i7–4700HQ (4 cores / 8 threads, x86–64)</em></blockquote><blockquote><em>- Ubuntu 26.04</em></blockquote><blockquote><em>- Amazon Corretto 21.0.11</em></blockquote><blockquote><em>- Amazon Corretto 25.0.4.</em></blockquote><blockquote><strong>Every output below came from six single-file programs.</strong></blockquote><blockquote><em>No build tool, no dependencies — </em><em>javac *.java and run.</em></blockquote><blockquote><em>The dump sections need two terminals: the program in one, </em><em>jcmd -l and </em><em>jstack -l &lt;pid&gt; in the other.</em></blockquote><blockquote><em>Source: [</em><a href="https://github.com/mryakar/article-examples/tree/master/synchronized-vs-reentrantlock"><em>github.com/…</em></a><em>]</em></blockquote><h3>A Transfer That Never Completes</h3><p>Two accounts, two threads, money moving in both directions.</p><pre>static void transfer(Account from, Account to, double amount) {<br>    synchronized (from) {<br>        synchronized (to) {<br>            from.balance -= amount;<br>            to.balance += amount;<br>        }<br>    }<br>}</pre><p>t1 transfers A → B a hundred thousand times. t2 transfers B → A the same number of times. The method locks both accounts, so no update is lost. The arithmetic is correct.</p><p>Run it five times:</p><pre><br>$ for i in 1 2 3 4 5; do timeout 15 java Transfer.java; echo &quot;-- exit $?&quot;; done<br>-- exit 124<br>-- exit 124<br>-- exit 124<br>-- exit 124<br>-- exit 124<br></pre><p>124 is the exit code of timeout. The program never finished, five times out of five. No exception, no error, no output — the process just stops making progress and stays alive until you kill it.</p><p>Both threads are correct on their own. Together they stop.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Locking both accounts makes each transfer atomic and the balances correct.</blockquote><blockquote>- The program still hangs, reliably, with no error of any kind.</blockquote><blockquote>- Correct code on each thread does not add up to a correct program.</blockquote><h3>What synchronized Already Gives You</h3><p>Every Java object has a <strong>monitor</strong>. synchronized acquires it: on this for an instance method, on the Class object for a static method, on whatever you name in a block.</p><p>It is <strong>reentrant</strong>. A thread already holding the monitor can enter again; the JVM keeps a counter and releases at zero. Without this, one synchronized method calling another on the same object would deadlock against itself.</p><p>And it gives you more than exclusion. From the happens-before rules: <em>an unlock on a monitor happens-before every later lock on that same monitor</em>. So synchronized also publishes everything the thread did before releasing. Exclusion and visibility, from one keyword.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- synchronized locks an object&#39;s monitor: this, the Class object, or a named object.</blockquote><blockquote>- It is reentrant, so nested calls on the same object do not block themselves.</blockquote><blockquote>- Unlock happens-before the next lock, so it provides <strong>visibility</strong> as well as exclusion.</blockquote><h3>What It Doesn’t</h3><p>ReentrantLock gives the same guarantees and adds five things synchronized cannot express.</p><p><strong>tryLock()</strong> returns immediately with false instead of waiting. <strong>tryLock(timeout, unit)</strong> waits a bounded time. Together they let a thread give up — which is the whole of the deadlock strategy in a later section.</p><p><strong>lockInterruptibly()</strong> lets a waiting thread respond to interrupt(). A thread blocked on synchronized cannot be interrupted at all; your shutdown signal is simply ignored.</p><p><strong>Fairness.</strong> new ReentrantLock(true) hands the lock to the longest waiter. It removes starvation and costs throughput, because it defeats the barging that makes the unfair path fast. Default to unfair.</p><p><strong>Multiple </strong><strong>Conditions.</strong> wait/notify gives one queue per object, so notifyAll wakes producers and consumers alike. A lock can create separate Condition objects and wake only the group that can make progress.</p><p><strong>Non-block-structured locking.</strong> synchronized releases at the closing brace. A lock can be acquired in one method and released in another — the basis of hand-over-hand traversal.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- tryLock and tryLock(timeout) let a thread stop waiting.</blockquote><blockquote>- lockInterruptibly makes a waiting thread cancellable; synchronized does not.</blockquote><blockquote>- Fairness prevents starvation and costs throughput. Multiple Conditions wake only the right waiters.</blockquote><blockquote>- A lock can be released outside the block it was taken in.</blockquote><h3>The Cost of Asking for More</h3><p>synchronized releases the monitor at the closing brace, including when an exception unwinds the stack. There is no way to leak it.</p><p>ReentrantLock has no closing brace, so you write the release yourself:</p><pre>lock.lock();<br>try {<br>    // critical section<br>} finally {<br>    lock.unlock();<br>}</pre><p>Two mistakes are easy here. Putting lock() <strong>inside</strong> the try means an exception from lock() leads to unlocking a lock you never acquired — IllegalMonitorStateException, masking the original error. Forgetting finally means one exception on a rare path leaks the lock permanently, and every later thread blocks forever on something that already returned.</p><p>This is the argument for synchronized as the default. Not that locks are slow — that the safe version of a lock is four lines of ceremony you have to get right every time.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- synchronized always releases, including on exceptions.</blockquote><blockquote>- ReentrantLock requires lock() before try, and unlock() in finally.</blockquote><blockquote>- A leaked lock does not fail loudly. Later threads block forever.</blockquote><blockquote>- Prefer synchronized unless you need something from the previous section.</blockquote><h3>Reading the Dump</h3><p>The hung program is still running, so take a thread dump. Find the process with jcmd -l, then:</p><pre>jstack &lt;pid&gt;</pre><p>At the end of the output:</p><pre>Found one Java-level deadlock:<br>=============================<br>&quot;t1&quot;:<br>  waiting to lock monitor 0x00007ccf68000f80 (object 0x00000007242a2088, a Transfer$Account),<br>  which is held by &quot;t2&quot;<br>&quot;t2&quot;:<br>  waiting to lock monitor 0x00007ccf5c000f60 (object 0x00000007242a2070, a Transfer$Account),<br>  which is held by &quot;t1&quot;</pre><p>The JVM found the cycle and named both threads, both objects, and printed the stacks so you can find the lines.</p><figure><img alt="Animation: two threads and two accounts. Each thread holds one account and waits for the one the other thread is holding, forming a cycle that never resolves." src="https://cdn-images-1.medium.com/max/880/1*qjjhm81mnwX1rCmmI9MBEw.gif" /><figcaption><em>Each thread holds what the other is waiting for. Nothing in the JVM will break the tie.</em></figcaption></figure><p>Now the same deadlock built from ReentrantLock instead:</p><pre>&quot;t1&quot;:<br>  waiting for ownable synchronizer 0x00000007253a3308,<br>  (a java.util.concurrent.locks.ReentrantLock$NonfairSync),<br>  which is held by &quot;t2&quot;</pre><p>Same cycle, different words. A monitor is <em>locked</em>; a ReentrantLock is an <strong>ownable synchronizer</strong>. If you grep thread dumps for waiting to lock, you will miss every java.util.concurrent deadlock in your system.</p><p>One more difference, and it costs nothing to avoid:</p><pre>--- without -l: 0<br>--- with    -l: 14</pre><p>That is the count of Locked ownable synchronizers lines. Without -l, the dump lists which monitors each thread holds but says nothing about which locks it holds. The deadlock section still appears — but contention that has not yet become a deadlock is invisible. Make -l a habit.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- The JVM detects deadlocks and prints them at the end of the dump. It does not resolve them.</blockquote><blockquote>- synchronized shows as waiting to lock monitor; ReentrantLock as waiting for ownable synchronizer.</blockquote><blockquote>- Searching dumps for only one of those phrases hides half your deadlocks.</blockquote><blockquote>- Always use jstack -l, or jcmd &lt;pid&gt; Thread.print -l.</blockquote><h3>The Deadlocks the JVM Will Not Tell You About</h3><p>The previous section ends on a comfortable note: take a dump, read the section, fix the code. Here is where that stops working.</p><p>One thread takes a monitor and then a write lock. Another takes a <strong>read</strong> lock and then the same monitor:</p><pre>// t1<br>synchronized (MON) { RW.writeLock().lock(); }<br>// t2<br>RW.readLock().lock(); synchronized (MON) { }</pre><p>Both threads hang. The dump shows exactly why:</p><pre>&quot;t1&quot; ... java.lang.Thread.State: WAITING (parking)<br>    - parking to wait for &lt;0x...&gt; (a ReentrantReadWriteLock$NonfairSync)<br>&quot;t2&quot; ... java.lang.Thread.State: BLOCKED (on object monitor)<br>    - waiting to lock &lt;0x...&gt; (a java.lang.Object)</pre><p>And then:</p><pre>=== deadlock reported? ===<br>NO DEADLOCK SECTION<br>=== still stuck? threads alive: 2</pre><p>Ten seconds later both threads are still there. This is a real deadlock, and jstack -l says nothing about it.</p><figure><img alt="Animation: one thread blocked on a monitor and another parked on a write lock. The monitor side has a named owner, the read lock side does not, so the ownership graph has no cycle to find and the thread dump reports nothing." src="https://cdn-images-1.medium.com/max/880/1*tefy2gzOo8cMD7Qu5kP_OA.gif" /><figcaption><em>A monitor has one owner, so the JVM can follow the edge. A read lock is shared and has no single owner, so the cycle never closes.</em></figcaption></figure><p>Deadlock detection works by building a graph of <em>who owns what</em> and looking for a cycle. A monitor has exactly one owner. An exclusive ReentrantLock has exactly one owner. A <strong>read lock does not</strong> — it is shared by design, held by any number of threads at once, and the JVM cannot name the thread you are waiting behind. The edge is missing, so the cycle is never found.</p><p>The practical rule: if a hang involves a ReadWriteLock, Semaphore, CountDownLatch, or any other shared-permit construct, do not trust the absence of a deadlock section. Read the thread states yourself. WAITING (parking) plus BLOCKED (on object monitor) that persist across two dumps taken a minute apart is a deadlock, whatever the tooling says.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- A monitor combined with a read lock can deadlock with <strong>no deadlock section in the dump</strong>.</blockquote><blockquote>- Detection needs a single owner per resource. Shared locks have none, so the cycle cannot be built.</blockquote><blockquote>- The same gap applies to semaphores, latches, and other permit-based constructs.</blockquote><blockquote>- Compare two dumps a minute apart. Threads stuck in the same frame are stuck, reported or not.</blockquote><h3>Four Conditions, and Which One You Can Break</h3><p>A deadlock needs all four <a href="https://en.wikipedia.org/wiki/Deadlock_(computer_science)"><strong>Coffman</strong></a> conditions at once. Remove any one and it cannot form.</p><p><strong>Mutual exclusion</strong> — the resource cannot be shared. This is what a lock is for. Not breakable.</p><p><strong>No preemption</strong> — nothing takes the lock away from its holder. The JVM never does this, and there is no API for it. Not breakable.</p><p><strong>Hold and wait</strong> — a thread holding one lock waits for another. Breakable: acquire everything at once, or release what you hold when you cannot get the rest.</p><p><strong>Circular wait</strong> — the wait-for graph forms a cycle. Breakable: make every thread acquire locks in the same global order, and a cycle becomes impossible.</p><p>Two doors out of four, and the rest of this article is those two.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Four conditions must hold at once for a deadlock; breaking one is enough.</blockquote><blockquote>- Mutual exclusion and no-preemption are not negotiable in Java.</blockquote><blockquote><strong>- Circular wait</strong> is broken by consistent lock ordering.</blockquote><blockquote><strong>- Hold and wait</strong> is broken by tryLock with release and retry.</blockquote><h3>The Lock You Take Second</h3><p>The bug in the first program is not that it takes two locks. It is that t1 takes A then B while t2 takes B then A. Give both threads the same order and the cycle cannot form:</p><pre>static void transfer(Account from, Account to, double amount) {<br>    Account first  = from.id &lt; to.id ? from : to;<br>    Account second = from.id &lt; to.id ? to   : from;<br>    synchronized (first) {<br>        synchronized (second) {<br>            from.balance -= amount;<br>            to.balance += amount;<br>        }<br>    }<br>}</pre><p>Nothing else changed. Same locks, same threads, same work:</p><pre>completed in 20 ms<br>A=1000.0  B=1000.0<br>completed in 21 ms<br>A=1000.0  B=1000.0<br>completed in 21 ms<br>A=1000.0  B=1000.0</pre><figure><img alt="Animation: two threads acquiring locks in opposite orders, then the same two threads acquiring in the same order, where a cycle can no longer form." src="https://cdn-images-1.medium.com/max/880/1*xovf6N2N3GkdMiqa4HlsFQ.gif" /><figcaption><em>The order is decided by the accounts, not by the caller. Every thread walks the same direction.</em></figcaption></figure><p>The ordering key has to be <strong>stable and unique</strong>. A database id or account number is ideal. System.identityHashCode works when there is no natural key, with one caveat most articles skip: identity hash codes can collide, and two colliding objects give you no order at all. The fix is a third lock taken first, held only while the tie is being broken. At the end of the day, the best choice is providing uniqueness with a database id or account number. Provide a deterministic ordering.</p><p>The real difficulty is not the code — it is that ordering is a <strong>global</strong> property. A rule obeyed in nine methods and broken in the tenth is not a rule. Write the order down, and keep every acquisition in the codebase pointing the same way.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Deadlock came from opposite ordering, not from taking two locks.</blockquote><blockquote>- Sort by a stable unique key before acquiring. The demo finishes in ~20 ms.</blockquote><blockquote>- identityHashCode can collide; break the tie with a third lock. Provide a deterministic ordering.</blockquote><blockquote>- The rule only works if the entire codebase follows it.</blockquote><h3>When You Cannot Order Them</h3><p>Sometimes there is no key to sort by, or the locks are behind an API you do not control. Then break hold-and-wait instead: take the first lock, try for the second, and <strong>give up both</strong> if it does not come.</p><pre>if (from.lock.tryLock(50, TimeUnit.MILLISECONDS)) {<br>    try {<br>        if (to.lock.tryLock(50, TimeUnit.MILLISECONDS)) {<br>            try {<br>                from.balance -= amount;<br>                to.balance += amount;<br>                return true;<br>            } finally { to.lock.unlock(); }<br>        }<br>    } finally { from.lock.unlock(); }   // release what we hold<br>}<br>retries.incrementAndGet();<br>Thread.sleep(ThreadLocalRandom.current().nextInt(1, 5));  // backoff with jitter</pre><p>Three details are not optional. <strong>Release the first lock</strong> before retrying — keeping it means hold-and-wait survives and you have built a livelock instead. <strong>Jitter the backoff</strong>, because two threads that collided once will collide again if they retry on the same schedule. <strong>Cap the attempts</strong>, so a permanent conflict fails loudly instead of spinning forever.</p><p>It works, and it is not free:</p><pre>completed in 638 ms<br>retries=23<br>A=1000.0  B=1000.0<br>completed in 321 ms<br>retries=12<br>A=1000.0  B=1000.0</pre><p>Correct balances — and note the loop count. This version does 20,000 transfers per thread, the ordered version did 100,000. A fifth of the work takes 16 to 32 times longer, so per transfer the gap is close to two orders of magnitude. Every failed attempt throws away a lock acquisition, and the numbers move run to run because they depend on how the collisions land.</p><p>Use ordering when you can. Use this when you cannot.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- tryLock with a timeout breaks hold-and-wait: fail, release, retry.</blockquote><blockquote>- Releasing the lock you already hold is what makes it work.</blockquote><blockquote>- Backoff needs jitter, and attempts need a cap.</blockquote><blockquote>- Much slower than ordering, and the cost varies per run. Second choice, not first.</blockquote><h3>Virtual Threads Are Invisible Here</h3><p>Everything above assumed a thread dump shows you your threads. Run the same monitor deadlock on two virtual threads:</p><pre>Thread.ofVirtual().name(&quot;vt1&quot;).start(() -&gt; {<br>    synchronized (A) { nap(); synchronized (B) {} }<br>});<br>Thread.ofVirtual().name(&quot;vt2&quot;).start(() -&gt; {<br>    synchronized (B) { nap(); synchronized (A) {} }<br>});</pre><p>On Corretto 21 and Corretto 25:</p><pre>jstack sees vt threads : 0<br>jstack reports deadlock: 0<br>json dump sees vt      : 2</pre><p>jstack does not list virtual threads at all — not their stacks, not their names, and not the deadlock between them. The process looks healthy: a handful of carrier threads, nothing blocked, no deadlock section. Netflix published the production version of this in <em>Java 21 Virtual Threads — Dude, Where&#39;s My Lock?</em>: instances stopped serving traffic while the JVM stayed alive and standard thread dumps showed an idle VM.</p><p>The threads are visible through a different tool:</p><pre>jcmd &lt;pid&gt; Thread.dump_to_file -format=json /tmp/dump.json</pre><p>That dump contains both virtual threads and their stacks. What it does <strong>not</strong> contain, on either version, is a deadlock section — the analysis in the previous sections has no equivalent here. You get the raw stacks and you do the cycle-finding yourself.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- jstack shows no virtual threads and no deadlock between them, on 21 and 25 alike.</blockquote><blockquote>- A stalled virtual-thread application looks like an idle JVM in a standard dump.</blockquote><blockquote>- Use jcmd &lt;pid&gt; Thread.dump_to_file -format=json to see them.</blockquote><blockquote>- Even there, nothing reports the deadlock. Read the stacks yourself.</blockquote><h3>JEP 491 Reset the Advice — Check Your JDK</h3><p>Between JDK 21 and 23 there was a second reason to prefer ReentrantLock, and it had nothing to do with the features in this article.</p><p>A virtual thread blocking inside synchronized <strong>pinned</strong> its carrier platform thread. Blocking in a ReentrantLock did not. With enough pinned carriers the scheduler ran out and the application stalled. That is why MySQL Connector/J 9.0.0 and other drivers replaced synchronized with ReentrantLock — not for interruptibility, but to stop pinning.</p><p>Pinning was not an oversight. The JVM tracked monitor ownership by the <strong>carrier</strong> thread’s identity. If a virtual thread could unmount while holding a monitor, the next virtual thread mounted on that carrier would appear to own a lock it never took. Pinning was what kept synchronized correct.</p><p><strong>JEP 491, delivered in JDK 24</strong>, made monitors virtual-thread-aware and removed that restriction. Two consequences:</p><ul><li>The synchronized-to-ReentrantLock migrations are no longer required. Still reasonable for your own code if you want interruptibility or timeouts — no longer a prerequisite for virtual threads.</li><li>The diagnostic flag -Djdk.tracePinnedThreads was <strong>removed</strong>, described in the change request as having proven problematic and no longer useful. It does not warn you about this:</li></ul><pre>$ java -Djdk.tracePinnedThreads=full -version<br>openjdk version &quot;21.0.11&quot; 2026-04-21 LTS$ <br>$J25/java -Djdk.tracePinnedThreads=full -version<br>openjdk version &quot;25.0.4&quot; 2026-07-21 LTS</pre><p>No error, no warning, no difference. On 25 the flag is simply gone, and a build script carrying it will look like it is still doing something. The JFR event jdk.VirtualThreadPinned remains and was extended to report the reason for pinning and the carrier&#39;s identity — use that instead.</p><p>Pinning still happens in narrow cases: native frames, the Foreign Function &amp; Memory API calling back into blocking Java code, and class loading.</p><p>The JEP states the outcome directly: choose between synchronized and java.util.concurrent.locks based only on which one solves your problem.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- JDK 21–23: synchronized pinned virtual threads to carriers; ReentrantLock did not.</blockquote><blockquote>- Pinning existed because monitor ownership was tracked per carrier, not per virtual thread.</blockquote><blockquote>- JEP 491 fixed this in <strong>JDK 24</strong>. Migrations done for pinning are no longer necessary.</blockquote><blockquote>- Flag -Djdk.tracePinnedThreads was removed and fails <strong>silently</strong>. Use the jdk.VirtualThreadPinned JFR event.</blockquote><h3>Which One, and When</h3><p>Default to synchronized. It cannot leak, it needs no ceremony, and since JDK 24 it carries no virtual-thread penalty.</p><p>Reach for ReentrantLock when you need something it cannot express: a bounded wait, a tryLock, an interruptible acquisition, fairness, or more than one condition queue. Those are real needs, and when you have one the extra four lines are the price.</p><p>Neither prevents deadlock. That is what ordering is for.</p><p>And often the answer is neither. A counter wants AtomicInteger. A shared map wants ConcurrentHashMap. State that never changes needs no lock at all. The fastest lock is the one you did not take — which is where the next article goes: compare-and-swap, and the atomic classes built on it.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- synchronized by default; ReentrantLock when you need a specific feature from it.</blockquote><blockquote>- Since JDK 24 there is no virtual-thread reason to choose between them.</blockquote><blockquote>- Neither prevents deadlock — ordering does.</blockquote><blockquote>- Prefer atomics, concurrent collections, and immutability over locking at all.</blockquote><blockquote><em>The six programs are on GitHub: </em><a href="https://github.com/mryakar/article-examples/tree/master/synchronized-vs-reentrantlock">https://github.com/mryakar/article-examples</a></blockquote><h3>References</h3><p><strong>Specification and JEPs</strong></p><ul><li><em>The Java® Language Specification, §17.4.5 — Happens-before Order.</em><br> <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html">https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html</a></li><li><em>JEP 491: Synchronize Virtual Threads without Pinning.</em><br> <a href="https://openjdk.org/jeps/491">https://openjdk.org/jeps/491</a></li><li><em>JDK-8338813 — CSR for JEP 491.</em><br> <a href="https://bugs.java.com/bugdatabase/view_bug?bug_id=8338813">https://bugs.java.com/bugdatabase/view_bug?bug_id=8338813</a></li><li><em>JEP 444: Virtual Threads.</em><br> <a href="https://openjdk.org/jeps/444">https://openjdk.org/jeps/444</a></li></ul><p><strong>API documentation</strong></p><ul><li>ReentrantLock, ReentrantReadWriteLock, Condition — java.util.concurrent.locks.<br> <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/locks/package-summary.html">https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/locks/package-summary.html</a></li><li><em>The jstack Utility</em> — the -l option and the deadlock detection section.<br> <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr016.html">https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr016.html</a></li></ul><p><strong>Field reports</strong></p><ul><li>Netflix Technology Blog, <em>Java 21 Virtual Threads — Dude, Where’s My Lock?</em></li><li>MySQL Connector/J 9.0.0 release notes — synchronized replaced with ReentrantLock for virtual-thread friendliness.</li></ul><p><strong>Further reading</strong></p><ul><li>Brian Goetz et al., <em>Java Concurrency in Practice</em></li><li>Doug Lea, <em>The JSR-133 Cookbook for Compiler Writers</em><br> <a href="https://gee.cs.oswego.edu/dl/jmm/cookbook.html">https://gee.cs.oswego.edu/dl/jmm/cookbook.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae3a3b269fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVCC — How PostgreSQL Actually Implements Isolation]]></title>
            <link>https://medium.com/@mr-yakar/mvcc-how-postgresql-actually-implements-isolation-6faddc9291ae?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6faddc9291ae</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 11:58:35 GMT</pubDate>
            <atom:updated>2026-08-21T14:52:22.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-usy9s4CIu3sBUHUV6sMOg.png" /></figure><h3>TL;DR</h3><ul><li>In PostgreSQL, UPDATE never changes a row in place. It writes a <strong>new row version</strong> and marks the old one dead. DELETE only marks. The number of rows in your table is not the number of tuples on disk.</li><li>Every tuple carries <strong>xmin</strong> (the transaction that created it) and <strong>xmax</strong> (the transaction that killed or locked it). These two fields are the core of MVCC.</li><li>A <strong>snapshot</strong> is three values: xmin, xmax, and the list of transaction ids that were still running when it was taken. Visibility is decided per tuple against that snapshot.</li><li>Isolation levels are not separate features. They are <strong>one engine with a different snapshot policy</strong>.</li><li><strong>Read Committed</strong> takes a new snapshot for every statement. An UPDATE that waits for a conflict then re-checks its WHERE clause against the new version.</li><li><strong>Repeatable Read</strong> freezes one snapshot for the whole transaction. In PostgreSQL this prevents dirty reads, non-repeatable reads <strong>and phantom reads</strong> — stronger than the SQL standard requires. What remains is serialization anomalies.</li><li><strong>Serializable</strong> adds SSI: predicate locks track read/write dependencies and abort transactions that would produce a non-serializable outcome. This is what catches <strong>write skew</strong>.</li><li>Under Repeatable Read and Serializable, could not serialize access is not a failure. It is part of the contract, and your application <strong>must retry</strong>, which makes idempotency mandatory.</li><li>Old versions pile up. <strong>VACUUM</strong> reclaims them — unless an open transaction holds the xmin horizon back, in which case nothing can be cleaned.</li><li>MVCC is not unique to PostgreSQL, but implementations differ. PostgreSQL keeps old versions in the table itself; Oracle and InnoDB keep them in undo segments. Lock-based systems (2PL) block readers against writers; MVCC does not.</li></ul><blockquote><strong><em>Environment for every output in this article:</em></strong><em> PostgreSQL 18.6 (Debian build) on x86_64, running in Docker with </em><em>autovacuum turned off so that nothing is cleaned up in the background while we are looking at it. Transaction ids on your machine will be different; the structure will not be.</em></blockquote><h3>From Anomalies to Mechanism</h3><p>In an earlier article I described what can go wrong when transactions run at the same time: <strong>dirty reads</strong>, <strong>non-repeatable reads</strong>, and <strong>phantom reads</strong>, and which isolation level prevents each one. That article stayed at the level of behavior — what you see, and which setting changes it.</p><p>This one goes underneath. The question here is not <em>which anomalies does Repeatable Read prevent</em>, but <em>what is the database actually doing that makes them impossible</em>.</p><p>The answer is a single mechanism: <strong>Multiversion Concurrency Control</strong>. The three isolation levels PostgreSQL offers are not three different algorithms. They are the same engine with a different rule about when a snapshot is taken.</p><p>One correction before we start. In that earlier article I wrote that you must move to Serializable to prevent phantom reads. That is true of the SQL standard. It is <strong>not</strong> true of PostgreSQL, and we will see exactly why once the mechanism is on the table.</p><p>Nothing here touches Spring, @Transactional, or the application layer. Two psql sessions and a table.</p><blockquote><strong>In short</strong></blockquote><blockquote>- The earlier article described <em>which</em> anomalies each isolation level prevents. This one explains <em>how</em>.</blockquote><blockquote>- PostgreSQL’s three isolation levels are not three algorithms. They are one engine — <strong>MVCC</strong> — with different snapshot rules.</blockquote><blockquote>- Correction to that earlier article: in PostgreSQL you do <strong>not</strong> need Serializable to prevent phantom reads.</blockquote><h3>UPDATE Does Not Update</h3><p>Start with a table:</p><pre>CREATE TABLE accounts (id int primary key, owner text, balance numeric); <br><br>INSERT INTO accounts VALUES <br>(1, &#39;amo&#39;, 100), <br>(2, &#39;simo&#39;, 250);</pre><p>Now change one row three times:</p><pre>UPDATE accounts SET balance = 90 WHERE id = 1; <br>UPDATE accounts SET balance = 80 WHERE id = 1; <br>UPDATE accounts SET balance = 70 WHERE id = 1;</pre><p>Two rows in, three updates applied. Ask the table how many rows it has:</p><pre>visible_rows<br>--------------<br>            2<br>(1 row)</pre><p>Now ask the <em>page</em> what it is holding. The pageinspect extension reads the raw heap:</p><pre>CREATE EXTENSION IF NOT EXISTS pageinspect; <br>SELECT lp, t_xmin, t_xmax, t_ctid <br>FROM heap_page_items(get_raw_page(&#39;accounts&#39;, 0));</pre><pre> lp | t_xmin | t_xmax | t_ctid<br>----+--------+--------+--------<br>  1 |    756 |    757 | (0,3)<br>  2 |    756 |      0 | (0,2)<br>  3 |    757 |    758 | (0,4)<br>  4 |    758 |    759 | (0,5)<br>  5 |    759 |      0 | (0,5)<br>(5 rows)</pre><figure><img alt="Animation: a table row count stays at two while the tuple count on the page climbs from two to five, each UPDATE marking the previous version dead and adding a new one." src="https://cdn-images-1.medium.com/max/880/1*_jb8qsWBZzkkDORHx5QRGw.gif" /><figcaption><em>The row count never changes. The page keeps growing.</em></figcaption></figure><p>Five tuples on disk. Two rows in the table.</p><p>An UPDATE in PostgreSQL does not change a row. It writes a <strong>new version</strong> of that row and marks the old version as dead. DELETE does not remove anything either. It only marks. Every version that ever existed is still on the page until something comes along to clean it up.</p><p>This is the foundation of everything that follows. Two transactions can read the same row and see different values, and both are right. There is no single “current value” on disk. There is a set of versions, and each transaction is entitled to a different one.</p><blockquote><strong>In short</strong></blockquote><blockquote>- UPDATE writes a <strong>new row version</strong> and marks the old one dead. DELETE only marks.</blockquote><blockquote>- Three updates to one row leave <strong>four versions</strong> of it on the page. Two logical rows, five tuples on disk.</blockquote><blockquote>- There is no single “current value” stored anywhere. There is a set of versions.</blockquote><blockquote>- pageinspect lets you see the raw tuples: heap_page_items(get_raw_page(&#39;accounts&#39;, 0)).</blockquote><h3>xmin and xmax: How a Row Version Is Marked</h3><p>Every tuple carries two system columns you can query directly:</p><ul><li><strong>xmin</strong> — the id of the transaction that created this version.</li><li><strong>xmax</strong> — the id of the transaction that marked it dead. 0 means still live.</li></ul><p>Right after the insert:</p><pre>SELECT xmin, xmax, ctid, * FROM accounts ORDER BY id;</pre><pre> xmin | xmax | ctid  | id | owner | balance<br>------+------+-------+----+-------+---------<br>  756 |    0 | (0,1) |  1 | amo   |     100<br>  756 |    0 | (0,2) |  2 | simo  |     250<br>(2 rows)</pre><p>Both rows were created by transaction 756, and nothing has killed them. After the three updates, row 1 looks like this:</p><pre> xmin | xmax | ctid  | id | owner | balance<br>------+------+-------+----+-------+---------<br>  759 |    0 | (0,5) |  1 | amo   |      70<br>  756 |    0 | (0,2) |  2 | simo  |     250<br>(2 rows)</pre><p>Row 1 is now the version created by transaction 759. Compare this with the raw page output above and you can follow the chain: version 1 was killed by 757, which created version 3, which was killed by 758, which created version 4, and so on. ctid is the physical address of a version — page number and item number.</p><p><strong>One thing that will confuse you at the terminal.</strong> A non-zero xmax does not always mean the row was deleted or updated. It is also set when a row is only <strong>locked</strong>:</p><pre>-- session B<br>BEGIN;<br>SELECT id FROM accounts WHERE id = 1 FOR UPDATE;</pre><pre> xmin | xmax | ctid  | id | balance<br>------+------+-------+----+---------<br>  759 |  760 | (0,5) |  1 |      70<br>  756 |    0 | (0,2) |  2 |     250<br>(2 rows)</pre><p>Transaction 760 has not written anything. It holds a lock. The row is alive and stays alive.</p><p>The tuple header knows the difference, and it will tell you. The HEAP_XMAX_LOCK_ONLY flag is bit 128 of t_infomask:</p><pre>SELECT lp, t_xmax, (t_infomask &amp; 128) != 0 AS xmax_is_lock_only<br>FROM heap_page_items(get_raw_page(&#39;accounts&#39;, 0))<br>WHERE lp = 5;</pre><pre> lp | t_xmax | xmax_is_lock_only<br>----+--------+-------------------<br>  5 |    760 | t<br>(1 row)</pre><p>So do not read xmax as &quot;this version is dead&quot;. The flag bits carry that distinction, not xmax on its own.</p><blockquote><strong>In short</strong></blockquote><blockquote><strong>- xmin</strong> = the transaction that created this version. <strong>xmax</strong> = the transaction that killed or locked it; 0 means live.</blockquote><blockquote>- Both are system columns you can query. ctid is the version&#39;s physical address (page, item).</blockquote><blockquote><strong>- A non-zero </strong><strong>xmax does not mean deleted.</strong> SELECT ... FOR UPDATE also sets it. The HEAP_XMAX_LOCK_ONLY flag in t_infomask carries the difference, not xmax alone.</blockquote><h3>Snapshots and the Visibility Rule</h3><p>A transaction does not see the newest version of a row. It sees the version its <strong>snapshot</strong> allows it to see.</p><p>A snapshot is three values, and PostgreSQL will show them to you:</p><pre>SELECT pg_current_snapshot();</pre><pre> pg_current_snapshot<br>---------------------<br> 761:763:761<br>(1 row)</pre><p>Read as xmin:xmax:xip_list:</p><ul><li><strong>xmin = 761</strong> — every transaction below this id has finished. No need to check them one by one.</li><li><strong>xmax = 763</strong> — every transaction from this id upward had not started when the snapshot was taken. Automatically invisible.</li><li><strong>xip_list = 761</strong> — transactions between xmin and xmax that were <strong>still running</strong>. Their work stays invisible even if they commit one microsecond later.</li></ul><p>Only the middle range needs a list. That is why xip_list is often empty. If the running transactions all have ids at or above xmax, the second rule already excludes them.</p><figure><img alt="Animation: the snapshot 761:763:761 drawn as a number line split into three zones — finished, in progress, not started — followed by two tuples tested against it, one visible and one invisible." src="https://cdn-images-1.medium.com/max/880/1*edMCAvbwwS1X0MYzIskJ0A.gif" /><figcaption>Everything below xmin is settled. Everything at or above xmax had not begun. Only the middle needs a list.</figcaption></figure><p>Now the rule that decides every read. For a tuple to be visible:</p><ol><li>Its <strong>xmin must have committed</strong>, and the snapshot must not exclude it — not in xip_list, not at or above xmax.</li><li>Its <strong>xmax must not disqualify it</strong> — either empty, or belonging to a transaction that has not committed, or one the snapshot excludes.</li></ol><p>Both conditions, per tuple, on every read. That is the whole of MVCC visibility.</p><p>One detail is missing, and it matters. Nothing in the tuple says whether transaction 757 committed. The tuple stores an id. The commit status lives in the <strong>commit log</strong> (pg_xact). Checking it on every read would be expensive, so PostgreSQL writes the answer back into the tuple as <strong>hint bits</strong> the first time someone asks. This is why the first SELECT after a write can be slower than the second one on the same data.</p><p>The mechanism is now complete: versions marked with xmin and xmax, and a snapshot that decides which ones you are allowed to see.</p><p>What we have not said is <strong>when</strong> the snapshot is taken. That single question is the difference between the isolation levels.</p><blockquote><strong>In short</strong></blockquote><blockquote>- A snapshot is three values: xmin:xmax:xip_list. Everything below xmin finished; everything at or above xmax had not started; xip_list holds the ones in between that were still running.</blockquote><blockquote>- A tuple is visible when its <strong>xmin committed and the snapshot does not exclude it</strong>, <strong>and</strong> its <strong>xmax does not disqualify it</strong>.</blockquote><blockquote>- xip_list is often empty. That is normal — running transactions at or above xmax are already excluded by the second rule.</blockquote><blockquote>- Commit status is not in the tuple. It lives in <strong>pg_xact</strong>, cached back as <strong>hint bits</strong>, which is why the first read after a write can be slower.</blockquote><h3>Not Just Postgres: The Two Families of Concurrency Control</h3><p>Before we look at the three isolation levels, one step back. MVCC is not a PostgreSQL invention, and knowing where it sits helps you read the levels correctly.</p><p>Databases solve concurrent access in one of two broad ways.</p><p><strong>The lock-based family.</strong> Under <strong>two-phase locking (2PL)</strong>, a transaction takes a shared lock to read and an exclusive lock to write, and holds them until it ends. The rule is simple and the cost is high: <strong>a reader blocks a writer, and a writer blocks a reader.</strong> Correctness comes from making conflicting transactions wait for each other.</p><p><strong>The multiversion family.</strong> Under MVCC, a write does not destroy what a reader is using, because the old version is still there. So <strong>readers do not block writers, and writers do not block readers.</strong> In plain MVCC, two transactions conflict only when both want to write the same row.</p><p>That is the whole reason MVCC won for OLTP workloads. A long report can scan a table while updates continue around it, and neither side waits.</p><p>But <strong>MVCC is a strategy, not a specification</strong>. Systems that all claim MVCC differ in the part that matters most — where the old versions are kept.</p><ul><li><strong>PostgreSQL</strong> keeps old versions <strong>in the table itself</strong>. That is what you saw on the page: five tuples for two rows. Cheap to write, and the reason PostgreSQL needs <strong>VACUUM</strong>.</li><li><strong>Oracle</strong> and <strong>MySQL/InnoDB</strong> keep old versions in <strong>undo segments</strong>, separate from the table, and rebuild earlier versions on demand. No VACUUM, but a long read can outlive the undo it needs — Oracle’s ORA-01555: snapshot too old is exactly that failure.</li><li><strong>SQL Server</strong> uses locking by default and switches to versioning only when you turn on snapshot isolation.</li><li><strong>CockroachDB</strong> and <strong>YugabyteDB</strong> apply MVCC across a distributed cluster, where version timestamps also have to survive clock differences between machines.</li></ul><p>At the far end there is a third answer: <strong>do not run transactions at the same time at all.</strong> VoltDB runs them one after another on single-threaded partitions. Correct by design, and only practical when transactions are short.</p><p>Why this matters for the rest of the article: everything from here on is <strong>PostgreSQL’s</strong> implementation. The isolation level names are standard. The behavior behind them is not.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Two families: <strong>lock-based (2PL)</strong>, where readers and writers block each other, and <strong>multiversion (MVCC)</strong>, where they do not.</blockquote><blockquote>- MVCC is a strategy, not a single design. Where old versions live is the main difference between implementations.</blockquote><blockquote>- PostgreSQL stores old versions <strong>in the table</strong>, which is why it needs VACUUM. Oracle and InnoDB use <strong>undo segments</strong> instead.</blockquote><blockquote>- The isolation level names in the SQL standard are shared. The behavior behind them is per-database.</blockquote><h3>Read Committed: A New Snapshot for Every Statement</h3><p>This is PostgreSQL’s default level, and its rule is one sentence: <strong>every statement takes a fresh snapshot.</strong></p><p>Which means two identical SELECTs in the same transaction can return different answers.</p><pre>-- session A<br>BEGIN ISOLATION LEVEL READ COMMITTED;<br>SELECT balance FROM accounts WHERE id = 1;</pre><pre>balance<br>---------<br>      70<br>(1 row)</pre><pre>-- session B<br>UPDATE accounts SET balance = 999 WHERE id = 1;<br>COMMIT;</pre><pre>-- session A, same transaction<br>SELECT balance FROM accounts WHERE id = 1;</pre><pre>balance<br>---------<br>     999<br>(1 row)</pre><p>Nothing is broken. A’s second statement asked for a new snapshot, and by then B’s transaction had committed and was therefore visible. This is the <strong>non-repeatable read</strong> from the earlier article, now with a mechanism behind it: not a race, not a bug — a new snapshot.</p><p><strong>The part almost every article skips.</strong></p><p>Statement-level snapshots explain reads. Writes need one more rule, because a writer cannot simply ignore a concurrent change to the row it is about to modify.</p><p>When an UPDATE reaches a row that another uncommitted transaction has already modified, it <strong>waits</strong>. If that transaction rolls back, the update goes ahead normally. If it commits, PostgreSQL does something you have to see to believe: it <strong>re-checks the </strong><strong>WHERE clause against the new version</strong>.</p><pre>-- balance is 1000<br>-- session A<br>BEGIN;<br>UPDATE accounts SET balance = 5 WHERE id = 1;   -- not committed yet</pre><pre>-- session B<br>BEGIN;<br>UPDATE accounts SET balance = balance - 100 WHERE balance &gt; 500;<br>-- blocks, waiting for A</pre><p>Session A commits. B wakes up and checks its condition again against the row as it now stands. balance is 5, and 5 &gt; 500 is false:</p><pre>UPDATE 0</pre><p>The row matched when B started and does not match anymore, so B skips it. <strong>No error, no warning, zero rows updated.</strong> If your code assumed the update applied, it is now wrong and silent.</p><p>This is the strongest argument for WHERE clauses that do not depend on values you are also changing — and, when correctness matters more than throughput, for a stricter isolation level.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Read Committed takes a <strong>new snapshot for every statement</strong>, not for every transaction.</blockquote><blockquote>- Two identical SELECTs in one transaction can return different values. That is the level working as designed.</blockquote><blockquote>- An UPDATE blocked by a concurrent write <strong>waits, then re-checks its </strong><strong>WHERE clause</strong> against the new version.</blockquote><blockquote>- If the row no longer matches, it is skipped silently — UPDATE 0, no error.</blockquote><h3>Repeatable Read: One Snapshot to Rule the Transaction</h3><p>Change one word and the mechanism changes completely. Under Repeatable Read, the snapshot is taken <strong>once</strong>, at the first statement of the transaction, and never refreshed.</p><pre>-- session A<br>BEGIN ISOLATION LEVEL REPEATABLE READ;<br>SELECT count(*) FROM accounts;           -- 2<br>SELECT balance FROM accounts WHERE id = 1;  -- 100</pre><pre>-- session B<br>INSERT INTO accounts VALUES (3, &#39;new&#39;, 500);<br>UPDATE accounts SET balance = 777 WHERE id = 1;<br>-- both committed</pre><pre>-- session A, same transaction<br>SELECT count(*) FROM accounts;<br>SELECT balance FROM accounts WHERE id = 1;</pre><pre> count<br>-------<br>     2<br>(1 row)<br><br> balance<br>---------<br>     100<br>(1 row)</pre><p>B’s work is committed and permanent. A cannot see it and will not see it until A ends. The snapshot is frozen.</p><p><strong>Here is the correction I owe the earlier article.</strong></p><p>Look at that count(*) again. B inserted a row that matches A&#39;s query, and A&#39;s second count still returns 2. That is a <strong>phantom read</strong>, and it did not happen.</p><p>In the SQL standard, Repeatable Read is allowed to permit phantom reads, and preventing them is the job of Serializable. That is what I wrote before, and it is what most articles repeat. <strong>In PostgreSQL it is wrong.</strong> Visibility here is decided by a frozen snapshot, not by row locks. A row created after the snapshot is invisible no matter how many times you look — as a row, and inside an aggregate.</p><p>The official documentation is explicit: PostgreSQL’s Repeatable Read prevents every phenomenon in the standard’s table except serialization anomalies. The standard sets a <strong>minimum</strong>. Giving more is allowed.</p><p><strong>What freezing costs you.</strong></p><p>A frozen snapshot is fine while you are reading. Writing is where it gets interesting, because a transaction cannot modify a row version it is not allowed to see.</p><pre>-- session A                      -- session B<br>BEGIN ISOLATION LEVEL REPEATABLE READ;<br>UPDATE accounts<br>  SET balance = 200 WHERE id = 1;<br>                                  BEGIN ISOLATION LEVEL REPEATABLE READ;<br>                                  UPDATE accounts<br>                                    SET balance = 300 WHERE id = 1;<br>                                  -- blocks<br>COMMIT;</pre><pre>ERROR:  could not serialize access due to concurrent update</pre><p>Compare this with Read Committed, where B waited and then quietly applied its update to the new version. Repeatable Read refuses. B’s snapshot says balance is 100. The row on disk says something else. There is no honest way to go on, so the transaction is aborted.</p><p><strong>This is not a bug and not a deadlock.</strong> It is the level telling you it could not keep its promise, and handing the decision back to your application. Which raises a question we will have to answer properly: what is your code supposed to do with that error?</p><blockquote><strong>In short</strong></blockquote><blockquote>- Repeatable Read takes <strong>one snapshot</strong> at the first statement and keeps it for the whole transaction.</blockquote><blockquote>- Committed changes from other transactions stay invisible until yours ends.</blockquote><blockquote><strong>- PostgreSQL’s Repeatable Read also prevents phantom reads</strong> — stronger than the SQL standard requires. Only serialization anomalies remain.</blockquote><blockquote>- A conflicting write does not wait and retry. It fails with could not serialize access due to concurrent update.</blockquote><h3>Serializable: When Snapshots Aren’t Enough</h3><p>A frozen snapshot prevents every anomaly built on <em>reading the wrong version</em>. There is a class of bug it cannot touch, because nothing is read wrongly at all.</p><p>Two doctors are on call. The rule: at least one must stay.</p><pre>CREATE TABLE doctors (name text primary key, on_call boolean);<br>INSERT INTO doctors VALUES (&#39;alice&#39;, true), (&#39;bob&#39;, true);</pre><p>Both want to go home, at the same time, under <strong>Repeatable Read</strong>:</p><pre>-- session A                        -- session B<br>BEGIN ISOLATION LEVEL REPEATABLE READ;<br>SELECT count(*) FROM doctors<br>  WHERE on_call;              -- 2<br>                                    BEGIN ISOLATION LEVEL REPEATABLE READ;<br>                                    SELECT count(*) FROM doctors<br>                                      WHERE on_call;              -- 2<br>UPDATE doctors SET on_call = false<br>  WHERE name = &#39;alice&#39;;<br>                                    UPDATE doctors SET on_call = false<br>                                      WHERE name = &#39;bob&#39;;<br>COMMIT;<br>                                    COMMIT;</pre><p>Both commit. No error. Now look at the table:</p><pre>name  | on_call<br>-------+---------<br> alice | f<br> bob   | f<br>(2 rows)</pre><p>Nobody is on call.</p><figure><img alt="Animation: two transaction timelines, both reading a count of two on-call doctors, each updating a different row, both committing, leaving the table with nobody on call." src="https://cdn-images-1.medium.com/max/880/1*EITYEAnERMBp9hwwdAR7jA.gif" /><figcaption><em>Both read the same condition. Both wrote a different row. MVCC has nothing to detect.</em></figcaption></figure><p><strong>Every step was legal.</strong> Each transaction read a correct snapshot, checked the rule, saw two doctors, and removed one. They wrote to <strong>different rows</strong>, so there was no write conflict for MVCC to detect. Each transaction is correct on its own, and the pair is not.</p><p>This is <strong>write skew</strong>, and it is the anomaly that snapshot isolation cannot see. The reason is structural. MVCC detects conflicts between <strong>writes</strong>. Here the conflict is between what one transaction <strong>read</strong> and what the other <strong>wrote</strong>.</p><p>SELECT ... FOR UPDATE would fix this particular case by locking the rows that were read. But that requires you to spot the problem first, in every place it can happen.</p><p><strong>What Serializable adds.</strong></p><p>PostgreSQL’s Serializable uses <strong>SSI — Serializable Snapshot Isolation</strong>. It keeps the snapshot machinery and adds tracking on top. When a transaction reads, PostgreSQL records what it read, including conditions and not only rows. That record is a <strong>predicate lock</strong>, held as an SIREAD lock, and it blocks nothing.</p><p>With that information, PostgreSQL watches for <strong>read/write dependencies</strong>: transaction B wrote something A had read. One such dependency is harmless. A specific pattern of them — one transaction sitting between two others in a way no serial order could produce — is not. When PostgreSQL sees that pattern, it aborts one of the transactions.</p><p>Same scenario, one word changed:</p><pre>BEGIN ISOLATION LEVEL SERIALIZABLE;</pre><pre>ERROR:  could not serialize access due to read/write dependencies among transactions<br>DETAIL:  Reason code: Canceled on identification as a pivot, during commit attempt.<br>HINT:  The transaction might succeed if retried.</pre><p>Read that error carefully. It is not about the row B wrote. It is about the <strong>dependency between what B read and what A wrote</strong> — a conflict with no locking, no waiting, and no blocking anywhere in the sequence. The database let both transactions run at full speed and only refused at the end, when it could prove the outcome was not serializable.</p><p>Note the word <strong>pivot</strong>. B is the transaction in the middle of the dangerous pattern, and PostgreSQL cancels the pivot rather than the first or last participant.</p><p>And the rule survives:</p><pre>name  | on_call<br>-------+---------<br> alice | f<br> bob   | t<br>(2 rows)</pre><p>Alice went home. Bob was rolled back and is still on call. Same two transactions, same order, one different keyword.</p><p>Serializable is not free. Tracking reads costs memory, and under contention it produces more aborts. But it gives you a guarantee no other level does: <strong>if your transaction is correct when it runs alone, it is correct when it runs alongside others.</strong> You stop reasoning about interleavings.</p><p>There is a condition attached, and it is not optional. That HINT says the transaction might succeed if retried — which means somebody has to retry it.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Repeatable Read prevents anomalies caused by reading a stale version. <strong>Write skew is not one of them.</strong></blockquote><blockquote>- Two transactions can read the same condition, write <strong>different rows</strong>, both commit, and break an invariant together.</blockquote><blockquote>- MVCC detects <strong>write/write</strong> conflicts. Write skew is a <strong>read/write</strong> conflict, which is invisible to it.</blockquote><blockquote>- Serializable adds <strong>SSI</strong>: predicate locks record what was read, and dangerous dependency patterns cause an abort at commit time.</blockquote><blockquote>- The abort is the mechanism working, not failing — and it assumes your application retries.</blockquote><h3>You Must Retry. There Is No Way Around It.</h3><p>Both stricter isolation levels can end your transaction with an error you did not cause:</p><pre>ERROR:  could not serialize access due to concurrent update<br>ERROR:  could not serialize access due to read/write dependencies among transactions<br>HINT:  The transaction might succeed if retried.</pre><p>Treating these as failures is the most common mistake made with Repeatable Read and Serializable. <strong>They are not failures. They are part of the contract.</strong></p><p>The deal PostgreSQL offers is this: run at full speed with no blocking, and in exchange, accept that some transactions will be told to start over. You cannot take the first half without the second. A system that uses Serializable and does not retry has taken the cost and refused the benefit.</p><p><strong>Which errors to retry.</strong></p><p>Retry only on <strong>SQLSTATE 40001</strong> (serialization_failure) and <strong>40P01</strong> (deadlock_detected). Both mean the same thing in practice: nothing was written, the transaction rolled back cleanly, and running it again may work.</p><p>Do not retry on constraint violations, syntax errors, or connection failures. Those will fail again.</p><pre>int attempt = 0;<br>while (true) {<br>    try {<br>        return doTransaction();<br>    } catch (SQLException e) {<br>        String state = e.getSQLState();<br>        if (!(&quot;40001&quot;.equals(state) <br>        || &quot;40P01&quot;.equals(state)) <br>        || ++attempt &gt;= MAX) {<br>            throw e;<br>        }<br>        Thread.sleep(backoffWithJitter(attempt));<br>    }<br>}</pre><p>Three details in that loop matter.</p><p><strong>The retry must be outside the transaction.</strong> A rolled-back transaction cannot be resumed. Everything the transaction did — including anything your application changed in memory — has to be redone from the start.</p><p><strong>Back off, and add jitter.</strong> Two transactions that conflicted once will conflict again if they both retry immediately. Without random jitter, retries line up and the contention gets worse.</p><p><strong>Cap the attempts.</strong> An endless retry loop turns a temporary conflict into an outage.</p><p><strong>The part that is easy to get wrong.</strong></p><p>Retrying means the transaction body may run more than once. That is safe for database work, because the rollback undid it. It is not safe for anything else your code does inside that block.</p><p>Sending an email, calling a payment API, publishing to Kafka, writing a file, increasing a counter in memory — PostgreSQL rolls back none of these. Retry the transaction three times and you may charge a customer three times.</p><p>So the rule is: <strong>the transaction body must be idempotent, or it must contain nothing but database work.</strong> Side effects belong outside the retry boundary, or behind an idempotency key, or in an outbox table written inside the same transaction and processed afterwards.</p><p><strong>Read Committed does not let you off.</strong> It avoids serialization failures for reads, but a deadlock between two transactions taking locks in different orders can happen at any isolation level, and that is 40P01. Retry logic is not a Serializable-only concern.</p><blockquote><strong>In short</strong></blockquote><blockquote>- 40001 and 40P01 are <strong>expected outcomes</strong>, not bugs. They mean the transaction rolled back cleanly and can be run again.</blockquote><blockquote>- Retry only those two SQLSTATEs. Constraint violations and syntax errors will fail again.</blockquote><blockquote>- The retry must wrap the <strong>whole</strong> transaction, with backoff, <strong>jitter</strong>, and a maximum attempt count.</blockquote><blockquote>- The transaction body will run more than once. Non-database side effects — emails, payments, message publishing — must be <strong>idempotent</strong> or moved outside the retry boundary.</blockquote><h3>The Bill: Dead Tuples, Bloat, and VACUUM</h3><p>MVCC’s advantage is that writers never block readers. The price is that every update leaves a corpse behind, and somebody has to bury it.</p><p>That somebody is <strong>VACUUM</strong>.</p><p>Fifty thousand rows, updated once:</p><pre>CREATE TABLE bloat (id int primary key, v int);<br>INSERT INTO bloat SELECT g, g FROM generate_series(1, 50000) g;<br>UPDATE bloat SET v = v + 1;</pre><pre>SELECT n_live_tup, n_dead_tup FROM pg_stat_user_tables WHERE relname = &#39;bloat&#39;;</pre><pre>n_live_tup | n_dead_tup<br>------------+------------<br>      50000 |      50000<br>(1 row)</pre><p>Fifty thousand live rows, fifty thousand dead versions, all in the same table. This is <strong>bloat</strong>: pages your queries still have to read past, and disk you are still paying for.</p><p>If that query returns zeros at first, wait a second and run it again. Table statistics are flushed with a short delay, not on every write.</p><p>VACUUM finds those dead tuples and marks their space reusable. <strong>Autovacuum</strong> does this in the background. By default it starts when the number of dead tuples passes 20% of the table plus 50 rows.</p><p><strong>The failure mode you will actually hit.</strong></p><p>VACUUM cannot remove a dead tuple that some open transaction might still need. The oldest transaction in the system sets a floor — the <strong>xmin horizon</strong> — and nothing above it can be cleaned.</p><p>Open a transaction, take a snapshot, then update every row from somewhere else:</p><pre>-- session A<br>BEGIN ISOLATION LEVEL REPEATABLE READ;<br>SELECT count(*) FROM bloat;    -- snapshot taken here<br>-- and then A just sits there</pre><pre>-- elsewhere<br>UPDATE bloat SET v = v + 1;<br>VACUUM (VERBOSE) bloat;</pre><pre>INFO:  vacuuming &quot;mvcc.public.bloat&quot;<br>INFO:  finished vacuuming &quot;mvcc.public.bloat&quot;: index scans: 1<br>pages: 0 removed, 664 remain, 664 scanned (100.00% of total), 0 eagerly scanned<br>tuples: 0 removed, 100000 remain, 50000 are dead but not yet removable<br>removable cutoff: 784, which was 1 XIDs old when operation ended</pre><p><strong>Zero removed.</strong> Fifty thousand tuples are dead, VACUUM found all of them, and it is not allowed to touch a single one — because session A’s snapshot might still need them.</p><figure><img alt="Animation: an open transaction holds the xmin horizon, VACUUM removes zero tuples, then the transaction commits and the same VACUUM removes fifty thousand." src="https://cdn-images-1.medium.com/max/880/1*QVLKoqMO28KDMBPtinauuQ.gif" /><figcaption>The open snapshot sets a floor. Every dead tuple above it is untouchable until that session ends.</figcaption></figure><p>You can see who is holding the line:</p><pre>SELECT pid, backend_xid, backend_xmin, now() - xact_start AS age<br>FROM pg_stat_activity<br>WHERE backend_xid IS NOT NULL OR backend_xmin IS NOT NULL;</pre><pre>pid | backend_xid | backend_xmin |       age<br>-----+-------------+--------------+-----------------<br> 521 |             |          785 | 00:00:00<br> 552 |             |          784 | 00:00:36.095027<br>(2 rows)</pre><p>The second row is the culprit: open for thirty-six seconds, holding backend_xmin at 784, which is exactly the cutoff VACUUM just reported.</p><p>Close that transaction and run VACUUM again:</p><pre>tuples: 50000 removed, 66642 remain, 0 are dead but not yet removable<br>removable cutoff: 785, which was 0 XIDs old when operation ended</pre><p>Nothing changed except that one session ended.</p><p><strong>Which open transactions actually block cleanup.</strong> Not all of them, and the difference is worth knowing before you go hunting.</p><ul><li>A transaction under <strong>Repeatable Read or Serializable</strong> holds its snapshot from the first statement until it ends. It shows up in backend_xmin, and it blocks cleanup for as long as it is open — even while idle.</li><li>A transaction under <strong>Read Committed</strong> that has <strong>written</strong> something holds an open transaction id. It shows up in backend_xid, and VACUUM cannot move its cutoff past it, so it blocks cleanup too. One UPDATE in an otherwise idle session is enough:</li></ul><pre>-- while that session is open<br>tuples: 0 removed, 39999 remain, 19999 are dead but not yet removable<br><br>-- after it commits<br>tuples: 20000 removed, 20000 remain, 0 are dead but not yet removable</pre><ul><li>A transaction under <strong>Read Committed</strong> that has only <strong>read</strong> does not hold a snapshot between statements. An idle one like this does not block cleanup. It is still worth closing, but it is not what is bloating your tables.</li></ul><p>So the dangerous pattern is precise: a long or idle transaction that either uses a stricter isolation level or has already written. Such a session freezes the horizon for the <strong>whole database</strong>, and the table that bloats may have nothing to do with the query that is stuck.</p><p>Set idle_in_transaction_session_timeout. Watch backend_xid and backend_xmin in pg_stat_activity. And note that Repeatable Read and Serializable make this worse by design: they hold a snapshot for the whole transaction, so a slow one costs more than it would under Read Committed.</p><p><strong>One thing VACUUM does not do.</strong> It just removed fifty thousand dead tuples. Now look at the file:</p><pre>SELECT pg_size_pretty(pg_relation_size(&#39;bloat&#39;)) AS before_full;<br>VACUUM FULL bloat;<br>SELECT pg_size_pretty(pg_relation_size(&#39;bloat&#39;)) AS after_full;</pre><pre>before_full<br>-------------<br> 5312 kB<br><br> after_full<br>------------<br> 1776 kB</pre><p>Ordinary VACUUM made the space <strong>reusable by that table</strong> and left the file at 5312 kB. VACUUM FULL rewrote the table and gave two thirds of the disk back. The catch is in how it does that: it takes an exclusive lock and blocks everything else on the table for the whole rewrite. On a large production table that is an outage, which is why pg_repack exists.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Every update leaves a dead tuple. <strong>VACUUM</strong> reclaims that space; <strong>autovacuum</strong> does it automatically.</blockquote><blockquote>- VACUUM cannot remove tuples that any open transaction might still need. The oldest one sets the <strong>xmin horizon</strong>.</blockquote><blockquote>- Repeatable Read and Serializable transactions block cleanup while open. So do Read Committed transactions that have written. A read-only idle Read Committed session does not.</blockquote><blockquote>- One such transaction can stop cleanup <strong>database-wide</strong>, in tables it never touched.</blockquote><blockquote>- Use idle_in_transaction_session_timeout and watch backend_xid and backend_xmin in pg_stat_activity.</blockquote><blockquote>- Ordinary VACUUM makes space reusable but does <strong>not</strong> shrink the file (5312 kB before and after). VACUUM FULL does, and it takes an exclusive lock while it works.</blockquote><h3>Choosing a Level: A Decision Checklist</h3><p>The mechanism is now on the table. Choosing a level comes down to answering a few questions honestly.</p><p><strong>1. Does any transaction read a value and then write based on it?</strong></p><p>If yes, Read Committed is dangerous. This covers UPDATE ... SET x = x - 100, reservation checks, balance checks, and &quot;does this already exist&quot; checks. Remember the UPDATE 0 from earlier: the row quietly stopped matching and nothing told you.</p><p>If no — if you only write independent values and read for display — Read Committed is fine and cheaper.</p><p><strong>2. Does correctness depend on a rule across several rows?</strong></p><p>“At least one doctor on call.” “The sum of these balances must not go negative.” “No two overlapping bookings.”</p><p>Snapshot isolation cannot protect these. This is <strong>write skew</strong>, and the answer is Serializable, or explicit locking, or a database constraint that enforces the rule directly.</p><p><strong>3. Does a report need a consistent view across many queries?</strong></p><p>Repeatable Read. One snapshot, one point in time, every statement agreeing with the others. Watch how long the transaction runs — a slow report holds the xmin horizon.</p><p><strong>4. Can your application retry?</strong></p><p>If the answer is no, you cannot use Repeatable Read or Serializable safely. The honest fix is to make retry possible, not to drop to a weaker level and hope.</p><p><strong>5. What happens if you move to another database?</strong></p><p>The names are standard. The behavior is not. PostgreSQL’s Repeatable Read prevents phantom reads with a frozen snapshot. InnoDB reaches a similar result for plain SELECTs with its own snapshot, but its locking reads — SELECT ... FOR UPDATE, UPDATE, DELETE — read the latest committed data instead and rely on gap locks, so the behavior differs exactly where you are writing. Serializable in PostgreSQL uses SSI and aborts transactions; other systems use locks and block them instead — same guarantee, completely different failure mode.</p><p><strong>If your code has to run on more than one engine, do not rely on an isolation level name to carry meaning.</strong> Rely on explicit locks, constraints, or application-level checks.</p><p><strong>A default worth having.</strong> Start at Read Committed. Move to Serializable for the specific transactions that carry a rule you cannot break, and keep them short. Isolation level is a per-transaction setting, not an application-wide one.</p><p><strong>Where this goes next.</strong> Everything here decides what a transaction is <em>allowed to see</em>. Sometimes that is not enough. Sometimes you need to reserve a row before you touch it, and tell other transactions to wait. That is explicit locking: SELECT ... FOR UPDATE, advisory locks, and the deadlocks that come with them. That is the next article.</p><h3>References</h3><p><strong>PostgreSQL documentation</strong></p><ul><li><em>Chapter 13: Concurrency Control</em><br> <a href="https://www.postgresql.org/docs/current/mvcc.html">https://www.postgresql.org/docs/current/mvcc.html</a></li><li><em>13.2 Transaction Isolation</em><br> <a href="https://www.postgresql.org/docs/current/transaction-iso.html">https://www.postgresql.org/docs/current/transaction-iso.html</a></li><li><em>Routine Vacuuming</em><br> <a href="https://www.postgresql.org/docs/current/routine-vacuuming.html">https://www.postgresql.org/docs/current/routine-vacuuming.html</a></li><li><em>System Columns</em> <br> <a href="https://www.postgresql.org/docs/current/ddl-system-columns.html">https://www.postgresql.org/docs/current/ddl-system-columns.html</a></li><li><em>pageinspect</em> <br> <a href="https://www.postgresql.org/docs/current/pageinspect.html">https://www.postgresql.org/docs/current/pageinspect.html</a></li><li><em>Transaction ID and Snapshot Information Functions</em><br> <a href="https://www.postgresql.org/docs/current/functions-info.html">https://www.postgresql.org/docs/current/functions-info.html</a></li><li><em>The Statistics Collector</em><br> <a href="https://www.postgresql.org/docs/current/monitoring-stats.html">https://www.postgresql.org/docs/current/monitoring-stats.html</a></li></ul><p><strong>Other engines</strong></p><ul><li>MySQL Reference Manual, <em>Transaction Isolation Levels</em> <br> <a href="https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html">https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html</a></li></ul><p><strong>Background reading</strong></p><ul><li>Hironobu Suzuki, <em>The Internals of PostgreSQL</em><br> <a href="https://www.interdb.jp/pg/">https://www.interdb.jp/pg/</a></li><li>PostgreSQL Wiki, <em>Serializable Snapshot Isolation (SSI)</em> <br> <a href="https://wiki.postgresql.org/wiki/SSI">https://wiki.postgresql.org/wiki/SSI</a></li><li>Michael J. Cahill, Uwe Röhm, Alan D. Fekete, <em>Serializable Isolation for Snapshot Databases</em> (SIGMOD 2008)<br> <a href="https://dl.acm.org/doi/10.1145/1376616.1376690">https://dl.acm.org/doi/10.1145/1376616.1376690</a></li><li>Martin Kleppmann, <em>Designing Data-Intensive Applications</em>, Chapter 7</li></ul><p><strong>Previous article</strong></p><ul><li><a href="https://medium.com/havelsan/database-transactions-and-springs-way-of-managing-them-1ae30b8e6c5c?sharedUserId=mr-yakar"><em>Database Transactions and Spring’s Way of Managing Them</em> </a>— the anomalies described at the behavior level, and the phantom read claim corrected here.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6faddc9291ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Program That Refused To Stop]]></title>
            <link>https://medium.com/@mr-yakar/the-program-that-refused-to-stop-d517a8fd10ab?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d517a8fd10ab</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[volatile]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[atomicity]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 19:25:42 GMT</pubDate>
            <atom:updated>2026-08-03T19:28:41.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDagtXW2Hm-8EvsAst1nOQ.jpeg" /></figure><h3>TL;DR</h3><ul><li>A non-volatile field written by one thread may <strong>never</strong> become visible to another thread. This is not a delay. There is no amount of waiting that fixes it.</li><li>The <strong>JIT compiler</strong> can relocate a field read out of a loop, turning while (!flag) {} into if (!flag) { while (true) {} }. The loop then spins forever.</li><li>The compiler and the CPU may also <strong>reorder</strong> your writes. Another thread can see write #2 before write #1. This is legal.</li><li>The <strong>Java Memory Model (JMM)</strong> is a specification, not a description of hardware. It lists what <em>cannot</em> happen. Anything not forbidden is allowed.</li><li><strong>happens-before</strong> is the only ordering relation that matters. Without a happens-before edge between a write and a read, nothing is guaranteed.</li><li>The edges come from a short list: program order, monitor unlock/lock, volatile write/read, Thread.start(), Thread.join(), interruption, default initialization — plus transitivity.</li><li>volatile creates an edge. It publishes <strong>everything</strong> the writing thread did before the write, not just the marked field.</li><li>volatile gives you <strong>visibility</strong>, not <strong>atomicity</strong>. count++ is still three operations and is still broken under concurrency.</li></ul><p>On cool summer mornings, Amo would sneak out to the street and play ball while his parents were still asleep.</p><p>There was only one rule: he had to come home when breakfast was ready. And rather than shout across the street and wake the neighbors, Amo’s mother would write the news on the wall in front of the house.</p><p><em>Breakfast is not ready.</em></p><p>The wall stood at the far end of the street. Checking it meant stopping the game, running down, reading, and running back.</p><p>That is what he did, the first few mornings.</p><p>That morning, Amo’s mother came out of the kitchen, picked up the chalk, wiped the wall clean and wrote a new message:</p><p><strong>BREAKFAST IS READY!</strong></p><p>Then she went back inside. She set the table. She poured the tea. From somewhere down the street came the steady thud of a ball against a garage door.</p><p>Nobody came.</p><p>The eggs went cold.</p><p>The same thing happens in Java:</p><pre>public class Breakfast {<br><br>    static boolean breakfastReady = false;<br><br>    public static void main(String[] args) throws InterruptedException {<br>        Thread amo = new Thread(() -&gt; {<br>            long kicks = 0;<br>            while (!breakfastReady) {<br>                kicks++;<br>            }<br>            System.out.println(&quot;Amo came home after &quot; + kicks + &quot; kicks.&quot;);<br>        });<br><br>        amo.start();<br>        Thread.sleep(1000);<br><br>        breakfastReady = true;<br>        System.out.println(&quot;The wall says: BREAKFAST IS READY!&quot;);<br><br>        amo.join();<br>        System.out.println(&quot;Breakfast is served.&quot;);<br>    }<br>}</pre><pre>The wall says: BREAKFAST IS READY!<br>^C</pre><p>On my machine it hangs every time — five runs, five hangs, five interrupts by hand.</p><p>The write happened. The message is correct. The program is wrong.</p><p>Why?</p><blockquote><strong>In short</strong></blockquote><blockquote>- One thread sets a boolean to true. Another thread loops until it becomes true.</blockquote><blockquote>- The write clearly happens — you can see the proof printed on the screen.</blockquote><blockquote>- The loop never ends. The program has to be killed by hand.</blockquote><h3>The Convenient Lie We Believe</h3><blockquote>One thread writes to a field. Another thread reads it. The second one sees the value that was written.</blockquote><blockquote>Nobody taught you this. You never needed to learn it, because you never thought to question it.</blockquote><p>Look at the output again. The write happened — the proof is on the screen. The reader still sees the old value. The <strong>assumption is broken</strong>, and the program that broke it does nothing clever.</p><p>Amo did not play alone. His friend Simo played with him, and Simo had a notebook in her pocket.</p><p>The notebook was copied from the wall once, at the start of the game. The wall was at the far end of the street, and Simo was not lazy. She was right. Nobody told her to copy it. She worked it out herself.</p><p>The wall was updated. The notebook was not.</p><p>The first villain: the <strong>stale copy</strong>.</p><figure><img alt="The wall was updated. The notebook was not. The loop keeps running." src="https://cdn-images-1.medium.com/max/880/1*3YK6xNJzg4ZJ87rFCQgpyQ.gif" /></figure><p>There is a second villain, and it was in the story all along.</p><p>The mother wrote READY, then she set the table, then she poured the tea. If Amo had come home between those moments, he would have found an empty table and an empty glass. The message was correct but not real.</p><p><strong>The order you write is not a promise about the order that runs.</strong></p><p>Neither villain is a defect. Both are <strong>optimizations</strong>, and both are usually right. Simo’s notebook saved her a hundred trips down the street, and the reordering that will cost you an afternoon of debugging is the same machinery that makes every other program on your laptop fast enough to use.</p><blockquote><strong>A word about the wall.</strong></blockquote><blockquote>The notebook is an honest picture of the first villain. There is a thing in the world, it holds a copy, and the copy goes out of date. You can point at it.</blockquote><blockquote>The second villain has no such thing. Nothing in the street rearranges the mother’s morning. If she wrote before she set the table, that was her decision — and decisions belong to the programmer. Real reordering is not decided by anyone who wrote the code. It is <strong>permitted</strong> to happen to it.</blockquote><blockquote>That is where the wall runs out. You can draw a notebook. You cannot draw a permission.</blockquote><p>It is tempting to file this under <strong>slowness</strong>. A copy goes stale, the new value takes a while to arrive, the loop spins a few thousand extra times. Annoying, but limited.</p><p>Look again at what happened. Amo did not come home late. He did not come home. The eggs went cold and stayed cold, and the program was still running when you killed it.</p><p>There is a smaller thing that should bother you more. Adding a print statement inside the loop changed the outcome. Slowness does not behave like that. Slowness does not care what else is in the room.</p><p>So ask the obvious question: how long would you have to wait? There is no number. Not a large one — none. And the missing number is not a gap in this article.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Two separate problems can hide a write from another thread: a <strong>stale copy</strong>, and <strong>reordering</strong>.</blockquote><blockquote>- Neither one is a bug in the JVM. Both are optimizations that are correct almost all the time.</blockquote><blockquote>- This is not slowness. Slow means late. This means never.</blockquote><h3>Visibility: Seeing Is Not Guaranteed</h3><p>The obvious explanation is that the value arrives late.</p><p>It is a reasonable theory, and it deserves a fair test. Caches go stale everywhere in computing, and stale things get refreshed. Your DNS resolver catches up. Your CDN catches up. Your browser catches up if you wait long enough or press reload twice. The word <em>cache</em> carries a promise inside it: wrong for now, right eventually. A few million wasted iterations is nothing to a modern processor. Amo is slow to notice. Amo will notice.</p><p>Two experiments say otherwise.</p><p>The first one you may have already run by accident. Put a println inside the loop, next to where Amo kicks the ball, and the program stops — on my machine, after about thirteen million kicks. Nothing about the waiting changed. What changed is that <strong>something else is now in the room</strong>. Slowness does not care what else is in the room.</p><p>The second experiment is harder to argue with, because it does not touch the code at all.</p><pre>$ java Breakfast.java<br>The wall says: BREAKFAST IS READY!<br>^C</pre><pre>$ java -Xint Breakfast.java<br>The wall says: BREAKFAST IS READY!<br>Amo came home after 105349152 kicks.<br>Breakfast is served.</pre><p>-Xint tells the JVM to run in interpreter mode and skip optimization.</p><blockquote><strong>Environment</strong></blockquote><blockquote>- Intel Core i7–4700HQ (4 cores / 8 threads, x86–64)</blockquote><blockquote>- 16 GB DDR3</blockquote><blockquote>- Ubuntu 26.04</blockquote><blockquote>- Amazon Corretto 21.0.11 (OpenJDK 21, HotSpot, mixed mode)</blockquote><p>Same file. Same machine. One flag. The second run comes home after a hundred million kicks — <strong>far more waiting</strong> than the first run ever needed. It waited longer and it succeeded. The first waited forever and failed.</p><p>So what changed is not how long anyone waited. What changed is <strong>what the machine was allowed to do with the code</strong>.</p><p>This is worth sitting with, because the instinct now is to reach for a fix. Wait longer. Put a Thread.sleep in the loop. Call Thread.yield. Give the loop more work so it runs slower.</p><p>Some of these will appear to work.</p><p>That is the worst outcome available to you. A change that hides the failure without promising anything has not fixed the program. It has removed your only evidence that something is wrong. The bug survives, the symptom leaves, and you ship with confidence you have not earned. This is the shape of every <strong>Heisenbug</strong>: it reacts to being watched, and looking at it the wrong way makes it disappear.</p><p>Ask the question directly. How long would you have to wait?</p><p>There is no answer. Not a large number, not an unpredictable one — <strong>there is no number</strong>, because time is not the missing ingredient. Waiting longer cannot get you there, in the same way that waiting cannot turn Monday into Tuesday if the calendar has stopped.</p><p>Which means the question was wrong. Asking <em>how long</em> is asking for the size of something that was never there.</p><p>The right question is what would make the value visible <strong>at all</strong> — not sooner, but at all. Somebody has to promise that a write becomes visible to a reader. Nothing in the program we have written contains such a promise.</p><p>So: who promises what, and to whom?</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- Adding a println inside the loop makes the program stop. Timing does not work that way.</blockquote><blockquote>- Running with -Xint makes the program stop, with <strong>no code change at all</strong>.</blockquote><blockquote>- The -Xint run waited eight times longer than the broken run and still finished. So waiting was never the problem.</blockquote><blockquote>- There is no amount of time that fixes this. The guarantee is missing, not late.</blockquote><h3>Reordering: The Order You Write Is Not The Order It Runs</h3><p>“Why does the value never become visible?” is settled. The new question: even when the value does become visible, in what order does it arrive?</p><pre>// mother<br>table = &quot;set&quot;;<br>breakfastReady = true;</pre><pre>// Amo<br>if (breakfastReady) {<br>    eat(table);      // table may still be null<br>}</pre><p>Amo’s reasoning is sound. The wall says READY, so the mother wrote it; she writes it when the table is set; therefore the table is set. Every step follows. He walks in and finds an empty table.</p><p>Only one link in that chain is broken, and it is not the one you would suspect. He read the flag correctly. The mother did set the table first. Her order was right from beginning to end.</p><p>The broken link is the one nobody writes down: <strong>that the order she worked in is the order Amo gets to see.</strong></p><p>Inside a single thread, that order is real. table = &quot;set&quot; genuinely happens before breakfastReady = true, and any code in that thread will see it that way. The guarantee is airtight — and it covers <strong>exactly one observer</strong>.</p><p>Amo is a different observer. Nothing was promised to him.</p><p>So table being null while breakfastReady is true breaks no rule. The comment in that snippet is not warning you about a rare race under load. It is describing what the program is permitted to do. Not unlikely, not timing-dependent: <strong>legal</strong>.</p><figure><img alt="Both writes happen. Only the order of arrival differs — and nothing in the program forbade it." src="https://cdn-images-1.medium.com/max/880/1*UPNSao2einjZ3XhvQ80l8w.gif" /></figure><p>The compiler and the CPU are both free to reorder your instructions. The one constraint: a <strong>single-threaded observer</strong> must not be able to tell.</p><p>Three layers can reorder what you wrote: the <strong>compiler and JIT</strong>, the <strong>CPU</strong> itself (out-of-order execution, store buffers), and the <strong>memory system</strong> beneath it. Most developers assume the CPU is the culprit. More often it is the compiler — and the JIT keeps rewriting code that is already running.</p><p>You do not have to take this on faith. Run the first program again with one extra flag:</p><pre>java -XX:+PrintCompilation Breakfast.java 2&gt;&amp;1 | grep Breakfast</pre><pre>620 1385 %     3       me.yakar.Breakfast::lambda$main$0 @ 2 (28 bytes)<br>621 1387 %     4       me.yakar.Breakfast::lambda$main$0 @ 2 (28 bytes)</pre><p>The % means <strong>on-stack replacement</strong>: the loop was already running when its code was swapped underneath it. The 3 and 4 are compiler tiers — first C1, then C2, each optimizing more aggressively than the last.</p><p>Now compare the timestamps with the program. The main thread sleeps for one second before it sets the flag. Both recompilations happened at around 620 ms — while Amo was already spinning, and <strong>before the write ever took place</strong>. By the time the mother picked up the chalk, the loop had already been rewritten twice, and the version running at that moment was the most optimized one the JVM could produce.</p><p>The code that eventually ran is not the code you wrote, and it was not even chosen when the program started.</p><p>x86 gives you <strong>strong ordering</strong>. Stores become visible in the order they were issued, so several categories of reordering never surface there — though not all of them. <strong>ARM</strong> and <strong>POWER</strong> promise far less, and they are what your phone runs on, and increasingly your servers.</p><p>Every experiment in this article ran on x86–64. So there are reorderings I cannot show you here: not because they are rare, but because this hardware suppresses them. Elsewhere it does not. And the hardware is only one of the three layers — the compiler above it is free to reorder on x86 too, as the first program already demonstrated on this very machine.</p><p>“It works on my machine” is not weak evidence here. <strong>It is not evidence.</strong></p><p>Two villains, then. One never shows you the value. The other shows it in an order you did not write.</p><p>Neither is malfunctioning. The JIT kept its promise: no single-threaded observer could tell the difference. The CPU kept its promise. x86 kept its promise. Every layer behaved exactly as specified.</p><p>Nobody ever made a promise to your <strong>second thread</strong>.</p><blockquote><strong>In short</strong></blockquote><blockquote>- Compiler, JIT, CPU, and memory system may all reorder your instructions.</blockquote><blockquote>- The only rule they must obey: a <strong>single-threaded</strong> observer must not notice. Your other thread is not that observer.</blockquote><blockquote>-XX:+PrintCompilation shows the loop being recompiled twice while it is already running.</blockquote><blockquote>- x86 hides some reorderings. ARM and POWER do not. The same code can behave differently on different hardware.</blockquote><h3>The Java Memory Model (JMM): A Contract, Not a Machine</h3><p>“Nobody ever made a promise to your second thread.” So who does make one?</p><p>The <strong>JMM</strong> does. It is not a machine. It is a model that defines what one thread is guaranteed to see of another thread’s work, and in what order.</p><p>When you picture the JMM, you probably picture hardware: caches, cores, store buffers. That is the notebook again — and you were warned about it. You can sketch a notebook, but not a permission. The picture is useful for intuition and wrong as a definition.</p><p>Here is the evidence. How else do you get two different outcomes from the same program on the same machine? Recall -Xint. One flag, no code change, no hardware change — and the loop that ran forever now terminates. What changed is what the JVM was <strong>permitted</strong> to do. If a rule cannot be read off the hardware, the hardware is not its source.</p><p>So who are the parties?</p><p>On one side, you. On the other, every JVM implementation on every architecture it will ever run on — HotSpot on x86, OpenJ9 on POWER, whatever runs on hardware that has not been designed yet. The JMM does not describe how one machine behaves. It defines the <strong>minimum</strong> every one of them must follow.</p><p>And here the contract runs in the direction you would not expect. It does not tell you what <em>will</em> happen. It tells you what <em>cannot</em> happen. It is a <strong>list of prohibitions</strong>, not a list of promises.</p><p>Which means anything not prohibited is legal. The run you observed is one lawful execution out of many. Tomorrow you may get a different one, and both are correct. This is why <strong>testing cannot prove the absence of a concurrency bug</strong>: a green test suite tells you which execution you happened to get, not which ones were available.</p><p>You might conclude from all this that you have been given nothing. The opposite is true. The contract is exactly what lets you write code on a MacBook and run it on an ARM server without thinking about either. Without it, “write once, run anywhere” would still hold for a single thread and quietly break the moment you started a second one — and you would be tuning for store buffers per architecture, by hand.</p><p>So: there is a contract. The parties are known. One question remains.</p><p>What language are its clauses written in?</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- The JMM is a <strong>specification</strong>, not a description of any particular CPU.</blockquote><blockquote>- It binds every JVM on every architecture, including hardware that does not exist yet.</blockquote><blockquote>- It works by listing what <strong>cannot</strong> happen. Everything else is allowed.</blockquote><blockquote>- A passing test shows you one legal execution. It does not show you the others.</blockquote><h3>Happens-Before: The Fine Print of the Contract</h3><p>In ordinary speech, “one thing happens before another” is a claim about time — hours, minutes, one clock reading smaller than another. Here that instinct is a trap. The clauses of this contract are not about <strong>time</strong>. They are about <strong>order</strong>.</p><p>When A <strong>happens-before</strong> B, everything A did is visible to B, and B is ordered after it. That is the whole content of the phrase.</p><p>The hyphen matters. <strong>happens before ≠ happens-before.</strong></p><p>The mother’s scene gives you this for free. table = &quot;set&quot; literally happened before breakfastReady = true — by any clock you care to hold up. But there was no happens-before edge reaching Amo, so nothing was guaranteed to him. Time passed. The guarantee did not.</p><p>The contract has a short list of clauses. Each one creates a happens-before edge; nothing else does.</p><p><strong>Program order.</strong> Within a single thread, each action happens-before every action that comes after it in the source. Airtight, and limited to one thread.</p><p><strong>Monitor lock.</strong> An unlock on a monitor happens-before every later lock on that same monitor.</p><p><strong>Volatile.</strong> A write to a volatile field happens-before every later read of that same field.</p><p><strong>Thread start.</strong> A call to start() on a thread happens-before any action in the started thread.</p><p><strong>Thread termination.</strong> All actions in a thread happen-before another thread returns from join() on it.</p><p><strong>Interruption.</strong> A thread interrupting another happens-before the interrupted thread detects it.</p><p><strong>Initialization.</strong> The default initialization of a field — 0, false, null — happens-before any other action in the program.</p><p>And the rule that makes the rest worth having:</p><p><strong>Transitivity.</strong> If A happens-before B and B happens-before C, then A happens-before C.</p><p>Two of these clauses mention a specific keyword and a specific method pair. Everything else on the list is either automatic or something you already do without thinking.</p><p>Which brings us to an uncomfortable observation about the program you have been running since the beginning. It already contains <strong>two happens-before edges</strong>. You wrote them without noticing.</p><p>amo.start() is one: everything the main thread did before that call is guaranteed visible to Amo. amo.join() is the other, running the opposite way — everything Amo did is guaranteed visible to the main thread once join() returns.</p><p>Look at where the write sits:</p><pre>amo.start();             // edge #1<br>Thread.sleep(1000);<br>breakfastReady = true;   // no edge<br>amo.join();              // edge #2</pre><figure><img alt="start() and join() each create an edge. The write in the middle is attached to neither." src="https://cdn-images-1.medium.com/max/880/1*JHrk473PjDeYWKIhtG6xgA.gif" /></figure><p>The write happens <strong>after</strong> start(), so the start rule does not cover it. It happens <strong>before</strong> join() returns, but Amo is not reading anything after join() — he is spinning inside it. The one write that matters in the entire program is the one action not attached to any edge on the list.</p><p>That is the bug. Not a cache, not a compiler, not an architecture. <strong>A missing clause.</strong></p><p>Earlier we called reordering a permission. Happens-before is the leash.</p><p>Where an edge exists, reordering does not disappear — the machine may still shuffle instructions underneath. What it may not do is let the shuffling <strong>become visible</strong> across the edge. This is the same shape as before: the contract does not describe what the hardware does. It describes what you are allowed to observe.</p><p>So you now know the language the clauses are written in, and you know your program is missing one.</p><p>You still do not know how to write one.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote><strong>- happens-before</strong> is about ordering and visibility, not about the clock.</blockquote><blockquote>- Something happening earlier in time guarantees nothing across threads.</blockquote><blockquote>- The full list of edges is short: program order, monitor unlock/lock, volatile write/read, start(), join(), interruption, default initialization — plus transitivity.</blockquote><blockquote>- Our program already had two edges (start() and join()). The one write that mattered had none.</blockquote><h3>volatile: The Always-Synced Field</h3><p>Go back to the list. One clause does exactly what this program is missing: <em>a write to a volatile field happens-before every later read of that same field.</em></p><p>So we add one keyword:</p><pre>static volatile boolean breakfastReady = false;</pre><p>Nothing else in the file changes. Run it again:</p><pre>The wall says: BREAKFAST IS READY!<br>Amo came home after 1700811096 kicks.<br>Breakfast is served.</pre><figure><img alt="No cached copy. Every turn is a real read, so the new value is seen the moment it is written." src="https://cdn-images-1.medium.com/max/880/1*g-aEm7d1kGfnVhIkJ_wzRw.gif" /></figure><p>Amo looked at the wall — the real one, at the far end of the street, the way he did on the first mornings. He read it and ran.</p><p>The eggs were still warm.</p><p>Half of this is obvious. The read cannot be lifted out of the loop anymore. Every turn goes back to the field and asks again.</p><p>That is where most explanations stop. It is the smaller half.</p><p>Here is the other one. The edge does not carry only breakfastReady. <strong>It carries everything the writing thread did before it.</strong></p><p>Which means the mother’s scene works now, too. table = &quot;set&quot; came before the volatile write, so it sits on the safe side of the edge. Amo sees a set table, not a null one.</p><p>And table is not volatile. Nobody touched it.</p><p>None of this is free. But the cost is not where most people put it.</p><p>The usual story goes like this: a volatile field skips the cache and goes all the way to RAM, every read, every write. Tidy, memorable, and wrong. If it were true, volatile would be unusable — main memory is roughly two hundred times slower than L1 cache. On x86, a volatile read costs about the same as an ordinary one.</p><p>Here is what actually happens.</p><p>The <strong>caches were never the problem</strong>. Modern processors keep them in sync with each other, in hardware, without being asked. One core writes a value; the other cores’ caches are told. That machinery runs whether or not you type volatile.</p><p>What is <em>not</em> kept in sync is a copy sitting in a <strong>register</strong>. Registers are the CPU’s private scratch space, and nothing coordinates them with anything. That is where Simo’s notebook really lives. Not in the cache — in a register. The compiler put it there because reading the same field over and over looked wasteful, and nothing forbade it.</p><p>So the first half of the cost is paid by the <strong>compiler</strong>. It loses moves. It cannot park the field in a register, cannot lift the read out of the loop, cannot reuse a value it read a moment ago. Every turn is a real read.</p><p>The second half is paid on the <strong>write</strong>. On x86, a volatile write is followed by a barrier that forces the processor to push out its pending writes before anything after it may proceed. That waiting is the expensive part. Reads are nearly free; writes are where the bill arrives.</p><p>The notebook is gone. Amo runs to the wall every single time — and the mother now waits at the wall until the writing is truly there.</p><p>So the program is fixed, the story has an ending, and you have a keyword that solves the problem you started with.</p><p>Which is a good moment to be careful.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- volatile creates a happens-before edge, which is exactly the missing clause.</blockquote><blockquote>- The edge publishes <strong>everything</strong> the writing thread did before the write — not only the marked field.</blockquote><blockquote>- volatile does not push data to RAM. Caches are already kept in sync by hardware. What it stops is the compiler keeping a copy in a <strong>register</strong>.</blockquote><blockquote>- Reads are cheap. The cost sits on the <strong>write</strong>, because of the memory barrier that follows it.</blockquote><h3>What volatile Does NOT Give You</h3><p>One keyword, one line, problem solved. That is a good feeling, and it is worth keeping — for about a page.</p><p>Take the same keyword one step further and watch it come apart.</p><p>Two threads, one counter, a million increments each. The field is volatile, so visibility is handled.</p><pre>public class Counter {<br>    static volatile int count = 0;<br><br>    public static void main(String[] args) throws InterruptedException {<br>        Runnable job = () -&gt; {<br>            for (int i = 0; i &lt; 1_000_000; i++) {<br>                count++;<br>            }<br>        };<br><br>        Thread a = new Thread(job);<br>        Thread b = new Thread(job);<br><br>        a.start(); b.start();<br>        a.join();  b.join();<br><br>        System.out.println(&quot;expected: 2000000&quot;);<br>        System.out.println(&quot;actual:   &quot; + count);<br>    }<br>}</pre><pre>expected: 2000000<br>actual:   1422924</pre><p>Run it again and you get a different number. Run it a few more times and you may get the right one, which is worse than getting the wrong one — the same point the reordering section made, arriving again from a different direction.</p><p>Nearly six hundred thousand increments are missing. Where did they go?</p><p>count++ looks like one instruction. <strong>It is three.</strong></p><p>Read the value. Add one. Write it back.</p><p>Now put two threads inside those three steps. Both read 41. Both add one. Both write 42. Two increments went in, one came out.</p><figure><img alt="Nothing was stale. Both threads read a current value — they just read the same one." src="https://cdn-images-1.medium.com/max/880/1*6w4cpErHONDHpCcl7mfTcw.gif" /></figure><p>Look closely at what did <em>not</em> go wrong there. Nothing was stale. Both threads read a perfectly current value — the volatile clause did its job exactly as written. They just read the <strong>same</strong> one.</p><p>These are two different guarantees, and it is worth saying their names out loud.</p><p><strong>Visibility</strong> is about whether you see the latest value. <strong>Atomicity</strong> is about whether an operation can be interrupted halfway through.</p><p>volatile gives you the first. It has never given you the second. Everything in this article up to now has been about the first one.</p><p>This is not a gap in the language, and it is not a defect in volatile. Go back to the clause: <em>a write to a volatile field happens-before every later read of that same field.</em> Read it again and notice what it does not mention. It says nothing about two threads taking turns. Nothing about an operation running start to finish without interference.</p><p>You asked the contract for a term that was never in it. And the contract did what it has done all along — it kept its word, precisely, and no further.</p><p>The tools for the other guarantee exist, and they are not this one. AtomicInteger for a counter like this. synchronized or a Lock when several fields have to move together. LongAdder when the counter is hot and heavily contended. Each of those deserves its own article. None of them is volatile.</p><p>So keep the keyword, and keep it for what it is: the right tool for a narrow job. One thread writes a value, other threads read it, and nobody’s write depends on what they just read. A status flag. A shutdown signal. A reference published once and then left alone.</p><p>The moment a write depends on the value you just read, volatile is no longer enough — and you need a different clause.</p><blockquote><strong><em>In short</em></strong></blockquote><blockquote>- volatile gives <strong>visibility</strong>. It does not give <strong>atomicity</strong>.</blockquote><blockquote>- count++ is read, add, write. Two threads can sit inside those three steps and lose an update.</blockquote><blockquote>- Nothing was stale in that failure. Both threads read a current value — the same one.</blockquote><blockquote>- Use AtomicInteger, synchronized, a Lock, or LongAdder when a write depends on the value just read.</blockquote><h3>The Contract Cheat Sheet</h3><p>You started with a program that would not stop. You now know why, and the answer turned out to have almost nothing to do with the program.</p><p>Here is what to carry out of it.</p><p><strong>1. Visibility is not a matter of time.</strong></p><p>A value that is not guaranteed to arrive does not arrive late. It may not arrive at all. There is no duration that fixes a missing guarantee, which is why adding a sleep, slowing the loop, or waiting longer are not fixes — at best they hide the failure and cost you the evidence.</p><p><strong>2. The order you write is not the order that runs.</strong></p><p>The compiler, the JIT, and the processor may all rearrange your instructions. The single constraint is that a single-threaded observer must not be able to tell. Your second thread is not that observer.</p><p><strong>3. The JMM is a contract, not a machine.</strong></p><p>It does not describe caches, cores, or store buffers. It defines the minimum every JVM on every architecture must honor. It works by listing what cannot happen, which means everything not forbidden is legal — and the run you observed was one lawful execution out of many. Testing shows you which one you got, not which ones were available.</p><p><strong>4. Happens-before is the only currency.</strong></p><p>Nothing is visible across threads unless an edge makes it so. The clauses are short and there is no secret extra one: program order, monitor unlock to lock, volatile write to read, start() into a thread, a thread into join(), interrupt to detection, default initialization. And transitivity, which is what lets them chain into something useful.</p><p><strong>5. </strong><strong>volatile buys visibility, not atomicity.</strong></p><p>It creates an edge, and the edge carries everything the writing thread did before it — not just the field you marked. What it does not do is make an operation indivisible. count++ is still three steps, and two threads still fit inside them.</p><p><strong>The question to ask</strong></p><p>When you next see a field touched by more than one thread, do not ask whether it looks thread-safe. Ask two things instead:</p><p><strong>Who writes it, and which clause guarantees that the reader sees it?</strong></p><p>If you cannot name the clause, there isn’t one. Not a small guarantee, not a probable one, not one that holds most of the time on your laptop. There isn’t one.</p><p>The eggs go cold quietly, and the program keeps running.</p><h3>References</h3><p><strong>Specification</strong></p><ul><li><em>The Java® Language Specification, Chapter 17: Threads and Locks </em>(§17.4.5).<br> <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html">https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html</a></li><li><em>JSR-133: Java Memory Model and Thread Specification</em> (2004)<br> <a href="https://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf">https://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf</a></li><li><em>JSR-133 (Java Memory Model) FAQ</em> <br> <a href="https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html">https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html</a></li></ul><p><strong>Implementation and hardware</strong></p><ul><li>Doug Lea, <em>The JSR-133 Cookbook for Compiler Writers</em><br> <a href="https://gee.cs.oswego.edu/dl/jmm/cookbook.html">https://gee.cs.oswego.edu/dl/jmm/cookbook.html</a></li><li>Rajiv Prabhakar, <em>Myths Programmers Believe about CPU Caches</em><br> <a href="https://software.rajivprab.com/2018/04/29/myths-programmers-believe-about-cpu-caches/">https://software.rajivprab.com/2018/04/29/myths-programmers-believe-about-cpu-caches/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d517a8fd10ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Transactions and Spring’s Way of Managing Them]]></title>
            <link>https://medium.com/havelsan/database-transactions-and-springs-way-of-managing-them-1ae30b8e6c5c?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae30b8e6c5c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 05:36:37 GMT</pubDate>
            <atom:updated>2023-12-27T11:15:15.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*g68r038XtlWOA0slE31CkQ.jpeg" /></figure><h3>Introduction</h3><p>In this article, we’ll begin by defining what a transaction is. Today, it’s a concept widely used in various professional domains. Our focus is specifically on database transactions. We’ll explore their definition, use cases, and key features. Once we’ve covered these foundational aspects, we’ll delve into the A.C.I.D. principles critical for successful transaction execution. Following that, we’ll address isolation and propagation properties, pivotal in determining transaction behavior. By the article’s end, we’ll gain valuable insights into transaction management in Spring Framework, including its advantages and abstraction mechanism. Finally, we’ll conclude with best practices essential for a software engineer to ensure a successful implementation.</p><figure><img alt="A man is messing up with the database." src="https://cdn-images-1.medium.com/max/500/1*4V1ySINh_VHUEZ0vMPH_kw.jpeg" /><figcaption>A man who is messing with database.</figcaption></figure><p>For an engineer unfamiliar with transactions, this article is ideal as it begins right from the basics.</p><p>Let’s kick off by establishing some definitions.</p><h3>What is a Transaction?</h3><figure><img alt="A funny meme that implies an unwanted situation that can happen in a database when two customers book same room in a hotel at the same time." src="https://cdn-images-1.medium.com/max/668/1*f7EnnVqB_l4eJBuU6gmyRw.jpeg" /><figcaption>A funny meme that is about two users booking the same room at the same time.</figcaption></figure><p>The <a href="https://dictionary.cambridge.org/dictionary/english/transaction">Cambridge</a> Dictionary provides multiple definitions of “transaction.” Here are the first two:</p><blockquote>An occasion when someone buys or sells something.</blockquote><blockquote>The process of doing business.</blockquote><p>In the context of databases, our focus lies on database transactions. <a href="https://en.wikipedia.org/wiki/Database_transaction">Wikipedia</a> defines a database transaction as:</p><blockquote>A database transaction symbolizes a unit of work, performed within a database management system (or similar system) against a database, that is treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in a database.</blockquote><p>In simple terms, a transaction is a collection of individual yet interconnected tasks that, in practice, act as a single unit. They rely on each other — if one fails, they all fail. In database systems, these interconnected tasks are referred to as transactions.</p><p>Transactions have two main purposes;</p><ol><li>To manage multiple tasks and recover from failures without compromising the database’s consistency.</li><li>To ensure transactions operate independently without affecting one another, maintaining isolation.</li></ol><p>These properties lead to principles transactions must adhere to. For instance, since a transaction is an individual unit of work, it must be atomic.</p><p>Let’s continue with these principles.</p><h3>A.C.I.D. Principles</h3><figure><img alt="An actor who is telling the famous quote that is “To be or not to be”. This time is for transactions." src="https://cdn-images-1.medium.com/max/450/1*7T4hzH-TLIqtUq-kv-Ahxw.jpeg" /><figcaption>A meme that mentions about the famous quote of Hamlet that is “to be or not to be”. This time is for transactions.</figcaption></figure><p>In computer science, ACID principles (Atomicity, Consistency, Isolation, Durability) outline a set of properties that all transactions must uphold. These principles ensure data validity even in the face of errors, hardware issues, or any other factors that might compromise data or database integrity.</p><p>In brief, any group of database actions that meet the ACID principles is termed a transaction.</p><p>As we move forward discussing definitions and traits, we’ll utilize a unique SQL script. Our scenario is a fictional one, featuring three characters from a highly popular movie series: Harry Potter. We’ll explore each principle alongside Harry, Hermione, and Ron. Let’s start by reviewing the upcoming SQL script.</p><pre>DROP TABLE IF EXISTS Houses CASCADE;<br>CREATE TABLE Houses<br>(<br>    id BIGINT NOT NULL,<br>    name VARCHAR,<br>    CONSTRAINT houses_primary_key_constraint PRIMARY KEY (id)<br>);<br><br>INSERT INTO Houses(id, name) VALUES (1, &#39;Gryffindor&#39;);<br>INSERT INTO Houses(id, name) VALUES (2, &#39;Slytherin&#39;);<br>INSERT INTO Houses(id, name) VALUES (3, &#39;Ravenclaw&#39;);<br>INSERT INTO Houses(id, name) VALUES (4, &#39;Hufflepuff&#39;);<br><br>DROP TABLE IF EXISTS Wizards;<br>CREATE TABLE Wizards<br>(<br>    id       BIGINT  NOT NULL,<br>    name     VARCHAR NOT NULL,<br>    surname  VARCHAR NOT NULL,<br>    house_id BIGINT,<br>    CONSTRAINT wizards_primary_key_constraint PRIMARY KEY (id)<br>);<br><br>ALTER TABLE Wizards<br>    ADD CONSTRAINT <br>      wizards_foreign_key_constraint_on_houses <br>      FOREIGN KEY (house_id) REFERENCES Houses (id);</pre><p>Imagine this script running within Hogwarts’ database system. Following its execution, we now have two tables: Houses and Wizards. Essentially, we’ve established a basic system to enroll new wizards at Hogwarts, with the option to assign them to a specific Hogwarts house, representing a distinctive group for wizards.</p><p>We also have specific constraints to adhere to when registering new wizards. One of these rules is that two wizards cannot share the same identification number. With this groundwork, let’s delve into the principles in more depth.</p><h4>Atomicity</h4><p>The principle that governs the atomic nature of a transaction. As previously discussed, a transaction comprises tasks treated as a single unit of work. Simply put, either all sub-tasks within a transaction execute successfully, or none of them affect the database. In essence, it’s an all-or-nothing action.</p><p>Otherwise, it might compromise data integrity, potentially resulting in data loss caused by an unsuccessfully executed sub-task.</p><p>Let’s illustrate this principle with an example by writing some additional SQL script.</p><p>It’s time to enroll Harry, Hermione, and Ron at Hogwarts.</p><pre>BEGIN;<br><br>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (1, &#39;Harry&#39;, &#39;Pother&#39;, 1);<br><br>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (2, &#39;Hermonie&#39;, &#39;Granger&#39;, null);<br><br>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (3, &#39;Ron&#39;, &#39;Weasley&#39;, null);<br><br>COMMIT;</pre><p>As seen in the movie series, Harry, Hermione, and Ron are inseparable friends. Their bond is crucial, and they can’t function well if one is absent. Consequently, we must register them together at Hogwarts. It’s an all-or-none scenario; either all of them are registered or none of them are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNfLKCaFdfugZRH0-GbabQ.jpeg" /></figure><p>In this heartfelt scenario, the insertion of their information is treated as a single unit of work, ensuring it’s carried out within a transaction. This transaction is atomic, guaranteeing its completion as a whole.</p><p>We start the transactional work with</p><pre>BEGIN;</pre><p>keyword. We can also use the following variations to do the same action;</p><pre>BEGIN WORK;<br>-- or<br>BEGIN TRANSACTION;</pre><p>Then we insert their information;</p><pre>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (1, &#39;Harry&#39;, &#39;Pother&#39;, 1);<br><br>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (2, &#39;Hermonie&#39;, &#39;Granger&#39;, null);<br><br>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (3, &#39;Ron&#39;, &#39;Weasley&#39;, null);</pre><p>Harry holds a special place for us, and that’s why we’ll assign him to one of the Hogwarts Houses first. Hermione and Ron will be assigned later.</p><p>To end the transaction, we use</p><pre>COMMIT;</pre><p>keyword. We can also use the following variations to complete the transaction;</p><pre>COMMIT WORK;<br>-- or<br>COMMIT TRANSACTION;</pre><p>Let’s execute this SQL script with an error. Change Ron’s identification number to null to simulate a situation where the official forgot to add an identification number for Ron.</p><pre>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (null, &#39;Ron&#39;, &#39;Weasley&#39;, null);</pre><p>You’ll notice that the SQL console raises an error because of the missing identification number for Ron. Consequently, none of them will be registered at Hogwarts. In simpler terms, none of their information will be inserted into the database. You can verify this by checking the rows in the tables.</p><p>Ultimately, our SQL statement adheres to the first principle of A.C.I.D.: ‘All will pass, or none shall pass.’</p><h4>Consistency</h4><p>Another principle of ACID ensures the database moves from one consistent state to another without breaking any defined constraints. Essentially, a transaction shouldn’t make the data invalid or violate any rules set in the database. For instance, if we add a table with a column storing unique values, every row must possess its unique value.</p><p>Otherwise, it could result in a data anomaly within the database or the transaction itself, leading to a failure in upholding the intended business logic accurately.</p><p>However, modern database systems typically offer built-in solutions to enforce this principle. Therefore, it’s uncommon to encounter a transaction violating this principle when there’s a defined constraint in place. Let’s illustrate this with SQL concepts and scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*DSgtyUBuyqkYaug6_OeQPw.jpeg" /></figure><p>Let’s build upon our previous example. After registering at Hogwarts, Harry, Hermione, and Ron will each have their unique identification number. This protocol is crucial within the Hogwarts student management system. However, establishing this mandatory requirement must occur before any student registration. To ensure this, we’ve already applied a primary key constraint to our Wizards table. Let’s revisit our previous example.</p><pre>CREATE TABLE Wizards<br>(<br>    id       BIGINT  NOT NULL,<br>    name     VARCHAR NOT NULL,<br>    surname  VARCHAR NOT NULL,<br>    house_id BIGINT,<br>    CONSTRAINT wizards_primary_key_constraint PRIMARY KEY (id)<br>);</pre><p>Let’s revisit our straightforward transaction example. This time, the official responsible for registering wizards at Hogwarts makes an error and assigns the same identification number to Hermione and Ron. However, let’s assume the official initially registered Harry and Hermione. This time, Ron’s registration occurs in a separate SQL statement, meaning it’s outside of the initial transaction.</p><pre>INSERT INTO Wizards(id, name, surname, house_id)<br>VALUES (2, &#39;Ron&#39;, &#39;Weasley&#39;, null);</pre><p>Because of the primary key constraint set initially, an error will be raised, causing the insert statement for Ron to fail. Ultimately, this preserves the consistency of the database.</p><p><strong><em>Note:</em></strong><em> In PostgreSQL every statement is actually wrapped with</em></p><pre>BEGIN;</pre><p><em>and</em></p><pre>COMMIT;</pre><p><em>implicitly. This makes each particular statement as transactional.</em></p><h4>Isolation</h4><p>Often, a database used in a project is accessed by multiple clients or services, each executing their logic. Sometimes, these services may work on the same table simultaneously. This results in multiple transactions running concurrently. However, this can create scenarios where transactions fetch data from the database inconsistently because they’re not isolated from each other. In simpler terms, they interfere with one another. For instance, one transaction might read a value while another transaction has already processed it, leaving the first transaction with the previous version of the data. There can be various examples of such scenarios. These situations compromise the reliability of the data. To prevent such race conditions, there are approaches designed to isolate transactions from each other.</p><p>In our previous fictional scenario, envision multiple officials at Hogwarts registering new Wizards simultaneously. In technical terms, they’re executing their own database transactions in parallel.</p><p>We’ll dive into the specifics of potential incorrect reads and explain the corresponding isolation level that prevents such mistaken reads.</p><p><strong>Dirty Read: </strong>Imagine one official at Hogwarts is updating the names of the Houses in the database as a transaction.</p><pre>BEGIN;<br><br>UPDATE Houses SET name = &#39;Powerpuff Girls&#39; where id=1;<br>UPDATE Houses SET name = &#39;Avengers&#39; where id=2;<br>UPDATE Houses SET name = &#39;Ninja Turtles&#39; where id=30;<br>UPDATE Houses SET name = &#39;Snow white and other Dwarfs&#39; where id=4;<br><br>COMMIT;</pre><p>Let’s say the first two houses, Gryffindor and Slytherin, were updated to Avengers and Powerpuff Girls within a transaction that hasn’t been committed or completed. Two update statements are still pending. Meanwhile, another official attempts to list the available Houses for Harry. Harry insists on seeing the actual names of the Houses before making a choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*eZJWVjMtf2D7gpOYMBCrig.jpeg" /></figure><p>Initially, the official retrieves data from the Houses table using a simple SELECT query. The result displays four available Houses: Powerpuff Girls, Avengers, Ravenclaw, and Hufflepuff. This occurs because the second transaction reads the uncommitted changes from the first transaction. Ultimately, Harry informs the official of his desire to join the House of Powerpuff Girls, believing it suits his personality. The official then finalizes Harry’s registration with a straightforward insertion statement. Harry’s registration is now complete.</p><p>Keep in mind, the first official is still processing the insertion script concurrently. There’s no assurance that the first transaction will execute successfully as there are pending statements within the transaction.</p><p>Looking at our SQL script again, in the third update statement, Ravenclaw’s identification number is mistakenly written as 30 instead of 3. As there’s no House in the database with the identification number 30, the transaction will fail at this point, triggering a rollback of all uncommitted changes that were previously completed. Consequently, Harry’s House name reverts to Gryffindor. Harry and the official registering him at Hogwarts are unaware of this situation. It’s a pity Harry will eventually discover that he’s not in the Powerpuff Girls house. Poor Harry.</p><p>It’s common for occasional mistakes in SQL execution, but now we face a serious problem. The first transaction failed, so the data remained unchanged in the Houses table. However, the second transaction had already retrieved changes before the first transaction failed, and it will commit Harry’s information into the database.</p><p>The result is inconsistent because Harry was assigned to a house that doesn’t align with his preference or choice.</p><p>This unpleasant situation is called as <strong>Dirty Read</strong>.</p><p>A Dirty Read occurs when a transaction reads uncommitted data from another transaction.</p><p>It’s a scenario that’s highly probable, especially in databases accessed by multiple transactions, and should be considered.</p><p>Our initial isolation level is Read uncommitted, which is the lowest level. In this level, Dirty Reads can occur as it allows transactions to read each other’s uncommitted changes.</p><p>To prevent Dirty Reads, we need to opt for one of the other isolation levels available, such as Read Committed, Repeatable Read, or Serializable.</p><p><strong>Non Repeatable Read: </strong>Let’s say Harry somehow discovered that his House isn’t the Powerpuff Girls, and he’s quite upset about it. He decides to change his House and approaches the official who registered him at Hogwarts, politely requesting a change to a House he prefers. The official, in a transactional manner, checks the available House names for Harry by executing a select statement on the Houses table to gather details about Harry’s House.</p><pre>SELECT * FROM Houses WHERE id=1;</pre><p>Keep in mind, Harry’s house identification number is 1. Upon inspection, they discover that the corresponding House name is Gryffindor, which Harry dislikes, and the official also disapproves of the current name. The official opts to directly change the House name instead of assigning Harry to a different House. Everyone in the House of Gryffindor will be pleased thanks to this decision, as most members dislike the current name. The official promptly begins the paperwork while Harry waits impatiently. Together, they decide to revert the name back to Powerpuff Girls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*7xnuh7Of92VWzDFi8F74Ow.jpeg" /></figure><p>Simultaneously, another official, unaware that Harry and the first official had begun the name-changing process, independently executes an update statement in the database to change Gryffindor to Powerpuff Girls. This action is executed as a transaction and is successful, resulting in committed changes to the database.</p><p>At a certain point, the first official, unsure of whether ‘Gryffindor’ has two ‘f’ letters or one, re-executes the previous select statement to confirm. The result astonishes him. He discovers that Gryffindor has already been changed to Powerpuff Girls. Turning to Harry, he attributes it to a miraculous occurrence — a spontaneous change in the House’s name. However, it’s not a miracle; Harry and the official are merely deluded. In reality, they’ve just experienced a <strong>Non-repeatable Read</strong> error.</p><p>Simply put, it’s an error that occurs when re-reading a row within a transaction yields a different result due to concurrent states of other transactions working on the same row simultaneously.</p><p>This scenario is quite possible. To prevent this, we should select an isolation level that’s higher and safer than Read Uncommitted and Read Committed. Options like Repeatable Read, which specifically prevents non-repeatable reads, or Serializable can be chosen.</p><p><strong>Phantom Read: </strong>As time passes, Harry starts feeling bored with Hermione and Ron. Their friendship is fine, but Harry desires to expand his circle and make new friends, especially within his House. He decides to approach his trusted official, the one who handles all of Harry’s peculiar requests. Harry asks the official to list the wizards in Hogwarts. Following this request, the official executes a simple select query in the Wizards table.</p><pre>SELECT *<br>FROM Wizards<br>WHERE house_id = (SELECT house_id<br>                  FROM Wizards<br>                  WHERE name = &#39;Harry&#39; AND surname = &#39;Pother&#39;);</pre><p>Unfortunately, they discover that the result contains only one wizard, and that’s Harry. This saddens him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*nBPM6w1zkUwfW69b_xEK8g.jpeg" /></figure><p>At the same time, another official registers a new wizard at Hogwarts named Draco Malfoy. Draco specifically requests to be placed in the Powerpuff Girls house because he’s eager to bully Harry. He insists on being in the same House as Harry. The official fulfills his request with an insertion statement, treating it as a transaction.</p><p>Seeing Harry’s disappointment, Harry’s caring official decides to check the database once more, holding onto a glimmer of hope. Perhaps Harry will find a great friendship with another wizard also in the Powerpuff Girls house. In the same transaction, he executes the same select statement once more and is immediately taken aback. There is now one more wizard. Excitedly, he informs Harry about this good news, grumbling about how the database system is so unreliable. However, he’s mistaken. He’s just experienced a <strong>Phantom Read</strong> error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*d1nXvdeFEW_M8QjokN3K5Q.jpeg" /></figure><p>It’s a scenario that occurs quite commonly and is of utmost importance to address, particularly in banking systems, to prevent such reading issues.</p><p>To address this, we need to elevate the isolation level to the highest, which is Serializable.</p><p>That’s an insightful observation! Opting for the highest isolation level seems like the ultimate solution to resolve all read problems. However, it’s not always the case. While it does provide data consistency, it comes at the cost of performance. As you move from the lowest to the highest isolation level, query performance decreases significantly due to concurrent query executions.</p><p>To better understand, review the following figure. It illustrates the read errors associated with different isolation levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*H8efjOnhy24erNTXQZ1qmg.png" /></figure><h4>Durability</h4><p>This final principle ensures that even after a completed transaction, the system’s state remains intact despite power loss, hardware failures, or any issues preventing the proper functioning of the database system. Without this, data corruption or loss might occur.</p><p>Even if Voldemort cut off the electricity at Hogwarts, the data in the database will remain unaffected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G106WWs3VjWUMX1QZ6RCGA.jpeg" /></figure><p>Dear reader, you’ve done really well so far. Thanks to Harry and others, we now have a clear understanding of A.C.I.D. principles. Let’s now delve into Spring’s Transaction Management, building on the background we’ve gained.</p><h3>The Actual Part: Spring’s Transaction Management</h3><p>Transactions are divided into two distinct groups: global and local transactions. This concept applies similarly within Spring’s Transaction Management.</p><h4>Global Transactions</h4><p>In essence, global transactions occur when you perform transactional actions across multiple transactional resources, such as multiple databases or message queues. These global transactions are handled using JTA (Java Transaction API). In this model, an application server oversees the accuracy of transaction execution. It’s important to note that most applications carry out transactions on a single resource.</p><h4>Local Transactions</h4><p>Simply put, local transactions are performed on a single resource. Unlike global transactions, this model doesn’t involve an application server; all transactions occur within the application itself.Although there are other approaches like programmatic transaction management, we are going to continue with declarative transaction management.</p><p>We won’t delve deeply into the various transaction management specifics, but do note that these configurations can be set up using Spring’s Transaction Management.</p><p>It’s also viable to handle global transactions using Spring, but we won’t delve into the specifics here.</p><p>Remember, transaction management is a deep hole which you can dive deeper and deeper.</p><h3>Advantages of Spring’s Transaction Management</h3><p>When we looked at local and global transactions earlier, they revealed certain drawbacks. For instance, changing environments while running your application might demand adjusting numerous configurations.</p><p>Spring’s Transaction Management offers essential mechanisms, enabling you to execute your transactional actions in any environment by handling all mechanisms within Spring itself.</p><p>In declarative transaction management, you simply add annotations to your classes or methods to guarantee transactional execution. It’s a simpler and recommended approach by Spring.</p><p>In essence, with Spring’s Transaction Management System, you don’t have to employ an external transaction manager or configure the transaction manager yourself.</p><h3>Manage Transactions at Service Level</h3><p>We’ll proceed with declarative transaction management, as it’s the recommended method. In Spring, declarative transaction management is achieved through the application of the Proxy Pattern. To grasp the upcoming sections, it’s helpful to have a good understanding of the Proxy Pattern. You can read <a href="https://medium.com/havelsan/spring-framework-beans-full-mode-and-lite-mode-6a16fae20149">one</a> of my articles to acquire that knowledge. Although it’s not solely focused on the Proxy Pattern, reading the related parts will prepare you for the upcoming content. Alternatively, there are numerous resources available online that you can explore.</p><p>There is an annotation called as <strong>@Transactional</strong>.<em> </em>We can use it at class level, method level or on interfaces(since Spring Framework 5.0) to declare a transactional state. Let’s start with interfaces;</p><pre>public interface Service { <br>  <br>  void update(EntityModel entityModel);<br><br>  void deleteById(Long id);<br><br>}</pre><p>Consider a class in the service layer called ‘Service Implementation,’ which implements the preceding interface. We can utilize the <strong>@Transactional</strong> annotation on the interface definition or on a method specified within the interface.</p><pre>@Transactional // Option 1<br>public interface Service { <br>  <br>  @Transactional // Option 2<br>  void update(EntityModel entityModel);<br><br>  void deleteById(Long id);<br><br>}</pre><p>With this approach all methods in the interface or methods in the interface that are annotated by <strong>@Transactional </strong>will be intercepted by the proxy and eventually become transactional.</p><p>On the previous versions of Spring Framework, annotating interfaces with <strong>@Transactional</strong> was not possible. By Spring Framework 5.0, it became applicable. However, this is not the recommended way to make the service layer transactional.</p><p>Java annotations aren’t inherited from interfaces. In cases using AspectJ, these annotations might be disregarded. This situation could lead to non-transactional business logic without your awareness, making it not an ideal choice.</p><p>On the other hand you can use <strong>@Transactional</strong> annotation on class level. Let’s now look at the following code snippet for this scenario;</p><pre>@Service<br>@Transactional<br>public class ServiceImplementation implements Service {<br><br>  // Assume that the implementations are completed.<br><br>  @Override<br>  public void update(EntityModel entityModel) {<br>    // ...<br>  }<br><br>  @Override<br>  public void deleteById(Long id) {<br>    // ...<br>  }<br><br>}<br></pre><p>Here, the class implements all methods in the Service interface, but this time the <strong>@Transactional</strong> annotation is applied at the class level. All methods with public, protected, or package-visible access modifiers are intercepted by the proxy. However, methods coming from the interfaces must use the public access modifier.</p><p>However, if a method is inherited from the parent class(es), it’s necessary to re-declare the method locally with the <strong>@Transactional </strong>annotation to ensure it becomes transactional, even if it’s already annotated in the parent class. While it’s a preferable approach to make the business logic transactional, it’s still not the best approach since you might forget to re-declare inherited methods, assuming they’ll be transactional when they won’t be.</p><p>There is still another option. Let’s see the following code snippet;</p><pre>@Service<br>public class ServiceImplementation implements Service {<br>  <br>  // Assume that the implementations are completed.<br>  <br>  @Transactional<br>  @Override<br>  public void update(EntityModel entityModel) {<br>    // ...<br>  }<br><br>  @Transactional<br>  @Override<br>  public void deleteById(Long id) {<br>    // ...<br>  }<br><br>}</pre><p>This approach is safer, because it is less likely to forget to make a part of the business logic transactional.</p><p>It is still possible to use these approaches in a combination. For example, you can use <strong>@Transactional</strong> at class level and method level at the same time. This creates a default transactional state and you can define a custom state for a particular method.</p><p><strong>Note:</strong> Due to the nature of default proxy approach, invocations within the Service Implementation class(annotated class with <strong>@Transactional</strong>) will not be intercepted by the proxy even if the invoked method is annotated as <strong>@Transactional</strong>.</p><h3>Propagation Levels of Transactions in Spring</h3><p>A transactional action may need to different transaction configurations including scope to be transactional, partial transaction, to be non-transactional, etc. Such states are adjusted with propagation levels.</p><p>Luckily, Spring provides many propagation levels for various transaction scenarios. It is set by a parameter of <strong>@Transactional</strong> annotation named by propagation;</p><pre>@Transactional(propagation = ...)</pre><p>Let’s now go through them one by one;</p><h4>REQUIRED</h4><p>Spring uses this propagation level as default. Within this level Spring check if there is an active transaction. If there is one, then the current action will be in this transaction. If there is no transaction, then Spring will create one for the current action.</p><h4>REQUIRES_NEW</h4><p>If there is an active transaction, Spring suspends it and creates a new one. This is especially meaningful when there are nested actions which requires its own transaction.</p><h4>SUPPORTS</h4><p>This propagation level is similar to REQUIRED propagation level. If there is an active transaction, the current action is going to use it. However, if there is no transaction, the current action will going to be executed as non-transactional.</p><h4>MANDATORY</h4><p>This propagation level is also similar to REQUIRED propagation level. If there is an active transaction, the current action is going to use it. However, if there is none, then it will throw an exception.</p><h4>NEVER</h4><p>As it is understood from the name of the propagation level, any transaction is not allowed. If there is an active transaction, Spring will throw an exception.</p><h4>NOT_SUPPORTED</h4><p>It is similar to NEVER propagation level. Any transaction is again not allowed. However, Spring will handle is silently. If there is an active transaction, it will be suspended and the action will be executed as non-transactional.</p><h4>NESTED</h4><p>With this level, Spring will check if there is an active transaction, and if so, it will put a save point there. If there occurs an exception in the business logic, Spring will rollback the current action to the save point.</p><h3>Isolation Levels of Transactions in Spring</h3><p>Transactions require varying levels of isolation to execute successfully amidst other concurrent transactions. As mentioned earlier, concurrent execution can lead to issues. However, configuring the isolation level in Spring is straightforward — it’s another parameter within the <strong>@Transactional </strong>annotation.</p><pre>@Transactional(isolation = ...)</pre><h4>DEFAULT</h4><p>This is the default isolation level for transactions in Spring. When Spring initiates a transaction, its isolation level aligns with the database’s default isolation level. For instance, PostgreSQL’s default isolation level is READ COMMITTED. It’s important to exercise caution when using this level, as altering the database can lead to complications.</p><p>The rest of the levels remain the same as mentioned previously in the isolation principle section.</p><h3>Best Practices</h3><p>By now, assuming you’ve read through this article, conducted additional research, and hopefully practiced, there are some best practices that I believe are worth mentioning.</p><h4>Nested Transactions</h4><p>At times, you might need to structure your business logic with nested transactions. During such instances, it’s crucial to carefully consider the propagation levels. For instance, you might require a transaction to execute independently, irrespective of the outer transaction. Be mindful of this scenario.</p><h4>Manipulating Entities in Transactions</h4><p>When utilizing JPA for your entities, it’s important to note that if you modify an entity at the Java level — such as invoking one of its setters — and apply the <strong>@Transactional</strong> annotation to your method, explicit saving isn’t necessary. Your transaction handles the persistence for you. This is a fundamental principle of JPA: any changes made to your entity within a transactional operation will be automatically persisted.</p><p>However, if you opt for persistence technologies other than JPA, remember to include save statements in your code to ensure proper persistence.</p><h4>Suppressing Exceptions in the Transaction</h4><p>Consider a scenario where you have nested transactions within your business logic. You invoke another method from a different service, which might throw an exception. If you configure your current service’s method to rollback specifically for that exception and wrap the invocation of the outer service’s method in a try-catch block within the current service method, it won’t trigger a rollback on the current service’s method. Exercise caution with this approach and try to minimize the use of try-catch blocks where possible.</p><h3>Conclusion</h3><p>We’ve covered quite a bit, and I hope Spring’s transaction management is clearer now.</p><p>Remember, there are numerous other resources available online. Feel free to explore those as well.</p><p>As always thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae30b8e6c5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/havelsan/database-transactions-and-springs-way-of-managing-them-1ae30b8e6c5c">Database Transactions and Spring’s Way of Managing Them</a> was originally published in <a href="https://medium.com/havelsan">HAVELSAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Best Friend of equals() method: hashCode()]]></title>
            <link>https://medium.com/havelsan/the-best-friend-of-equals-method-hashcode-79a8a352da15?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a8a352da15</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 18:53:06 GMT</pubDate>
            <atom:updated>2023-12-14T13:33:20.646Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>hashCode()</strong> and <strong>equals()</strong> methods in Java Programming have a mutual contract and they also can’t function independently of one another; they are <strong>interdependent</strong>. This symbiotic relationship defines the core necessity for their concurrent and harmonious implementation within class definitions, as they serve complementary roles in object comparisons and hash-based data structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*NDRRA5MZQUX_HQ3smx_HDA.png" /></figure><p>Indeed, the <strong>hashCode() </strong>and <strong>equals()</strong> methods are regarded as inseparable companions within a class definition. Their joint presence in a class is pivotal for averting numerous bugs or errors that could be challenging to detect and rectify. The collaborative existence of both methods ensures a comprehensive and accurate handling of object comparisons and hash-based data structures, contributing significantly to the reliability and integrity of the codebase.</p><p>In this article, we’ll dive into the specifics of the <strong>hashCode()</strong> method within the Java programming language. To commence, we’ll lay the foundation by exploring fundamental definitions integral to understanding this topic. It’s essential to reinforce these definitions with more intricate and critical concepts.</p><p>Subsequently, we’ll dive into the application of the hashing mechanism in Java and dissect the details surrounding the <strong>hashCode()</strong> method, unveiling how it operates within the Java runtime environment. Finally, we’ll explore the inseparable connection between the <strong>equals()</strong> and <strong>hashCode()</strong> methods. This exploration will involve understanding specific data structures and elucidate how these methods coordinate and complement each other within these structures.</p><p>It seems there’s a strong interconnection between the concepts discussed in this article and the “<strong>equals()</strong> method” in Java programming. Understanding the “equals() method” is crucial for comprehending the content covered in <a href="https://medium.com/@mr-yakar/how-to-write-equals-in-java-5e9a908045a1"><strong>this</strong></a> article. If you’re not well-versed in the “equals() method,” I’d recommend pausing here and familiarizing yourself with that content first. It will significantly enhance your understanding of the topics discussed herein due to their close correlation.</p><p>Let’s start with the introduction by giving some definitions.</p><h3>What is Hashing?</h3><p>In simple terms, hashing is the process of transforming a set of data into an alternative form. Essentially, it involves converting a value into another value. The resulting converted value is irreversible and commonly referred to as a “hash.”</p><h3>What is Hash Function?</h3><p>According to <a href="https://en.wikipedia.org/wiki/Hash_function">Wikipedia</a>;</p><blockquote>A hash function is any function that can be used to map data of arbitrary size to fixed-size values.</blockquote><p>In essence, a hash function is designed to produce a converted value of a fixed size utilizing one of the mathematical hashing algorithms. Moreover, there exist specific algorithms that can generate converted values of variable sizes.</p><p>Consider the following function ‘h’ as an example of a hash function:</p><blockquote>h(k) = k (mod 10)</blockquote><p>Since <em>k</em> represents for key, the following hashes are generated;</p><blockquote>h(1) = 1</blockquote><blockquote>h(12) = 2</blockquote><blockquote>h(896543) = 3</blockquote><p>Certainly, various mathematical algorithms are employed for data conversions. However, if a method allows the converted data to be restored back to its original form straightforwardly, it does not align with the principles of hashing; rather, it falls under the category of encoding/decoding, which may be a separate topic of discussion.</p><p>Similarly, if a unique key is used for data conversion and another key, whether the same or different, is required to revert the data to its original state, this process is recognized as encryption/decryption. These concepts diverge from the fundamental properties of hashing and might be explored in a separate article.</p><p>A hash function operates using a <strong>one-way</strong> algorithm, meaning data is transformed <strong>irreversibly</strong> into another form. This irreversible transformation prohibits the retrieval of the original data. In the earlier mentioned function ‘h,’ the modulo operation in mathematics, for instance, is an irreversible process. For instance, both 12 mod 10 and 22 mod 10 result in 2, which indicates that distinct values such as 12 and 22 cannot be uniquely obtained from the output.</p><p>However, the generation of identical results for different keys poses a significant issue in hashing, referred to as hash collision. The details regarding collision will be elaborated in one of the upcoming sections.</p><p>The quality and suitability of a hashing algorithm hinge on several critical properties, including the ability to produce unique results, irreversibility, and swift calculation of the hash. These properties are pivotal in determining the effectiveness and reliability of a mathematical conversion algorithm employed for hashing purposes.</p><p>Indeed, hashing provides numerous benefits and is extensively employed across various domains such as mathematics, data security, electronic communication, and more. Each of these fields leverages hashing techniques according to their specific requirements.</p><p>In computer science, hashing is prominently utilized in tandem with data structures, particularly in hash tables. Exploring the intricacies of the hash table data structure will shed light on how hashing is applied and its significance within the realm of computer science.</p><h3>What is Hash Table?</h3><p>According to <a href="https://en.wikipedia.org/wiki/Hash_table">Wikipedia;</a></p><blockquote>In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.</blockquote><p>In short, a hash table comprises keys in their hashed forms and corresponding values. Let’s examine the following example of a hash table as described on Wikipedia:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*tKyXdlZo6yhajQR57kYBOg.png" /><figcaption>A small phone book as a hash table</figcaption></figure><p>As evident from the description, the individual’s full name is processed by the hash function to generate the output, which is utilized as the key within the hash table. Meanwhile, the person’s phone number is stored as the corresponding value. One of the primary advantages of a hash table is that the time complexity for search, insertion, and deletion operations is O(1), signifying nearly instant processing.</p><h3>What is Hash Collusion?</h3><p>Returning to the initial example provided at the beginning of the article, the hash function, denoted as ‘h,’ essentially computes the hash by determining the modulus of the key divided by 10.</p><blockquote>h(k) = k (mod 10)</blockquote><p>In this context, the value of 10 represents the size of the table. This specification ensures that the hash generated always falls within the boundaries defined by the table size.</p><p>Let’s examine the basic definition of a hash as per Wikipedia. A hash function takes inputs of arbitrary sizes and produces an output of a fixed size. This fixed output size corresponds to the size of the table, which sets a limit on the memory available for storing values in the table. Consequently, it’s feasible for different inputs to yield the same hash value. Here’s an example to illustrate this concept:</p><blockquote>h(1) = 1</blockquote><blockquote>h(121) = 1</blockquote><blockquote>h(1653552771) = 1</blockquote><p>The observation indicates that the hash function, denoted as ‘h,’ generates the same hash result for different key values. This occurrence arises from the characteristics of the hash function and the size of the hash table being set to 10. This phenomenon is commonly referred to as a “<strong>hash collision</strong>.” Hash collisions pose significant challenges, impacting both security and performance aspects.</p><p>The scenario described involves a login page for a website where user passwords are stored as hash values, making it difficult for anyone to access the original plain text passwords due to the irreversible nature of hash functions. However, if the hash function is poorly designed, it becomes susceptible to exploitation by malicious individuals. In such a case, a malicious actor could potentially take advantage of vulnerabilities within the hash function to create hash collisions.</p><p>By generating these collisions, an attacker could attempt to log in to the website using someone else’s account. With a poorly designed hash function, creating collisions becomes relatively easy. Furthermore, in some instances, an attacker might even attempt to crack the original password directly through brute-force attacks, leveraging weaknesses in the hash function’s design.</p><p>This scenario underscores the critical importance of using robust, well-designed hash functions in securing sensitive information like user passwords. A well-designed hash function significantly mitigates the risk of malicious exploitation and unauthorized access to user accounts.</p><p>In cases with minimal or no hash collisions, the search operation within these arrays is fast, even if the search operation is theoretically <strong>O(n)</strong>, since the arrays are relatively small. However, as the number of collisions increases, leading to fewer distinct hash values and more substantial associative arrays, the time complexity for finding the correct key-value pair can shift from an efficient <strong>O(1)</strong> to a less efficient <strong>O(n)</strong>. This becomes particularly problematic with a large amount of data.</p><p>There is a mention of an intriguing mathematical approach aimed at uniformly distributing collisions across associative arrays to optimize hash function performance. However, this concept will be covered in a separate article.</p><p>Probability of occurrence differs from algorithm to another. Let’s get into the some basic information;</p><p><a href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check"><strong>CRC-32:</strong></a><strong> </strong>It has the highest risk for hash collisions. If there are already 77163 hash values, then the probability of a hash collision is %50 which is extremely high compared to the other algorithms.</p><p><a href="https://en.wikipedia.org/wiki/MD5"><strong>MD5:</strong></a><strong> </strong>It is most commonly used hash algorithm. If there are already 5.06 billion hash values, then the chance of having a hash collision is %50 which is moderately better than CRC-32.</p><p><a href="https://en.wikipedia.org/wiki/SHA-1"><strong>SHA-1:</strong></a><strong> </strong>It offers the lowest risk of hash collision in between these three algorithms. For SHA-1 algorithm, to reach the hash collision risk of %50 there must be already 1.42 × 10²⁴ hash values.</p><p>Let’s continue with hashing in terms of Java.</p><h3>Hash Function in Java</h3><p>Given the coverage of the hashing mechanism and some potential hash algorithms, the following section will directly focus on the hashing mechanism in the Java programming language.</p><p>In the Java programming language, the hashing mechanism is facilitated by a method named <strong>hashCode()</strong>, which is a part of the <strong>java.lang.Object</strong> class. Before diving into the specifics of how to use this method, let’s explore some details regarding its actual implementation.</p><p>The hash function in Java is <strong>dependent</strong> on the <strong>Java Virtual Machine (JVM)</strong> it runs on. This implies that one JVM can calculate one value while another JVM can calculate a different value. The reason behind this is straightforward: the <strong>hashCode()</strong> method is actually a native method, written in a language other than Java. This function is provided by internal libraries within the JVM, and these libraries may differ from one JVM to another. If you wish to examine the actual method signature of the <strong>hashCode()</strong> method in <strong>java.lang.Object</strong>, refer to the following code snippet:</p><pre>public native int hashCode();</pre><p>This code snippet showcases the signature of the <strong>hashCode()</strong> method in the <strong>java.lang.Object</strong> class, indicating its native implementation.</p><p>In the Java Programming Language, the term “native” is a reserved word utilized when integrating functions from an external library not written in Java. As the actual implementation may vary across different Java Virtual Machines (JVMs), the intricate details of these potential implementations will be omitted in this article, warranting its individual discussion.</p><p>The following section is essential and cannot be skipped, as it directly concerns the topic of this article. The <strong>hashCode()</strong> method adheres to a specific contract.</p><h4>The Consistency of the Hash Value</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tP7ZAb9PMdSxuFNLf5yx9Q.jpeg" /></figure><p>The official documentation specifies that the <strong>hashCode()</strong> method must consistently return the same integer as the hash value as long as invocations are made on the same object during the current execution of the application. Let’s consider an already implemented class named ‘Pencil.’ Imagine that we run the program, create an object from the ‘Pencil’ class, and subsequently execute the <strong>hashCode()</strong> method twice on the object, as follows:</p><pre>Pencil a = new Pencil();</pre><pre>int firstHashCodeCalculation = a.hashCode();<br>int secondHashCodeCalculation = a.hashCode();</pre><pre>boolean same = firstHashCodeCalculation == secondHashCodeCalculation;</pre><p>The variable ‘same,’ as defined last, must have the value ‘true’ in compliance with the first principle of the <strong>hashCode()</strong> contract. This principle is exceptionally crucial as it dictates the exclusion of any inconsistent variables in our implementation of the <strong>hashCode()</strong> method. For instance, it is ill-advised to include a value from <strong>java.util.Random</strong>. Similarly, adding a variable from <strong>java.util.Date</strong> in the calculation of hash value is an example of an incorrect implementation, as it could generate constantly changing values.</p><h4>Consistency of equals() and hashCode() Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*S6dSHlWRQFLqks-AEBPqlw.jpeg" /></figure><p>The second principle of the <strong>hashCode()</strong> contract stipulates that if two objects are considered equal according to the <strong>equals()</strong> method, their hash values must also be identical. This aspect relies on the quality of the implementation of our <strong>hashCode()</strong> method. Achieving this involves employing the same properties in both the <strong>hashCode()</strong> and <strong>equals()</strong> methods. Any alteration in properties that are not utilized will not lead to a different outcome in the <strong>hashCode()</strong> or <strong>equals()</strong> method.</p><p>The crux of this principle lies in the utilization of hash-based collections. Let’s now revisit our hypothetical class ‘Pencil.’ In this scenario, let’s assume it possesses three distinct properties: ‘brand,’ ‘color,’ and ‘size.’ All these properties are included in the <strong>equals() </strong>method, but we haven’t provided an implementation for the <strong>hashCode()</strong> method. In other words, none of the properties utilized in the <strong>equals()</strong> method have been used. Below is the following code snippet:</p><pre>Pencil a = new Pencil(&quot;Rotring&quot;, &quot;Black&quot;, 0.5);<br>Pencil b = new Pencil(&quot;Faber Castell&quot;, &quot;Black&quot;, 0.5);<br>Pencil c = new Pencil(&quot;Faber Castell&quot;, &quot;Red&quot;, 1.0);<br><br>Map&lt;Pencil, Integer&gt; pencilPriceMap = new HashMap&lt;&gt;();<br>pencilPriceMap.put(a, 100);<br>pencilPriceMap.put(b, 120);<br>pencilPriceMap.put(c, 150);<br><br><br>int price = pencilPriceMap.get(new Pencil(&quot;Rotring&quot;, &quot;Black&quot;, 0.5));</pre><p>We might assume the price will be 100, but it won’t be the case. This is where we encounter issues. If we intend to utilize objects of the Pencil class as keys in a hash map, we must override the <strong>hashCode()</strong> method and employ the same properties as those used in the <strong>equals()</strong> method.</p><h4>A Performance Criterion of hashCode() Method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*_9V_LwEX-auKwg1yZscljg.jpeg" /></figure><p>The last principle states that resulting hash codes do not have to be different when two objects are not equal according to the <strong>equals()</strong> method of the corresponding class. However, it is better for them to be different due to performance concerns.</p><p>At the start of this article, we provided information about how hash collisions occur. We encounter a similar situation here. Once again, let’s revisit our hypothetical class, ‘pencil.’ It possesses the same properties as in the previous principle, but this time, its <strong>hashCode()</strong> method consistently computes the same hash for all distinct or equal objects. Below is the following code snippet to demonstrate this:</p><pre>Pencil a = new Pencil(&quot;Rotring&quot;, &quot;Black&quot;, 0.5);<br>Pencil b = new Pencil(&quot;Faber Castell&quot;, &quot;Black&quot;, 0.5);<br>Pencil c = new Pencil(&quot;Faber Castell&quot;, &quot;Red&quot;, 1.0);<br><br>Map&lt;Pencil, Integer&gt; pencilPriceMap = new HashMap&lt;&gt;();<br>pencilPriceMap.put(a, 100);<br>pencilPriceMap.put(b, 120);<br>pencilPriceMap.put(c, 150);<br><br>pencilPriceMap.get(new Pencil(&quot;Rotring&quot;, &quot;Black&quot;, 0.5));</pre><p>Since all objects’ keys are the same and they are added to the same bucket, given that the hash map’s key is derived from the object’s hash code, the time complexity of a get operation shifts from <strong>O(1)</strong> to <strong>O(n)</strong>, essentially rendering our map into a list. This results in a significant performance loss.</p><p>It does not affect the runtime logic, but it does impact the performance. To benefit from using a hash table, it is evident that we must provide an implementation of <strong>hashCode()</strong> that does not violate the third principle of the <strong>hashCode()</strong> contract.</p><h3>In Conclusion</h3><p>As it is obvious, the <strong>hashCode()</strong> and <strong>equals()</strong> methods form an inseparable duo and must be taken very seriously when implementing your code. There are numerous sources available on the web, and I recommend not only relying on this article but also exploring other sources.</p><p>As always, thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a8a352da15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/havelsan/the-best-friend-of-equals-method-hashcode-79a8a352da15">The Best Friend of equals() method: hashCode()</a> was originally published in <a href="https://medium.com/havelsan">HAVELSAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write equals() in Java]]></title>
            <link>https://medium.com/havelsan/how-to-write-equals-in-java-5e9a908045a1?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9a908045a1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[equality]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 13:58:17 GMT</pubDate>
            <atom:updated>2023-12-14T13:33:16.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An amazed boy with the result of equals method" src="https://cdn-images-1.medium.com/max/600/1*9vs1MXBtyHVWFmdXHlNOBA.jpeg" /></figure><p>By the end of this article, all required information is going to be covered to be able to write the best equals() method in Java programming language. The details of equality are going to be dealt with in terms of mathematical definition and in the manner of Java programming language in order to cover the fundamental information that is needed to use the best practice of <strong><em>equals()</em></strong> method.</p><h3>Mathematical Definition of Equality</h3><p>According to <a href="https://en.wikipedia.org/wiki/Equality_(mathematics)#:~:text=In%20mathematics%2C%20equality%20is%20a,and%20pronounced%20A%20equals%20B.">Wikipedia</a>, the definition of mathematical equality is</p><blockquote>In mathematics, equality is a relationship between two quantities or, more generally two mathematical expressions, asserting that the quantities have the same value, or that the expressions represent the same mathematical object. The equality between <em>A</em> and <em>B</em> is written <em>A</em> = <em>B</em>, and pronounced <em>A</em> equals <em>B</em>.</blockquote><h3><strong>Definition of Equality in Java</strong></h3><p>In Java programming language, equality means simply having the same value. It is sometimes literally meant to have the same value and sometimes meant to have the same structure in terms of the properties of the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3S3ux2oXv-afvWC5Y3k0Q.png" /></figure><p>When it is needed to check the equality of two primitive type values, equals sign is directly used as in the example below;</p><pre>int a = 5;<br>int b = 6;<br>int c = 5;<br><br>// Prints &quot;false&quot; since a and b do not have the same value.<br>System.out.println(a == b);<br><br>// Prints &quot;true&quot; since a and c have the same value.<br>System.out.println(a == c);</pre><p>In this code snippet, an integer primitive type is used. However, it is the same for other primitive types.</p><p>On the other hand, it is sometimes needed to check the equality of two objects. In terms of objects, there are two different approaches that are used in different stages of process of checking of the equality of two objects. Let’s get into the details.</p><h4>Referential Equality</h4><p>In Java programming language, the objects’ actual values are stored somewhere in the memory and they are pointed by the object references which are also stored somewhere in the memory. Let’s look at the following code snippet;</p><pre>// Create an object with &quot;new&quot; operator.<br>// Point to object with object reference &quot;a&quot;.<br>Object a = new Object();<br><br>// Create another object reference.<br>// Point to the same object as the reference &quot;a&quot; is pointing.<br>Object b = a;<br><br>// Output is true.<br>System.out.println(a == b);<br><br>// Create another object with &quot;new&quot; operator.<br>// Point to object with object reference &quot;b&quot;.<br>b = new Object();<br><br>// Output is false.<br>System.out.println(a == b);</pre><p>In Java programming language, “new” operator creates an object and returns a reference which points the actual memory location of the object. Many object references which point to the same object may be created at runtime. In terms of referential equality, it is checked whether two object references are pointing to the same memory location or not.</p><p>In such a scenario, “a” and “b” are actually two references that are pointing to the same object, so it can be directly said that “a” is equal to “b” since the referential equality is obtained.</p><p>However, the opposite scenario is not valid all the time. Two different references may point different memory locations, but the objects that the references point may still be equal.</p><p>In normal life, sometimes quantities are compared. Like if you have two apples and your friend has two apples then the number of apples you and your friend has is equal.</p><p>On the other hand, sometimes things may also be compared in terms of its properties or structure. Let’s get into the details for this scenario.</p><h4>Structural Equality</h4><p>Structural equality is the type of which the objects are compared according to states of their properties. A more sophisticated tool is needed to check this type of equality rather than only “==” operator. It is the equals() method. It comes from the Object class which is at the highest point of the class hierarchy in Java programming language. Let’s check the upcoming Java code snippet;</p><pre>public class Car {<br><br>    // Assume that we have corresponding constructor, accessors, mutators, etc.<br><br>    private String brand;<br>    private String model;<br>    private Integer modelYear;<br>    private Integer mileage;<br>    <br>}</pre><p>Let’s assume that two cars are equal if their brands, models and model years are same. We have an assumption here, because it is always the actual case. This type of equality is not about the quantity but the identity. So we create a definition for identity. If we have two same identities, we can say they are identical or equal. Let’s continue with the up coming code snippet;</p><pre>Car car1 = new Car(&quot;Audi&quot;,&quot;R8&quot;, 2023);<br>Car car2 = new Car(&quot;Audi&quot;,&quot;R8&quot;, 2023);<br>Car car3 = new Car(&quot;Audi&quot;,&quot;R8&quot;, 2021);<br><br>System.out.println(car1.equals(car2));<br>System.out.println(car2.equals(car3));</pre><p>What do you expect to see in the output? If you think that you would see true for the first line and false in the second line then you are wrong. Let’s look at the <strong><em>equals()</em></strong> method in the Object class since the equals method of the Car class has not been implemented, yet. So we end up with the <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)"><strong><em>equals()</em></strong></a> method of Object class;</p><pre>public boolean equals(Object obj) {<br>    return (this == obj);<br>}</pre><p>Only the referential equality is checked here which is totally expected, because there must be different identities for different classes. Object class represents the top point on the hierarchy of all objects in Java. The mutual point of all types of objects in Java is the references of them. That is why it is totally normal to check only the referential equality in the <strong><em>equals()</em></strong> method of the Object class. To specify the identity of a child class, we must create an identity for it. In other words we must override the equals() method in Object class and determine how two objects of the class can be equal. Let’s extend the Car class by overriding the equals() method;</p><pre>public class Car {<br><br>    private String brand;<br>    private String model;<br>    private Integer modelYear;<br>    private Integer mileage;<br><br>    // Assume that we have corresponding constructor, accessors, mutators, etc.<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Car car = (Car) o; <br>        return brand.equals(car.brand) &amp;&amp; model.equals(car.model) &amp;&amp; modelYear.equals(car.modelYear);<br>    }<br>    <br>}</pre><p>On the first line of the method, the referential equality is checked. Since the two different object references point to the same object, they are equal. If this is not the case, in other words if we have two different references which do not point to the same object, it is time to start checking the identity of the these two objects.</p><p>On the second line we start to check the identity of the objects. If the object reference <em>o</em> is null or the both object references point to the objects which belong different classes, then it can be directly said that these two objects do not have the same identity and are not equal. If this is not the case then we are finally able to check the actual structures of the objects.</p><p>On the third line of the method, we cast the reference <em>o</em> to the corresponding class type since the method is overridden from Object class and now we know that it belongs to Car class.</p><p>Finally, on the last line of the method, the structure of two objects are checked and this is the actual line that the identity is defined. Simply, if brands models and model years are the same then these two objects are equal. On the other words, this is the structural equality.</p><p>We have learned the properties of mathematical equality at the elementary school. Some of these properties have to be valid for <strong><em>equals()</em></strong> method, too. It means that these properties have to be added to the ingredients of the <strong><em>equals()</em></strong> method. Let’s see these properties in terms of mathematical equality and in terms of equality in Java;</p><h4>Reflexive Property</h4><p>In the mathematical definition of reflexive property, for all real numbers <strong>x</strong>;</p><blockquote><strong>x = x</strong></blockquote><p>A number equals itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IHMRqOD8US-kFq6JZizqA.jpeg" /></figure><p>In terms of Java equality, an object has to equals itself;</p><pre>Car car1 = new Car(&quot;Audi&quot;,&quot;R8&quot;,2013);<br>System.out.println(car1.equals(car1));</pre><p>Let’s assume that the <strong><em>equals()</em></strong> method is written accidentally or purposefully like in the up coming code snippet;</p><pre>@Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Car car = (Car) o; <br>        return mileage &lt; car.mileage &amp;&amp; brand.equals(car.brand) &amp;&amp; model.equals(car.model) &amp;&amp; modelYear.equals(car.modelYear);<br>    }</pre><p>This implementation of <strong><em>equals()</em></strong> method violates the reflexive property apparently. Mileage of the object cannot be smaller than itself.</p><h4>Symmetric Property</h4><p>In terms of mathematical definition of symmetric property, for all real numbers <strong>x</strong> and <strong>y</strong>;</p><blockquote>If <strong>x =</strong> <strong>y</strong> , then <strong>y =</strong> <strong>x</strong></blockquote><p>Order of equality does not matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4Yp41WPCRQDi-co0wyoLA.jpeg" /></figure><p>In terms of Java equality, if object a equals object b, then object b has to equal object a;</p><pre>Car car1 = new Car(&quot;Audi&quot;,&quot;R8&quot;,2013);<br>Car car2 = new Car(&quot;Audi&quot;,&quot;R8&quot;,2013);<br>System.out.println(car1.equals(car2));<br>System.out.println(car2.equals(car1));</pre><p>For the above code snippet, we must see two consecutive trues since the <strong><em>equals()</em></strong> method has to follow the symmetric property. Despite all, let’s assume that we have implemented <strong><em>equals()</em></strong> method like in the up coming code snippets;</p><pre>public class Car {<br><br>    private String brand;<br>    private String model;<br>    private Integer modelYear;<br>    private Integer mileage;<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (o == this) return true;<br>        if (!(o instanceof Car)) return false;<br>        Car car = (Car) o;<br>        return brand.equals(car.brand) &amp;&amp; model.equals(car.model) &amp;&amp; modelYear.equals(car.modelYear);<br>    }<br>}<br></pre><p>And we have another class extends to Car class;</p><pre>public class SportCar extends Car {<br>    <br>    private String engineType;<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (o == this) return true;<br>        if (!(o instanceof SportCar)) return false;<br>        SportCar sportCar = (SportCar) o;<br>        return engineType.equals(sportCar.engineType);<br>    }<br>}</pre><p>With these classes, let’s suppose that we have the code snippet below;</p><pre>Car car1 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br>SportCar car2 = new SportCar(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000, &quot;4.0&quot;);<br>System.out.println(car1.equals(car2));<br>System.out.println(car2.equals(car1));</pre><p>The first line of output is going to be true that actually car1 is equal to car 2. According to symmetric property, the second output also must be true but it is false due to the incorrect implementation of <strong><em>equals()</em></strong> methods. This is one of the examples that violates the symmetric property. Also, it is better to <strong><em>avoid using inheritance</em></strong> in <strong><em>equals()</em></strong> method implementations since it is very hard to come up a correct implementation that follow this property.</p><h4>Transitive Property</h4><p>In the mathematical definition of transitive property, for all real numbers <strong>x</strong>, <strong>y</strong>, and <strong>z</strong>;</p><blockquote>if <strong>x = y</strong> and <strong>y = z</strong>, then <strong>x = z</strong></blockquote><p>Two numbers equal to the same number are equal to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKf7y0CNGR6CJnnlK5BA7w.jpeg" /></figure><p>In terms of Java equality, if object a equals object b and object b equals object c, then object a has to be equal to object c;</p><pre>SportCar car1 = new SportCar(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000, new Turbo(&quot;100RPM&quot;));<br>Car car2 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br>SportCar car3 = new SportCar(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000, new Turbo(&quot;101RPM&quot;));<br>System.out.println(car1.equals(car2));<br>System.out.println(car2.equals(car3));<br>System.out.println(car1.equals(car3));</pre><p>For the above code snippet, we must see three consecutive trues since the <strong><em>equals()</em></strong> method has to follow the transitive property. Let’s assume that something really went wrong and we implemented below <strong><em>equals()</em></strong> method for SportCar class;</p><pre>public class SportCar extends Car {<br>    <br>    private Turbo turbo;<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (!(o instanceof Car)) return false;<br>        if (!(o instanceof SportCar)) return o.equals(this);<br>        return super.equals(o) &amp;&amp; ((SportCar) o).turbo == turbo;<br>    }<br>}</pre><p>Also we have an additional Turbo class;</p><pre>public class Turbo {<br>    private String power;<br><br>    public Turbo(String power) {<br>        this.power = power;<br>    }<br>}</pre><p>Now let’s return to below code snippet;</p><pre>SportCar car1 = new SportCar(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000, new Turbo(&quot;100RPM&quot;));<br>Car car2 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br>SportCar car3 = new SportCar(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000, new Turbo(&quot;101RPM&quot;));<br>System.out.println(car1.equals(car2));<br>System.out.println(car2.equals(car3));<br>System.out.println(car1.equals(car3));</pre><p>At the end of the execution, on the first line we are going to see true since according to SportCar class <strong><em>equals()</em></strong> implementation car1 is equal to car2. On the second line we are also going to see true as output, because car2 is also equal to car3. However, on the last line we are going to see false as the output. Since the turbo powers are different and in the SportCar’s <strong><em>equals()</em></strong> method implementation it is also added to the calculation. As we see again, it is a good practice to <strong><em>avoid inheritance applications</em></strong> in equality mechanisms of classes. Even if there is an inheritance relation between two objects of different classes, treat them as totally different objects in terms of equality definition.</p><h4><em>Consistent </em>Property</h4><p>This is a different property since there is no exact equivalent mathematically. For this one we need to get the same result for consecutive executions of equals() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nwIrPBXjdUJtotMOj6g4Q.jpeg" /></figure><p>Let’s look the below code snippet;</p><pre>Car car1 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br>Car car2 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br><br>for (int i = 0; i &lt; 100000; i++) {<br>    System.out.println(car1.equals(car2));<br>}</pre><p>We expect to see only trues or false in the output. Let’s suppose that there is a scenario that a random integer is used in the calculation of equality. Look at the below code snippet;</p><pre>@Override<br>public boolean equals(Object o) {<br>    if (o == this) return true;<br>    if (!(o instanceof Car)) return false;<br>    Car car = (Car) o;<br>    Random random = new Random();<br>    return brand.equals(car.brand) &amp;&amp; model.equals(car.model) &amp;&amp; (random.nextInt(10) + 2013) == car.modelYear;<br>}</pre><p>Under these circumstances we cannot expect it to give consistent results from multiple invocations. So it is a good practice to avoid using any random value mechanism in equals() method.</p><p><strong>Note: </strong>This example does not really satisfy me. After an extensive research, I will replace it with a better one. It is clearly said in the Java documentation of equals() method that <em>“multiple invocations of </em><em>x.equals(y) consistently return </em><em>true or consistently return </em><em>false”.</em><strong><em> </em></strong>There must be a solid example of violation for this statement.</p><h4>Null Parameter Property</h4><p>This is how I choose to call this property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoyPqiu0nAQD1glLOa1EjQ.jpeg" /></figure><p>Please look at the below code snippet;</p><pre>Car car1 = new Car(&quot;Audi&quot;, &quot;R8&quot;, 2012, 1000);<br>Car car2 = null;<br>System.out.println(car1.equals(car2));</pre><p>We always expect <strong><em>equals()</em></strong> method to return false as the result when the parameter is null, so it is a good idea to apply this property in every possible implementation of equals method.</p><p>Now it is clear which properties an equals() method implementation should have in order to provide a correct calculation of the equality. Also, we have seen the possible violation scenarios, so we can now avoid them for the sake of the code quality and business logic.</p><p>Today many IDEs provide generation mechanisms to generate the best possible <strong><em>equals()</em></strong> method implementations. It is a good idea to stick with them most of the time instead of implementing the <strong><em>equals()</em></strong> method. Let’s see an example from <a href="https://www.jetbrains.com/idea/">Intellij IDEA</a>;</p><pre>  @Override<br>   public boolean equals(Object o) {<br>       if (this == o) return true;<br>       if (o == null || getClass() != o.getClass()) return false;<br>       Car car = (Car) o;<br>       return brand.equals(car.brand) &amp;&amp; model.equals(car.model) &amp;&amp; modelYear.equals(car.modelYear) &amp;&amp; mileage.equals(car.mileage);<br>   }</pre><p>Let’s assume that all properties of car class are not null.</p><p>On the first line, the referential equality is checked, because two object references may point to the same object.</p><p>On the second line, the validation of <strong><em>Null Parameter Property</em></strong> is ensured and also the same if condition acts as a <strong><em>guard if clause</em></strong> by controlling the class type of the objects that are pointed out by references in order to prevent violation of <strong><em>Transitive Property</em></strong> and <strong><em>Symmetric Property.</em></strong></p><p>On the third line, the object reference is cast into the corresponding class type which is Car in our example in order to reach the properties of the Car object.</p><p>Finally, on the fourth line the equality is checked in terms of the structural equality.</p><p>There are other templates for <strong><em>equals()</em></strong> method generation. You can also go and check them.</p><p>If you would like to write the implementation on your own, please keep in mind that the implementation must ensure validity for all <strong><em>equals()</em></strong> method property.</p><p>As we come to the end of the article, there is still a very important gap that needs to be covered. Open your IDE and try to generate <strong><em>equals()</em></strong> method. You are going to see that there is no option to only generate <strong><em>equals()</em></strong> method without <strong><em>hashCode()</em></strong> method. Due to the some collection types in Java programming language, it is a very good practice not to separate these two methods from each other. It is also said in the official Java documentation that it is generally necessary to override the <strong><em>hashCode()</em></strong> method whenever the <strong><em>equals()</em></strong> method is overridden. I would like to give corresponding information about hashing and <strong><em>hashCode()</em></strong> method in other article of mine.</p><p>Also, sometimes we may need not to stick with the <strong><em>equals()</em></strong> method properties for some exceptional cases like entity classes of JPA. It also deserves its own article.</p><h4>In Conclusion</h4><p>All the important points for implementing the correct <strong><em>equals()</em></strong> method are covered in this article. I also recommend you to write the corresponding unit tests to test the validation of <strong><em>equals()</em></strong> method properties. Do not forget to look at the other resources that can be founded on the web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGmAafHoWnxBq-F1sMxMCA.jpeg" /></figure><p>On the first place, it seems like a very easy and primitive topic since it is from the fundamentals of object oriented design. However, as it is seen from the details that it is very important not to skip these basic concepts and fully understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9a908045a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/havelsan/how-to-write-equals-in-java-5e9a908045a1">How to Write equals() in Java</a> was originally published in <a href="https://medium.com/havelsan">HAVELSAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Private Methods!]]></title>
            <link>https://medium.com/havelsan/testing-private-methods-afbda842d44a?source=rss-ef7b7e79da5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/afbda842d44a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Ahmet Yakar]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 11:36:07 GMT</pubDate>
            <atom:updated>2023-12-14T13:32:54.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oW0kDwi36Ng7JMvT1b9EXg.jpeg" /><figcaption>Image credit: Marc Moreno on <a href="https://bugfender.com/blog/how-to-write-unit-tests-for-kotlin/">BugFender</a>.</figcaption></figure><p>In object oriented design, naturally the objects are interacting each other which makes them clients of each other, indeed. Actually, just after this, the very first clients of an object are the <a href="https://en.wikipedia.org/wiki/Unit_testing">unit tests</a>.</p><p>The all <strong><em>public</em></strong> functionalities of the object are used by unit tests for testing purposes like a real client in the production environment is using these functionalities for the sake of its business. As it is supposed to be, the internal functionalities may not be served to the clients because they are irrelevant to them. So according to this point of view, private methods <strong><em>must be primitively simple</em></strong> or <strong><em>must not need </em></strong>to be tested.</p><p>When developers tests the private methods, they normally end the day with complex, unnecessary and boilerplate code which is a sign that unit testing is not only the way to test the functionality but also <strong><em>a tool</em></strong> to see possible design flaws. Let’s get into the details on this sentence with a <strong><em>very basic</em></strong> example but first we need to check a very basic concept of software engineering.</p><h3>Single Responsibility Principle (SRP)</h3><p>In short, as it is stated by the name itself, the single responsibility principle is a programming principle which every part of program must be responsible for <strong><em>only one job</em></strong>. In another saying, each part must only serve the functionality that is related to what it is supposed to do. These parts may be a class, a module or the program itself. We are going to stick with a class this time. For detailed information about this principle, you can check <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">this</a> out.</p><h3>Let’s Get Hands Dirty</h3><p>Amazingly, I say amazingly because when I learn this I was like “wow that is amazing”, when you find yourself in a situation that you need to test private methods of a class to ensure the functionality of the class is correctly implemented or coverage is good enough, you <strong><em>most probably</em></strong> have violated the <strong><em>SRP</em></strong>.</p><p>Let’s see the upcoming <strong><em>Java</em></strong> code snippet which is a sample class for such a scenario;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d66892373b5659eb76b80909c6c4679/href">https://medium.com/media/2d66892373b5659eb76b80909c6c4679/href</a></iframe><p>Here we see a simple Student class with a couple of attributes and two different methods which the one of them has public access modifier and the other has private. Normally, taking an exam is a behavior of the student class. However, in a normal situation, students are not supposed to prepare and create his/her own student identification card.</p><p>In this scenario, <strong><em>takeExam()</em></strong> method is dependent to another method in order to provide its function fully. On the other hand, <strong><em>createIdCard()</em></strong> method is serving an inner functionality for the sake of another functionality and since it is declared as a private method it cannot be reached from outside the class <strong><em>including from unit tests</em></strong>. Also, since it <strong><em>relatively</em></strong> has a complex logic rather than the other parts of the class, not ensuring that everything is working properly within the function can give you really bad headaches in the next stages of development or even in the production stage.</p><p>So what options do we have in order to solve this problem? There may be a couple of approaches.</p><h3>Possible Approaches</h3><h4>Testing Private Methods (DON’T)</h4><p>Let’s start with testing this private method which may be <strong><em>the worst one</em></strong>. There are ways to achieve this with using some core features of programming language. For example, in C# we have <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/ms245564(v=vs.120)">PrivateObject</a> which gives you the ability to call a private property or method within the test. Also we have <a href="https://www.oracle.com/technical-resources/articles/java/javareflection.html">Reflection</a> in Java which provides the same functionality or the annotation of <a href="https://github.com/manifold-systems/manifold/blob/master/manifold-deps-parent/manifold-ext/README.md#type-safe-reflection-via-jailbreak">Jailbreak</a> which is provided by <a href="http://manifold.systems/">Manifold Compiler Plugin</a> is also using <a href="https://www.oracle.com/technical-resources/articles/java/javareflection.html">Reflection</a>. However, choosing this approach is going to be time consuming for development time and also running time and creates <strong><em>unnecessary</em> <em>complexity</em></strong><em>.</em> According to one of the basic principles of unit tests that is <strong><em>being able to run fast</em></strong>, this approach is violating it because <a href="https://www.oracle.com/technical-resources/articles/java/javareflection.html">Reflection</a> and similar libraries are really hungry for processing time. Also, you test a function which normally you cannot use in the production as a client. This also creates a meaningless situation. It is like buying a mobile phone and specifically checking whether its super duper microprocessor can do some complex mathematical calculations like integral by disassembling and connecting it to a special tester device. It is time consuming and difficult as a normal client, isn’t it? Most importantly, it creates redundant complexity for a simple buying action. These functions need their testing in a mobile phone factory. The functions of the mobile phone that you must test are the ones that are easily and normally reachable from a client side. For example, you test it whether you can switch it on and off, have a phone call, see the display is have three colors etc. Be careful. Here is tricky. We can think that the mobile phone factory is also another client for those tests that you normally should not run.</p><h4>Leave Private Methods as They are (Not Recommended)</h4><p>Let’s assume that you have implemented your current business logic and unit tests for all public methods and they all pass. However, there are still some parts that belong to your business logic left untested directly but through your public methods. You kept developing your code and add some new features. After sometime you needed to add some logic in your private methods or change the signature of them because they are used in other logical parts, too. Then you see some red crosses on the test suite which means you break some logic. Now, you have to rewrite your corresponding tests to adapt the logic which requires more time and shows lack of confidence on your tests and also on your code design. This is the same with when you needed to rewrite your already designed and implemented code parts which is a sign of poorly designed structure. Most of the time, dealing with such scenarios requires more and more refactoring and obviously more time. On the other hand, in professional life, you inevitably may come a point that you are required to work with another developers or change your job to another. This new coming poor developer may also face with the same situation and need to add some features or etc. Then it would be harder for him/her to overcome with the situation because he/she is not the who wrote the code itself and this is again just going to cost more time. As it is seen, this is mostly about the time amount that is dedicated to the project.</p><h4>Extract New Parts (Go for it!)</h4><p>As it was stated at the beginning of this article, when you are in a need to test your private methods, you most probably violate SRP. In other means, your class is doing too much. Now, it may be a good time to think about refactoring your existing class structure and extract some new classes from there. Let’s refactor the previous <strong><em>very simple</em></strong> code snippet into two different parts;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5bf3c1004cd37e695789ddd686776df/href">https://medium.com/media/e5bf3c1004cd37e695789ddd686776df/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c68027a0b4ebf22bb65f6a5f203ce7/href">https://medium.com/media/03c68027a0b4ebf22bb65f6a5f203ce7/href</a></iframe><p>As we can see, the creation of student cards is not a responsibility of students. After refactoring and extracting a new class, now we can test each function separately by <a href="https://en.wikipedia.org/wiki/Mock_object"><strong><em>mocking</em></strong></a> the components in each class and also satisfy the SRP. There is a framework called <a href="https://site.mockito.org/">Mockito</a> but it deserves its own article. This approach will decrease the chance of any future errors or unwanted design flaws.</p><h3>In Conclusion</h3><p>Even if I presented a couple of approaches to overcome this problem, there are still another available solutions or counter arguments to this situation. Personally, I mostly stick with the last option.</p><p>As it is seen, unit testing is not only a way to test the functionality but also an indicator of how solid your design is.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afbda842d44a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/havelsan/testing-private-methods-afbda842d44a">Testing Private Methods!</a> was originally published in <a href="https://medium.com/havelsan">HAVELSAN</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>