<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Anant Ghadi</title>
    <description>The latest articles on DEV Community by Anant Ghadi (@anantghadi).</description>
    <link>https://dev.to/anantghadi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4219166%2F6841d0c0-613b-4211-bbfe-2f00ab4e9973.png</url>
      <title>DEV Community: Anant Ghadi</title>
      <link>https://dev.to/anantghadi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/anantghadi"/>
    <language>en</language>
    <item>
      <title>Spring Boot @Transactional: 7 Interview Traps That Catch Experienced Developers</title>
      <dc:creator>Anant Ghadi</dc:creator>
      <pubDate>Tue, 03 Nov 2026 04:34:03 +0000</pubDate>
      <link>https://dev.to/anantghadi/spring-boot-transactional-7-interview-traps-that-catch-experienced-developers-5h7l</link>
      <guid>https://dev.to/anantghadi/spring-boot-transactional-7-interview-traps-that-catch-experienced-developers-5h7l</guid>
      <description>&lt;p&gt;Most backend developers have put &lt;code&gt;@Transactional&lt;/code&gt; on a service method and moved on. It usually works, which is exactly why interviewers like it. A few follow-up questions show quickly whether you know what the annotation does or just where to put it.&lt;/p&gt;

&lt;p&gt;Here are seven of those follow-ups, with answers written the way I'd say them out loud. Everything assumes Spring Boot 3.x (Spring Framework 6.x), Jakarta Persistence, Hibernate 6 and Java 17-21.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. "Why didn't my @Transactional method start a transaction?"
&lt;/h2&gt;

&lt;p&gt;The usual cause is self-invocation.&lt;/p&gt;

&lt;p&gt;Spoken answer: "Spring applies &lt;code&gt;@Transactional&lt;/code&gt; through a proxy. Callers get the proxy, the proxy opens the transaction, then delegates to the real object. If a method inside the same class calls another annotated method with &lt;code&gt;this.&lt;/code&gt;, that call never goes through the proxy, so the annotation is ignored."&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OrderService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;OrderRepository&lt;/span&gt; &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;OrderService&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OrderRepository&lt;/span&gt; &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;orderRepository&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;placeOrders&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;saveOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// same as this.saveOrder(order): no proxy, no transaction&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;saveOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fixes, in the order I'd suggest them: move &lt;code&gt;saveOrder&lt;/code&gt; into a separate bean and inject it, use &lt;code&gt;TransactionTemplate&lt;/code&gt; for programmatic control, or switch to AspectJ weaving if you really need it. Self-injecting the bean with &lt;code&gt;@Lazy&lt;/code&gt; also works, but it's a workaround most reviewers won't love.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. "Can I put @Transactional on a private or final method?"
&lt;/h2&gt;

&lt;p&gt;Spoken answer: "With the default proxy mode, no for private, and no for final. Spring Boot uses class-based (CGLIB) proxies by default, which work by subclassing your bean and overriding methods. A private method can't be overridden, and neither can a final one, so no transaction is applied."&lt;/p&gt;

&lt;p&gt;Two details make this answer stand out:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Since Spring Framework 6.0, &lt;code&gt;protected&lt;/code&gt; and package-private methods &lt;em&gt;can&lt;/em&gt; be transactional with class-based proxies. Before that, only &lt;code&gt;public&lt;/code&gt; methods counted. With interface-based JDK proxies, the method still has to be public and declared on the interface.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;final&lt;/code&gt; method on a proxied bean is a nasty bug. The call runs on the proxy instance itself, whose injected fields are usually &lt;code&gt;null&lt;/code&gt;, so you can get a &lt;code&gt;NullPointerException&lt;/code&gt; instead of a missing transaction.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. "My method threw an exception. Why did the data still commit?"
&lt;/h2&gt;

&lt;p&gt;Spoken answer: "By default Spring rolls back only on &lt;code&gt;RuntimeException&lt;/code&gt; and &lt;code&gt;Error&lt;/code&gt;. A checked exception, like &lt;code&gt;IOException&lt;/code&gt; or your own &lt;code&gt;PaymentFailedException extends Exception&lt;/code&gt;, does not trigger rollback. The transaction commits whatever was written before the exception."&lt;/p&gt;

&lt;p&gt;Fixes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@Transactional(rollbackFor = Exception.class)&lt;/code&gt; on the method or class.&lt;/li&gt;
&lt;li&gt;Since Spring Framework 6.2 you can change the default globally with &lt;code&gt;@EnableTransactionManagement(rollbackOn = RollbackOn.ALL_EXCEPTIONS)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A related follow-up: if you catch the exception inside the method and don't rethrow it, Spring never sees it, so it commits. And if an inner &lt;code&gt;REQUIRED&lt;/code&gt; method throws a runtime exception that the outer method catches, the shared transaction is already marked rollback-only. The outer commit then fails with &lt;code&gt;UnexpectedRollbackException&lt;/code&gt;. That surprises people the first time they see it.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. "REQUIRED vs REQUIRES_NEW: when would you use each?"
&lt;/h2&gt;

&lt;p&gt;Spoken answer: "&lt;code&gt;REQUIRED&lt;/code&gt; is the default. If a transaction already exists, the method joins it; if not, it starts one. Everything commits or rolls back together. &lt;code&gt;REQUIRES_NEW&lt;/code&gt; suspends the current transaction and starts an independent one, which commits or rolls back on its own."&lt;/p&gt;

&lt;p&gt;A real use case: recording a failed payment attempt. You want the audit row saved even when the payment transaction rolls back.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentAuditService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PaymentAuditRepository&lt;/span&gt; &lt;span class="n"&gt;auditRepository&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;PaymentAuditService&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentAuditRepository&lt;/span&gt; &lt;span class="n"&gt;auditRepository&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;auditRepository&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;auditRepository&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;propagation&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Propagation&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;REQUIRES_NEW&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;recordFailure&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;auditRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;PaymentAudit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;reason&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;PaymentService.charge()&lt;/code&gt; runs in its own &lt;code&gt;REQUIRED&lt;/code&gt; transaction, calls &lt;code&gt;paymentAuditService.recordFailure(...)&lt;/code&gt; (a different bean, so the proxy applies), then throws. The charge rolls back, and the audit row stays.&lt;/p&gt;

&lt;p&gt;The catch worth mentioning: &lt;code&gt;REQUIRES_NEW&lt;/code&gt; needs a second database connection while the first one is suspended. Under load, heavy use of it can exhaust a small connection pool.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. "What does readOnly = true actually do?"
&lt;/h2&gt;

&lt;p&gt;Spoken answer: "It's a hint, and with Hibernate it has real effects. Spring sets the Hibernate session to manual flush mode and marks it read-only, so Hibernate skips dirty checking and doesn't keep snapshots of loaded entities. That saves memory and CPU on big reads. By default Spring also passes the read-only flag to the JDBC connection, and some drivers and databases use it for optimisations, or a routing data source can send those calls to a read replica."&lt;/p&gt;

&lt;p&gt;What it doesn't do: it isn't a security guarantee. Whether a write fails depends on the driver and the database, so don't rely on it to block writes. Use it on query methods so you get the performance benefit, and keep writes in methods without it.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. "Two users update the same row at once. What happens?"
&lt;/h2&gt;

&lt;p&gt;This is the lost update problem. Both transactions read balance 1,000, one adds 200, the other subtracts 100, and whichever commits last wins. One change disappears.&lt;/p&gt;

&lt;p&gt;Spoken answer: "&lt;code&gt;@Transactional&lt;/code&gt; uses &lt;code&gt;Isolation.DEFAULT&lt;/code&gt;, which means the database's default: READ COMMITTED on PostgreSQL and Oracle, REPEATABLE READ on MySQL InnoDB. READ COMMITTED does not stop a read-modify-write lost update. You can raise isolation, but in a JPA application the common fix is optimistic locking with a version column."&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Version&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;deposit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;balance&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hibernate adds &lt;code&gt;WHERE version = ?&lt;/code&gt; to the update. If another transaction changed the row first, zero rows are updated and Spring throws &lt;code&gt;ObjectOptimisticLockingFailureException&lt;/code&gt;. You then retry or return a conflict to the client. When conflicts are frequent, like a hot counter, pessimistic locking with &lt;code&gt;@Lock(LockModeType.PESSIMISTIC_WRITE)&lt;/code&gt; on a repository query can be the better choice.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. "Why do I get LazyInitializationException, and why doesn't it happen in my controller?"
&lt;/h2&gt;

&lt;p&gt;Spoken answer: "A lazy association is loaded only when you touch it, and that needs an open Hibernate session. If you access &lt;code&gt;order.getItems()&lt;/code&gt; after the transaction and session are closed, for example in a mapper or a scheduled job, you get &lt;code&gt;LazyInitializationException&lt;/code&gt;."&lt;/p&gt;

&lt;p&gt;It often doesn't show up in controllers because Spring Boot enables Open Session in View by default (&lt;code&gt;spring.jpa.open-in-view=true&lt;/code&gt;). The session stays open for the whole web request, so lazy loading works in the controller and during JSON serialisation. Boot logs a warning about it at startup for a reason: it hides N+1 queries and holds a connection for the whole request.&lt;/p&gt;

&lt;p&gt;Better fixes: fetch what you need inside the service with &lt;code&gt;JOIN FETCH&lt;/code&gt;, &lt;code&gt;@EntityGraph&lt;/code&gt;, or a DTO projection, and set &lt;code&gt;spring.jpa.open-in-view=false&lt;/code&gt; so problems show up in tests instead of production.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;OrderRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@EntityGraph&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attributePaths&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"items"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findWithItemsById&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Quick revision checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Self-invocation skips the proxy. Call through another bean or use &lt;code&gt;TransactionTemplate&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Private and final methods aren't proxied. Protected and package-private work on class-based proxies since Spring 6.0.&lt;/li&gt;
&lt;li&gt;Default rollback is unchecked exceptions and errors only. Use &lt;code&gt;rollbackFor&lt;/code&gt;, or &lt;code&gt;rollbackOn = ALL_EXCEPTIONS&lt;/code&gt; on Spring 6.2+.&lt;/li&gt;
&lt;li&gt;A caught inner exception can still mark the transaction rollback-only and give you &lt;code&gt;UnexpectedRollbackException&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;REQUIRES_NEW&lt;/code&gt; is for work that must survive the outer rollback, like audit logs. It costs an extra connection.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;readOnly = true&lt;/code&gt; turns off Hibernate dirty checking and flushing. It's not a write lock.&lt;/li&gt;
&lt;li&gt;Default isolation comes from the database. Use &lt;code&gt;@Version&lt;/code&gt; against lost updates.&lt;/li&gt;
&lt;li&gt;Fetch lazy data inside the transaction and consider turning off open-in-view.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Which of these has bitten you in a real project? I'd like to hear about it in the comments.&lt;/p&gt;




&lt;p&gt;If you're preparing for Java backend interviews, my Java &amp;amp; Spring Boot Interview Prep Guide has 240 questions like these (Core Java, Spring Boot 3, JPA, microservices, system design). Get it here: &lt;a href="https://topmate.io/anantghadi/2384289" rel="noopener noreferrer"&gt;https://topmate.io/anantghadi/2384289&lt;/a&gt; (India, ₹299) or &lt;a href="https://payhip.com/b/pNo2T" rel="noopener noreferrer"&gt;https://payhip.com/b/pNo2T&lt;/a&gt; (international, $7). There's also a free 8-page sample on my Topmate: &lt;a href="https://topmate.io/anantghadi" rel="noopener noreferrer"&gt;https://topmate.io/anantghadi&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This article was written with AI assistance.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>interview</category>
      <category>programming</category>
    </item>
    <item>
      <title>How HashMap Really Works in Java 21: 7 Interview Follow-ups Most People Miss</title>
      <dc:creator>Anant Ghadi</dc:creator>
      <pubDate>Sat, 31 Oct 2026 14:35:22 +0000</pubDate>
      <link>https://dev.to/anantghadi/how-hashmap-really-works-in-java-21-7-interview-follow-ups-most-people-miss-45j4</link>
      <guid>https://dev.to/anantghadi/how-hashmap-really-works-in-java-21-7-interview-follow-ups-most-people-miss-45j4</guid>
      <description>&lt;p&gt;"How does HashMap work internally?" is probably the most asked Java interview question. Most candidates say "it uses hashing and buckets" and stop there. The interviewer then asks a follow-up, and that is where the round is won or lost.&lt;/p&gt;

&lt;p&gt;Here are the 7 follow-ups I see most often, with answers you can say out loud.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. What actually happens when you call put()?
&lt;/h2&gt;

&lt;p&gt;HashMap keeps an array of buckets (a &lt;code&gt;Node&amp;lt;K,V&amp;gt;[] table&lt;/code&gt;). On &lt;code&gt;put(key, value)&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It calls &lt;code&gt;key.hashCode()&lt;/code&gt; and spreads the bits: &lt;code&gt;hash = h ^ (h &amp;gt;&amp;gt;&amp;gt; 16)&lt;/code&gt;. This mixes the high bits into the low bits so small tables still get a good spread.&lt;/li&gt;
&lt;li&gt;It finds the bucket with &lt;code&gt;index = (n - 1) &amp;amp; hash&lt;/code&gt;, where n is the table size (always a power of two).&lt;/li&gt;
&lt;li&gt;If the bucket is empty, the new node goes there. If not, it walks the bucket and uses &lt;code&gt;equals()&lt;/code&gt; to check whether the key already exists. If it does, the value is replaced. If not, the node is added at the end.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One-line answer: &lt;strong&gt;hashCode() picks the bucket, equals() picks the entry.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What are the default capacity and load factor, and why do they matter?
&lt;/h2&gt;

&lt;p&gt;Default capacity is 16 and the load factor is 0.75, so the map resizes once it holds more than 12 entries. Resizing doubles the table and redistributes the entries, which costs time. If you know you will store 10,000 entries, size the map up front.&lt;/p&gt;

&lt;p&gt;Since Java 19 there is a cleaner way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;newHashMap&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10_000&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This sizes the table for 10,000 mappings with the load factor already accounted for. Most candidates have never heard of it, so mentioning it stands out.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How does resizing work without recalculating every hash?
&lt;/h2&gt;

&lt;p&gt;Because the table size is a power of two, doubling it adds one more bit to the index. Java 8+ checks &lt;code&gt;(hash &amp;amp; oldCapacity)&lt;/code&gt;. If that bit is 0, the entry stays at the same index. If it is 1, it moves to &lt;code&gt;index + oldCapacity&lt;/code&gt;. Each bucket splits into a "low" and a "high" list, and the original order is kept.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. What happens when many keys collide in one bucket?
&lt;/h2&gt;

&lt;p&gt;Up to Java 7, a bucket was always a linked list, so a bad &lt;code&gt;hashCode()&lt;/code&gt; could turn lookups into O(n).&lt;/p&gt;

&lt;p&gt;Since Java 8, when a single bucket reaches 8 entries and the table has at least 64 buckets, that bucket is converted into a red-black tree, making worst-case lookups O(log n). If the table is smaller than 64, HashMap resizes instead. When a tree shrinks to 6 entries, it turns back into a list.&lt;/p&gt;

&lt;p&gt;Follow-up trap: trees work best when keys implement &lt;code&gt;Comparable&lt;/code&gt;. Without it, HashMap falls back to tie-breaking rules and loses some of the benefit.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Why must equals() and hashCode() be overridden together?
&lt;/h2&gt;

&lt;p&gt;The contract: if &lt;code&gt;a.equals(b)&lt;/code&gt; is true, then &lt;code&gt;a.hashCode() == b.hashCode()&lt;/code&gt; must be true.&lt;/p&gt;

&lt;p&gt;Override &lt;code&gt;equals()&lt;/code&gt; but not &lt;code&gt;hashCode()&lt;/code&gt;, and two "equal" keys can land in different buckets. You put a value in, then &lt;code&gt;get(sameLookingKey)&lt;/code&gt; returns null.&lt;/p&gt;

&lt;p&gt;The modern answer: use a record. Records generate &lt;code&gt;equals()&lt;/code&gt; and &lt;code&gt;hashCode()&lt;/code&gt; from their components automatically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;EmployeeKey&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;dept&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Why are mutable keys dangerous?
&lt;/h2&gt;

&lt;p&gt;If you change a field used in &lt;code&gt;hashCode()&lt;/code&gt; after inserting the key, the entry is still sitting in the old bucket, but lookups now go to a different one. The value is effectively lost: &lt;code&gt;get()&lt;/code&gt; returns null, and the stale entry stays in the map.&lt;/p&gt;

&lt;p&gt;Rule of thumb: keys should be immutable. &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Integer&lt;/code&gt; and records are ideal.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Is HashMap thread-safe? What should you use instead?
&lt;/h2&gt;

&lt;p&gt;No. Concurrent writes can lose updates or corrupt the structure. In Java 7, concurrent resizing could even create a loop in a bucket, causing an infinite loop on &lt;code&gt;get()&lt;/code&gt;, because entries were inserted at the head of the list. Java 8 switched to tail insertion, but HashMap is still not safe for concurrent use.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;ConcurrentHashMap&lt;/code&gt;. It locks at the bucket level and uses CAS for empty buckets, so reads are mostly lock-free.&lt;/p&gt;

&lt;p&gt;Follow-up trap: &lt;code&gt;ConcurrentHashMap&lt;/code&gt; does not allow null keys or null values, while HashMap allows one null key (stored in bucket 0) and many null values. The reason: in a concurrent map, &lt;code&gt;get()&lt;/code&gt; returning null would be ambiguous. Is the key missing, or is the value null?&lt;/p&gt;

&lt;h2&gt;
  
  
  Bonus: what about ordering?
&lt;/h2&gt;

&lt;p&gt;HashMap gives no ordering guarantee. Use &lt;code&gt;LinkedHashMap&lt;/code&gt; for insertion order (or access order, for LRU caches) and &lt;code&gt;TreeMap&lt;/code&gt; for sorted keys. In Java 21, &lt;code&gt;LinkedHashMap&lt;/code&gt; implements the new &lt;code&gt;SequencedMap&lt;/code&gt; interface, so you get &lt;code&gt;firstEntry()&lt;/code&gt;, &lt;code&gt;lastEntry()&lt;/code&gt; and &lt;code&gt;reversed()&lt;/code&gt; directly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quick revision checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;hashCode() picks the bucket, equals() picks the entry&lt;/li&gt;
&lt;li&gt;Capacity 16, load factor 0.75, resize past 12 entries&lt;/li&gt;
&lt;li&gt;Treeify at 8 entries per bucket when the table has 64+ buckets&lt;/li&gt;
&lt;li&gt;Resize splits buckets using &lt;code&gt;hash &amp;amp; oldCapacity&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Immutable keys, ideally records&lt;/li&gt;
&lt;li&gt;ConcurrentHashMap for concurrency, and no nulls there&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HashMap.newHashMap(n)&lt;/code&gt; to pre-size (Java 19+)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you're preparing for Java backend interviews, I put together a guide with 240 questions like this one, covering Core Java, Spring Boot 3, JPA, microservices and system design. There's a free 8-page sample on my profile.&lt;/p&gt;

&lt;p&gt;Which HashMap follow-up caught you off guard in an interview? Tell me in the comments.&lt;/p&gt;

</description>
      <category>java</category>
      <category>interview</category>
      <category>programming</category>
      <category>career</category>
    </item>
  </channel>
</rss>
