<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Nataliia Dziubenko</title>
        <description>Blog</description>
        <link>https://nataliiadziubenko.com/</link>
        <atom:link href="https://nataliiadziubenko.com/feed.xml" rel="self" type="application/rss+xml"/>
        <pubDate>Fri, 13 Nov 2026 21:11:40 +0000</pubDate>
        <lastBuildDate>Fri, 13 Nov 2026 21:11:40 +0000</lastBuildDate>
        <generator>Jekyll v3.10.0</generator>
        
        <item>
            <title>What makes a puzzle hard? Grading puzzles for my first iOS game</title>
            <description>&lt;p&gt;After spending about a month building Furdoku, my first iOS game, I came to a conclusion that didn’t surprise me at all: building is never the hardest part. The hardest part is actually making it a product, which involves a range of challenges from design to sales and marketing.&lt;/p&gt;

&lt;p&gt;Most of my time went into the game design. Since it’s a puzzle game, I had to figure out how to make it fun, how to make it easy enough and also hard enough, and how to grade it correctly. With AI, building something from scratch with unfamiliar technology no longer surprises anyone, I believe :) So let me share the actually interesting part of the process.&lt;/p&gt;

&lt;p&gt;Let’s start with some numbers that made me go “wow” when I learned them. I playtested well over 500 puzzles and spent 50+ hours doing it (yes, it was measured).&lt;/p&gt;

&lt;p&gt;You might be wondering: wasn’t it possible to automate this work? Was it really necessary to playtest everything? Playtesting helped me gather the data that I could use to calibrate my grading logic.&lt;/p&gt;

&lt;p&gt;Some of the tested puzzles didn’t make it into the release. I often threw away whole batches because the metrics weren’t good enough. I had tons of data, but wasn’t using it right. I made loads of mistakes before I got to a grading approach I could trust. It turned out to be a really difficult problem, one that AI couldn’t solve for me, though it definitely helped a lot.&lt;/p&gt;

&lt;h3 id=&quot;what-is-furdoku&quot;&gt;What is Furdoku?&lt;/h3&gt;

&lt;p&gt;Ever since I was a kid, I’ve enjoyed puzzles like sudoku and Minesweeper. Furdoku is a sudoku variant, where you place entities such as sheep, people, dogs, and chickens, following the sudoku rules, meaning you must put exactly one of each entity in every row, column and 3x3 box. On top of that, there are special rules, for example, you can’t place sheep near wolves, or you need to place a dog near a human, otherwise it feels lonely, and so on. Many cells stay empty, which invites new techniques for solving these puzzles, such as checking how many cells are taken in a row/column/box to decide that a certain cell is definitely empty (it feels like Minesweeper at times). Marking cells as empty is part of the game: this way you eliminate where none of the entities can be placed and rely on this for the next steps.&lt;/p&gt;

&lt;p&gt;Each pack has its own rules and feels like a slightly different game. Some examples:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wolf, Goat &amp;amp; Cabbage&lt;/strong&gt;: the old river-crossing riddle in a new form. The wolf eats the goat, the goat eats the cabbage. Place goats and cabbages by sudoku rules, but don’t allow anything to get eaten.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pets&lt;/strong&gt;: cats like to be on their own, dogs don’t. Place humans and dogs by sudoku rules, but nothing can stand next to a cat, and every dog needs a human next to it.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/furdoku_grading/ipad-pets-rules.jpg&quot; alt=&quot;A Pets puzzle on iPad, with the pack&apos;s rules open next to the board&quot; width=&quot;560&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Every puzzle must have exactly one solution, and importantly, you can get to that solution without trial and error. Everything can be solved by logic alone. To ensure that, I have a solver for each pack that solves puzzles like a human would, using techniques, step by step.&lt;/p&gt;

&lt;p&gt;Every pack has easy/medium/hard levels, and to determine these levels I needed to build a grader. That was the main challenge. I will talk more about it below.&lt;/p&gt;

&lt;h3 id=&quot;how-furdoku-was-built&quot;&gt;How Furdoku was built&lt;/h3&gt;

&lt;p&gt;Furdoku is built on my ideas, design, and mechanics. I drew the art for it on my iPad and put a piece of myself into this project. It was implemented using Claude, where I worked with it closely to ensure good code quality and architecture, and made adjustments wherever things looked fishy. Rules and constraints of the puzzles were defined by me, but the puzzles were generated, and they needed quality (solver) and difficulty (grader) evaluation.&lt;/p&gt;

&lt;p&gt;I was teaming up with Claude very closely while building the grader. My part was spotting patterns we could incorporate into our tooling, and Claude made it possible to quickly implement them and try out ideas. The prototyping went fast, and that was the big strength of AI.&lt;/p&gt;

&lt;h3 id=&quot;fewer-clues--harder-right&quot;&gt;Fewer clues == harder, right?&lt;/h3&gt;

&lt;p&gt;The starting point for me was the instinct that the more constraints are visible on the board at the start, the easier it is to solve. I wanted to make sure my metrics were somewhat defensible, so I played the puzzles myself and timed each and every one of them (the app does it for you actually) to judge difficulty based on my timing.&lt;/p&gt;

&lt;p&gt;Well, here is an example from the Pets pack. The assumption is that the more cats there are at the start, the easier it is to solve the puzzle.&lt;/p&gt;

&lt;p&gt;Which one do you think took me longer to solve?&lt;/p&gt;

&lt;p style=&quot;display: flex; gap: 20px;&quot;&gt;
  &lt;img src=&quot;/assets/images/furdoku_grading/puzzle-b-four-cats.png&quot; alt=&quot;Pets puzzle B, with 4 cats&quot; style=&quot;width: calc(50% - 10px);&quot; /&gt;
  &lt;img src=&quot;/assets/images/furdoku_grading/puzzle-a-seven-cats.png&quot; alt=&quot;Pets puzzle A, with 7 cats&quot; style=&quot;width: calc(50% - 10px);&quot; /&gt;
&lt;/p&gt;

&lt;p&gt;The one with fewer clues took me under &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 min&lt;/code&gt;, the one with more clues took &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8 min&lt;/code&gt;.
It turned out that the number of clues didn’t matter. I expected a graph telling me otherwise, but the data of solving 150 puzzles in this pack showed there was little to no dependency of my timing on the number of clues (&lt;a href=&quot;https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient&quot;&gt;Spearman correlation&lt;/a&gt; = &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;−0.14&lt;/code&gt;, where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; means “no relationship at all”).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/furdoku_grading/clues-vs-time.svg&quot; alt=&quot;My solve time for each of the 150 Pets puzzles against its number of cat clues: no visible relationship&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The same pattern (or the absence of one) showed in different packs with different rules too.&lt;/p&gt;

&lt;p&gt;So what actually makes a puzzle hard?&lt;/p&gt;

&lt;h3 id=&quot;putting-on-the-scientist-pants&quot;&gt;Putting on the scientist pants&lt;/h3&gt;

&lt;p&gt;My first improvement was counting ‘rounds’, where, in a nutshell, you count how many rounds of throwing techniques at the grid it takes to solve a puzzle. You end up counting the steps, but not the difficulty of those steps. The time-to-rounds correlation was better, but still weak.&lt;/p&gt;

&lt;p&gt;I was sure somebody had already researched the problem of grading sudoku puzzles, and possibly variants too. And indeed, I found Andrew Stuart’s &lt;a href=&quot;https://www.sudokuwiki.org/Sudoku_Creation_and_Grading.pdf&quot;&gt;paper on grading sudoku&lt;/a&gt;, which helped me a lot.&lt;/p&gt;

&lt;p&gt;The paper lists dozens of solving techniques, ordered by their estimated difficulty. Here are some of the techniques that were applicable to my variant. Let’s continue with the Pets pack as an example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hidden singles&lt;/strong&gt;: if a human can go in exactly one place in a given row/column/box, it goes there, even if a dog could go there too.&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;/assets/images/furdoku_grading/tip-hidden-single.png&quot; alt=&quot;Hidden single: the box&apos;s human has only one cell left&quot; /&gt;
&lt;/figure&gt;

&lt;p&gt;&lt;strong&gt;Intersection removal&lt;/strong&gt;: if a box’s dog can only go in one line, that line’s dog must be in this box, so no other cell in that line can hold a dog.&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;/assets/images/furdoku_grading/tip-intersection-removal.png&quot; alt=&quot;Intersection removal: the box&apos;s dog must be in the middle row, so the rest of that row can&apos;t hold a dog&quot; /&gt;
&lt;/figure&gt;

&lt;p&gt;On top of these, there were pack-specific techniques. For example, a dog needs a human next to it, so if none of the cells around a spot can hold a human, a dog can’t go there.&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;/assets/images/furdoku_grading/tip-dog-needs-human.png&quot; alt=&quot;A dog needs a human next to it: no human can stand around the middle cell, so no dog can go there&quot; /&gt;
&lt;/figure&gt;

&lt;p&gt;There were a couple of techniques based on this dog-human relationship, and they weren’t equally hard. To figure out which ones were hard, I had to get properly stuck in a puzzle a few times, so that part was mostly subjective. Each technique got a weight assigned to it, mostly driven by my playtime measurements, the best data I had.&lt;/p&gt;

&lt;p&gt;The next step was to adopt technique scoring from the paper. In each round, you add the weight of the easiest technique needed to get to the next round. This time, the difficulty of each step actually matters. After incorporating this and identifying some more “custom” techniques, the Spearman correlation settled at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.46&lt;/code&gt; for the whole pack (not great, not terrible).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/furdoku_grading/technique-vs-time.svg&quot; alt=&quot;My solve time for each of the 150 Pets puzzles against its technique score: higher-scored puzzles tend to take longer&quot; /&gt;&lt;/p&gt;

&lt;p&gt;But that is not the whole story…&lt;/p&gt;

&lt;h3 id=&quot;nuances&quot;&gt;Nuances&lt;/h3&gt;

&lt;p&gt;Playing it all myself mattered for finding the strange outliers and filtering them out.&lt;/p&gt;

&lt;p&gt;Yes, technically it was all solvable by logic, but at some point I found myself holding two hypotheses in my head at the same time before I could place anything, and it felt like trial and error. That’s also the simplest brute-force approach a program can use to get to a solution (backtracking): try different possibilities that fit until you stumble upon a conflict, and if you do, go back and try another possibility.&lt;/p&gt;

&lt;p&gt;When you find yourself needing a pencil and an eraser to solve a sudoku, know that something is wrong. I caught myself using a mental pencil to write mental notes, even if only one level deep into the possibility tree. Puzzles like that were thrown away. Hard puzzles are great, but they shouldn’t be punishing.&lt;/p&gt;

&lt;p&gt;There is one more nuance: my sudoku variant has at most 2 kinds of entities (versus 9 digits in classic sudoku), so many techniques that work for classic sudoku don’t apply here. Instead of dozens of techniques, I had a handful to play with, meaning I had less wiggle room for difficulty.&lt;/p&gt;

&lt;h3 id=&quot;deceived-by-data&quot;&gt;Deceived by data&lt;/h3&gt;

&lt;p&gt;One thing you might have been shouting in your head this whole time:
‘Girl, your solving skills improved! Time is a bad metric!’
And you’re absolutely right.&lt;/p&gt;

&lt;p&gt;My difficulty formula was based on time ranges for solving: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 3 min&lt;/code&gt; for easy, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;= 3&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 7&lt;/code&gt; for medium, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;= 7&lt;/code&gt; for hard.
I found myself timing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1:20&lt;/code&gt; for a hard puzzle that genuinely felt hard and made me twist my brain a little. Putting it in the easy tier was just wrong.&lt;/p&gt;

&lt;p&gt;At the start, each pack was like a new game. I was working out the logic, and every conclusion felt like a new discovery. As you go through a pack, you start spotting patterns automatically. They don’t need discovering anymore, they’re already familiar.&lt;/p&gt;

&lt;p&gt;So I had to change the way I used my times. At that point I had a lot more trust in my grader, because it was backed by science (yeah, right), so my times became supporting information. The puzzles that only need the easiest techniques go to the easy tier, the ones that need advanced techniques can’t go there. Outside of that, sort them by my time.&lt;/p&gt;

&lt;p&gt;The last pack I made was a Christmas pack (coming in the next update), and it’s a good illustration. In the final version, the easy puzzles took me slightly longer on average than the medium ones, but they stayed in easy because of the techniques they needed.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/furdoku_grading/xmas-tiers.svg&quot; alt=&quot;My solve time for each of the 60 Christmas puzzles by shipped tier: easy puzzles took slightly longer than medium ones&quot; /&gt;&lt;/p&gt;

&lt;p&gt;At least, it looked like it made sense.&lt;/p&gt;

&lt;h3 id=&quot;lessons&quot;&gt;Lessons&lt;/h3&gt;

&lt;p&gt;In an ideal world, with an ideal me, this would have been the right approach:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;find research on the matter on day one, don’t blindly bump into things;&lt;/li&gt;
  &lt;li&gt;involve more people in testing;&lt;/li&gt;
  &lt;li&gt;give them smaller batches, so their learning curve doesn’t skew the times;&lt;/li&gt;
  &lt;li&gt;ask them to write down where they got stuck the most (this was one of the signals that worked best for me).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If I am completely honest, I am still not sure that I did it right in the end.&lt;/p&gt;

&lt;p&gt;If you’re willing to &lt;del&gt;supply more data&lt;/del&gt; play Furdoku for fun and fun only, &lt;a href=&quot;https://apps.apple.com/app/apple-store/id6825307980?pt=129655037&amp;amp;ct=blog&amp;amp;mt=8&quot;&gt;here it is&lt;/a&gt;.
If you want to talk about Furdoku, write me at &lt;a href=&quot;mailto:nataliia@frozenbits.se&quot;&gt;nataliia@frozenbits.se&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thank you for reading! I hope you enjoyed it and will come back when I tell you about my next project 👀&lt;/p&gt;

&lt;p align=&quot;center&quot;&gt;
  &lt;img class=&quot;no-plate&quot; src=&quot;/assets/images/furdoku_grading/sheep-sunglasses.png&quot; alt=&quot;A sheep from Furdoku wearing sunglasses&quot; width=&quot;220&quot; /&gt;
&lt;/p&gt;
</description>
            <pubDate>Thu, 12 Nov 2026 11:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2026/11/12/furdoku-grading-puzzles.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2026/11/12/furdoku-grading-puzzles.html</guid>
            
            
        </item>
        
        <item>
            <title>AWS RDS (Postgres): how to debug spilling to disk</title>
            <description>&lt;p&gt;Recently, I had to quickly learn how to debug excessive spilling to disk on a Postgres instance. Information online on this topic is mostly scattered. I have a feeling that, whenever query plan analysis is involved, things always get a bit mystical.&lt;/p&gt;

&lt;p&gt;Since I’m going to forget it all tomorrow, it’s good to write it down, both for others and for the future me.&lt;/p&gt;

&lt;h3 id=&quot;situation&quot;&gt;Situation&lt;/h3&gt;

&lt;p&gt;You notice that your RDS instance is consistently eating large amounts of storage space (in my case, the rate was ~280MB/min).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/images/rds_spilling/storage-eaten.png&quot; alt=&quot;Eaten storage&quot; /&gt;&lt;/p&gt;

&lt;p&gt;You ruled out the data itself, index bloating, checked that autovacuum is working. You also don’t have any long-running transactions.&lt;/p&gt;

&lt;p&gt;You ruled out the WAL (Write-Ahead Logs). It’s easy to see whether it’s a problem in RDS monitoring by checking the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransactionLogsDiskUsage&lt;/code&gt; metric.&lt;/p&gt;

&lt;p&gt;You also possibly notice that there is enough available memory, yet it’s not being used. So that can’t be spilling, right? Well… we’ll come back to that a bit later.&lt;/p&gt;

&lt;p&gt;You can actually prove that crazy volumes are taken by temporary files:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SELECT temp_bytes FROM pg_stat_database;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Keep in mind that it’s a cumulative metric, it shows how many bytes have been written since the last reset.
This looks pretty bad:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&quot;temp_bytes&quot;: 275091742956
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now you know that temporary files are steadily eating your storage and threatening to kill your DB.&lt;br /&gt;
What can you do?&lt;/p&gt;

&lt;h3 id=&quot;dont-panic&quot;&gt;Don’t panic&lt;/h3&gt;
&lt;p&gt;Enable logging of temp file creation, and you will be able to see the exact queries writing to temporary files.
PostgreSQL has a setting for that: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_temp_files&lt;/code&gt;, where you can specify the file size threshold (in KB) for logging.&lt;/p&gt;

&lt;p&gt;You can adjust settings globally through AWS, and the changes will apply immediately, no reboot needed.
To do that, go to RDS Parameter groups.&lt;/p&gt;

&lt;p&gt;Where are the logs? &lt;br /&gt;
Go to RDS -&amp;gt; DB Instances, chose yours, go to Logs &amp;amp; Events.
In the logs, you can now find entries like this:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;STATEMENT:  INSERT INTO foobar (id, name) SELECT * FROM UNNEST($1, $2) AS t(id, name) ORDER BY id ...
LOG:  temporary file: path &quot;base/pgsql_tmp/pgsql_tmp1234.5&quot;, size 124718640
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If you’ve run out of storage, you’ll see spilling in the logs even without enabling any settings, since the errors are quite
descriptive of the situation (always look for positives):&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;STATEMENT:  INSERT INTO foobar (id, name) SELECT * FROM UNNEST($1, $2) AS t(id, name) ORDER BY id ...
ERROR: could not write to file &quot;base/pgsql_tmp/pgsql_tmp1234.5&quot;: No space left on device
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now you know which query is causing the problem. &lt;br /&gt;
What now?&lt;/p&gt;

&lt;h3 id=&quot;memory&quot;&gt;Memory&lt;/h3&gt;
&lt;p&gt;Remember when I mentioned memory earlier?&lt;/p&gt;

&lt;p&gt;It turns out it’s not enough to just have gigabytes of available memory. You should also check what your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;work_mem&lt;/code&gt; value is.
You can either see it again in the RDS parameter group or simply run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;show work_mem;&lt;/code&gt;. The default value is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4MB&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This value defines how much memory can be used by a single node in your query execution. For example, if you’re doing sorting and
the intermediate data doesn’t fit in memory, it’s written to a temporary file.&lt;/p&gt;

&lt;p&gt;From &lt;a href=&quot;https://www.postgresql.org/docs/17/runtime-config-resource.html&quot;&gt;Postgres documentation&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;work_mem (integer)&lt;br /&gt;
Sets the base maximum amount of memory to be used by a query operation (such as a sort or hash table) before writing to temporary disk files. If this value is specified without units, it is taken as kilobytes. The default value is four megabytes (4MB). Note that a complex query might perform several sort and hash operations at the same time, with each operation generally being allowed to use as much memory as this value specifies before it starts to write data into temporary files. Also, several running sessions could be doing such operations concurrently. Therefore, the total memory used could be many times the value of work_mem; it is necessary to keep this fact in mind when choosing the value. Sort operations are used for ORDER BY, DISTINCT, and merge joins. Hash tables are used in hash joins, hash-based aggregation, memoize nodes and hash-based processing of IN subqueries.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To summarize: having a lot of available memory doesn’t mean it will be used; if intermediate data doesn’t fit in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;work_mem&lt;/code&gt;, it still spills to disk. Adjust this value carefully. If it’s set too high, you’re allowing each node in a query to use that much memory. If you run out of memory, things can go from bad to worse.&lt;/p&gt;

&lt;h3 id=&quot;but-whats-wrong-with-my-query&quot;&gt;But what’s wrong with my query?&lt;/h3&gt;
&lt;p&gt;If you have some really complex queries, it’s not obvious which operation needs so much space. And if you want to optimize it, how do you even know what to fix?&lt;/p&gt;

&lt;p&gt;You tried running &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;EXPLAIN (ANALYZE, BUFFERS) ...&lt;/code&gt; with some test parameters, but nothing in the plan mentions writing to disk.
It seems you need some real execution plans, with real parameters, from real queries.&lt;/p&gt;

&lt;p&gt;Here are some interesting settings:&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shared_preload_libraries&lt;/code&gt; - make sure it contains &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;auto_explain&lt;/code&gt;, which allows to log query plans of real queries at runtime.&lt;/p&gt;

&lt;p&gt;Then, enable these:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;auto_explain.log_analyze=1
auto_explain.log_buffers=1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Also, you can set the minimum duration for queries to be logged:&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;auto_explain.log_min_duration=1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now, you’ll be able to see the execution plans of real queries in the logs.
What should you look for?&lt;/p&gt;

&lt;h4 id=&quot;any-mentions-of-disk&quot;&gt;🔸any mentions of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Disk:&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;Sometimes it’s straightforward, for example:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;-&amp;gt;  Sort  (cost=256783.74..258210.97 rows=570890 width=108) (actual time=124156.238..124157.932 rows=8198 loops=1)
      Sort Key: a.some_value
      Sort Method: external merge  Disk: 152352kB
      Buffers: shared hit=117500 read=38719, temp read=46571 written=65161
      I/O Timings: shared read=3578.004, temp read=10198.270 write=19054.568
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This means that sorting didn’t fit in memory and had to write about &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;150MB&lt;/code&gt; to disk.&lt;/p&gt;

&lt;h4 id=&quot;-any-mentions-of-buffers-temp-writtenn-or-buffers-temp-readm-writtenn&quot;&gt;🔸 any mentions of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Buffers: temp written=n&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Buffers: temp read=m written=n&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;Some &lt;a href=&quot;https://www.pgmustard.com/docs/explain/buffers-temp-written&quot;&gt;info on it&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt; is the value that you’re interested in, it specifies how many blocks of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8KB&lt;/code&gt; are written to disk.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;-&amp;gt;  Hash  (cost=84674.80..84674.80 rows=1585280 width=58) (actual time=32708.031..32708.031 rows=1634942 loops=1)
        Buckets: 131072  Batches: 32  Memory Usage: 5583kB
        Buffers: shared hit=30103 read=38719, temp written=15455
        I/O Timings: shared read=3578.004, temp write=5954.796
        -&amp;gt;  Seq Scan on abcdef a  (cost=0.00..84674.80 rows=1585280 width=58) (actual time=42.932..18984.238 rows=1634942 loops=1)
              Filter: (something IS NOT NULL)
              Buffers: shared hit=30103 read=38719
              I/O Timings: shared read=3578.004
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here, hash table was written to disk, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15455 * 8KB = ~120MB&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Keep in mind that you should carefully check the most nested child nodes containing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;temp written&lt;/code&gt;, because parent nodes
have a value that’s the sum of their children’s values. Often, it all boils down to a single nested node, and that’s where you’ll find the real cause.&lt;/p&gt;

&lt;p&gt;Sometimes, you simply have CTE scans:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;-&amp;gt;  CTE Scan on something  (cost=0.00..0.04 rows=2 width=64) (actual time=0.002..930.622 rows=18607 loops=1)
      Buffers: shared hit=111639, temp written=295
      I/O Timings: temp write=18.274
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This hints that the CTE (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;WITH cte as (...)&lt;/code&gt;) has been materialized, which Postgres can do behind the scenes when CTE is reused in the query. The materialized CTE is normally held in memory if it fits; otherwise, it spills to disk.&lt;/p&gt;

&lt;p&gt;Now that you know what’s “wrong” with your queries, you can consider some ways to rewrite them.&lt;/p&gt;

&lt;p&gt;Don’t forget to disable query plan logging afterward; it consumes a lot of, well, storage 😛&lt;/p&gt;

&lt;h3 id=&quot;cleaning-up&quot;&gt;Cleaning up&lt;/h3&gt;

&lt;p&gt;Here’s another interesting piece of information that might be relevant.
Postgres also has this boolean setting: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;remove_temp_files_after_crash&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;By default, it’s enabled, but if it’s disabled in your system, it means that if a backend crashes, Postgres won’t clean up the related temporary files so you can use them for debugging. However, if crashes happen a lot, you will accumulate these files and fill your storage.&lt;/p&gt;

&lt;p&gt;Here are related &lt;a href=&quot;https://postgresqlco.nf/doc/en/param/remove_temp_files_after_crash/&quot;&gt;docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In normal situation, Postgres cleans up temporary files, and you don’t need to do anything manually.
It can happen though, that Postgres can’t keep up with the rate of writing, hence the storage space keeps shrinking.&lt;/p&gt;

&lt;h3 id=&quot;other&quot;&gt;Other&lt;/h3&gt;

&lt;p&gt;There’s a config that you can use to prohibit writing to temp files if the current process’s files
reach certain size threshold (in KB): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;temp_file_limit&lt;/code&gt;. You’ll be getting errors on such attempts.&lt;/p&gt;

&lt;p&gt;Related &lt;a href=&quot;https://www.pgmustard.com/docs/explain/buffers-temp-written&quot;&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;cheat-sheet&quot;&gt;Cheat sheet&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;work_mem&lt;/code&gt; specifies how much memory you allow each node to use&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_temp_files&lt;/code&gt; boolean to enable logging queries that write temporary files to disk&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;remove_temp_files_after_crash&lt;/code&gt; boolean to let PG remove temp files in case of crashes&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;temp_file_limit&lt;/code&gt; threshold in KB when temp files start getting rejected, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1&lt;/code&gt; == unlimited&lt;/li&gt;
  &lt;li&gt;logging query plans at runtime:
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shared_preload_libraries&lt;/code&gt; should contain &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;auto_explain&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;auto_explain.log_analyze=1&lt;/code&gt; (enabled)&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;auto_explain.log_buffers=1&lt;/code&gt; (enabled)&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;auto_explain.log_min_duration=&amp;lt;any_duration&amp;gt;&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;look for these patterns in query plans to identify writing to temp files (where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt; is number of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;8KB&lt;/code&gt; blocks):
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Disk:&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Buffers: temp written=n&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Buffers: temp read=m written=n&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;examples of operations that could be writing to temp files:
    &lt;ul&gt;
      &lt;li&gt;hash&lt;/li&gt;
      &lt;li&gt;sort&lt;/li&gt;
      &lt;li&gt;CTE scan&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hope this helps! Good luck!&lt;/p&gt;

</description>
            <pubDate>Thu, 17 Jul 2025 22:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2025/07/17/aws-rds-how-to-debug-spilling.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2025/07/17/aws-rds-how-to-debug-spilling.html</guid>
            
            
        </item>
        
        <item>
            <title>Java&apos;s synchronized explained</title>
            <description>&lt;p&gt;There’s a ton of documentation and specifications describing the internal workings of the JVM. However, going through all of that
to simply gain some understanding might be a bit too much. I’ve read those specs and looked inside, so here’s a simple little
explanation of how &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; works in Java.&lt;/p&gt;

&lt;p&gt;Java syntax allows for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; methods and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchroized&lt;/code&gt; blocks (in docs, they call them “statements”).
The idea is that only one thread can execute them at a time, so we can avoid competition for resources etc. etc.&lt;/p&gt;

&lt;h2 id=&quot;monitors&quot;&gt;monitors&lt;/h2&gt;
&lt;p&gt;Synchronized methods and statements look slightly different under the hood.&lt;/p&gt;

&lt;p&gt;Here’s an example of a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; statement:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;normalMethod&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;outside synchronized block&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;synchronized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;inside synchronized block&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here’s the bytecode of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;normalMethod&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; 0: getstatic     #23    // Field java/lang/System.out:Ljava/io/PrintStream;
 3: ldc           #39    // String normal method outside synchronized block
 5: invokevirtual #31    // Method java/io/PrintStream.println:(Ljava/lang/String;)V
 8: aload_0
 9: getfield      #7     // Field a:Ljava/lang/Object;
12: dup
13: astore_1
14: monitorenter
15: getstatic     #23    // Field java/lang/System.out:Ljava/io/PrintStream;
18: ldc           #41    // String normal method inside synchronized block
20: invokevirtual #31    // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: aload_1
24: monitorexit
25: goto          33
28: astore_2
29: aload_1
30: monitorexit
31: aload_2
32: athrow
33: return
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The most interesting part begins when we encounter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; in Java code, which, in the bytecode, starts with the
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorenter&lt;/code&gt; instruction. Before that instruction, the compiler made sure that a reference to our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Object a&lt;/code&gt; is present
on top of the operand stack, so &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorenter&lt;/code&gt; could use it and lock its &lt;strong&gt;monitor&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;What is a monitor? You can think of it as some metadata that every instance has.
Every object has a “monitor” associated with it, and when a thread locks it, other threads must wait until it’s released.
It’s possible to see whether that object’s monitor is locked by simply checking its header.
The object knows: who is the owner, and how many times that owner has obtained that same lock (reentered).
Eventually, the thread must let go of the monitor exactly as many times as it has acquired it.&lt;/p&gt;

&lt;p&gt;In the example above, we use a dummy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Object&lt;/code&gt; to control that only one thread executes the piece of code
inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt;. Alternatively, we can synchronize on a specific instance that we don’t want to access concurrently.
But the rule is, there always must be some object.&lt;/p&gt;

&lt;p&gt;Further in the bytecode, after we’re done with our single-threaded piece of logic, we encounter a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt; instruction.
If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorenter&lt;/code&gt; uses the reference and increments its counter of locks by this thread, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt; works similarly -
it uses the reference and decrements the counter. If a thread tries to release a monitor it does not own, an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;IllegalMonitorStateException&lt;/code&gt; is thrown.&lt;/p&gt;

&lt;p&gt;Did you notice? The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt; instruction appears twice!
Well, while we’re executing some code inside a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; block, we might encounter an exception, which would lead to
us missing a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt; instruction. But because it’s very important to let go of that monitor in any case,
the compiler inserted a piece of logic identical to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; block:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Exception table:
 from    to  target type
    15    25    28   any
    28    31    28   any
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If things don’t go well while we’re in a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; block (lines &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt; - &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;25&lt;/code&gt;), we jump to instruction at line &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;28&lt;/code&gt;,
and proceed with the following set of instructions:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;28: astore_2
29: aload_1
30: monitorexit
31: aload_2
32: athrow
33: return
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Basically: save a reference pointing to the exception, put the reference used for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; onto the stack, use it to
execute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt;, take that exception reference again and throw it using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt;. Done!&lt;/p&gt;

&lt;p&gt;Also, if something goes wrong between lines &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;28&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;31&lt;/code&gt; (the “finally” block), we’ll end up in that same block again.&lt;/p&gt;

&lt;h2 id=&quot;synchronized-methods&quot;&gt;synchronized methods&lt;/h2&gt;
&lt;p&gt;As I mentioned earlier, synchronized methods look a bit different. They don’t have explicit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorenter&lt;/code&gt;
or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;monitorexit&lt;/code&gt; instructions, but internally, the JVM still uses monitors.&lt;/p&gt;

&lt;h3 id=&quot;virtual&quot;&gt;virtual&lt;/h3&gt;
&lt;p&gt;Let’s consider an example of a virtual synchronized method:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;synchronized&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;virtualSyncMethod&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;virtual synchronized method&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here’s the bytecode:&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public synchronized void virtualSyncMethod();
descriptor: ()V
flags: (0x0021) ACC_PUBLIC, ACC_SYNCHRONIZED
Code:
  stack=2, locals=1, args_size=1
     0: getstatic     #23                 // Field java/lang/System.out:Ljava/io/PrintStream;
     3: ldc           #37                 // String virtual synchronized method
     5: invokevirtual #31                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     8: return
  LineNumberTable:
    line 18: 0
    line 19: 8
  LocalVariableTable:
    Start  Length  Slot  Name   Signature
        0       9     0  this   Lorg/example/SyncMethods;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The JVM knows that a method is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; based on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ACC_SYNCHRONIZED&lt;/code&gt; flag. Even though we don’t see any
monitor-something instructions, internally, the JVM still needs an object to coordinate the locking. When the method
is called, some monitor must be locked, and on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;return&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt; instructions, the lock must be released.
The solution is simple: JVM uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; reference, which is the reference to the owner instance.
This means that if a class contains multiple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; methods, and one of these methods is in use, other threads
cannot access any other &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; methods of the same instance. Different instance - no problem.&lt;/p&gt;

&lt;p&gt;In our example, in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LocalVariableTable&lt;/code&gt;, we can see a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; reference, which points to an instance of the class
containing my demo methods, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SyncMethods&lt;/code&gt;. This reference will come in handy for the JVM.&lt;/p&gt;

&lt;h3 id=&quot;static&quot;&gt;static&lt;/h3&gt;
&lt;p&gt;Let’s take a quick look at the same situation, but with a static method:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;synchronized&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;staticSyncMethod&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;static synchronized method&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The bytecode:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static synchronized void staticSyncMethod();
descriptor: ()V
flags: (0x0029) ACC_PUBLIC, ACC_STATIC, ACC_SYNCHRONIZED
Code:
  stack=2, locals=0, args_size=0
     0: getstatic     #23                 // Field java/lang/System.out:Ljava/io/PrintStream;
     3: ldc           #29                 // String static synchronized method
     5: invokevirtual #31                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     8: return
  LineNumberTable:
    line 14: 0
    line 15: 8
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Looks very similar, but of course, it can’t have any kind of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;this&lt;/code&gt; reference because there is no owning instance for this method.
In this case, the JVM uses a reference to the whole class containing the method (for example, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SyncMethods.class&lt;/code&gt;).
That is why, &lt;strong&gt;across all instances&lt;/strong&gt;, two &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;synchronized&lt;/code&gt; methods of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SyncMethods&lt;/code&gt; class can’t be executed 
concurrently by different threads.&lt;/p&gt;

&lt;hr /&gt;
&lt;p&gt;Of course, there are more details about synchronization in the JVM that I didn’t cover, and that was done intentionally
to keep it digestible. If you have any specific feedback or would like to read about a particular topic in the future,
feel free to contact me on &lt;a href=&quot;https://bsky.app/profile/nataliiadziubenko.com&quot;&gt;Bluesky&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks and see you soon!&lt;/p&gt;

&lt;p&gt;References:&lt;br /&gt;
&lt;a href=&quot;https://docs.oracle.com/javase/specs/jvms/se6/html/Instructions2.doc9.html&quot;&gt;monitorenter/monitorexit specs&lt;/a&gt; &lt;br /&gt;
&lt;a href=&quot;https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html&quot;&gt;Intrinsic Locks and Synchronization&lt;/a&gt; &lt;br /&gt;
&lt;a href=&quot;https://docs.oracle.com/javase/specs/jvms/se6/html/Compiling.doc.html#6530&quot;&gt;Synchronization&lt;/a&gt; &lt;br /&gt;
&lt;a href=&quot;https://docs.oracle.com/javase/specs/jvms/se6/html/Threads.doc.html#21294&quot;&gt;Threads and Locks&lt;/a&gt;&lt;/p&gt;

</description>
            <pubDate>Sat, 01 Feb 2025 22:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2025/02/01/javas-synchronized-explained.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2025/02/01/javas-synchronized-explained.html</guid>
            
            
        </item>
        
        <item>
            <title>Postgres: notes from day-to-day engineering</title>
            <description>&lt;p&gt;As a software engineer, I learn something new every day simply by doing my job. This post contains three small tips
that I thought were worth noting down and might be useful for someone, or even for my future self.&lt;/p&gt;

&lt;p&gt;In this post, I talk about Postgres, but I guess these tips would apply similarly to other relational databases.
Beware: there might be traces of AWS here and there :)&lt;/p&gt;

&lt;h3 id=&quot;transaction-locks&quot;&gt;Transaction locks&lt;/h3&gt;
&lt;p&gt;Say we have a table, and we’ve created a unique constraint for the combination of two columns.
Now, let’s imagine we have a query that is trying to insert 10k rows into this table. So far, so good.&lt;br /&gt;
We even specify the conflict resolution policy for this insert: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ON CONFLICT ... DO NOTHING&lt;/code&gt;, so if a conflicting record exists,
we’re still proceeding without an issue. It’s worth mentioning, though, that if a single query tries to insert the same
conflicting record twice, that will result in an error.&lt;/p&gt;

&lt;p&gt;Now, let’s imagine that this insert query runs in multiple concurrent transactions. If, by any chance, there’s a significant
overlap between the rows they are trying to insert… well, the transactions will spend quite some time waiting for each other.&lt;/p&gt;

&lt;p&gt;What is going on? The transaction inserts values into two columns, and the combination of these values must be unique.
Before the transaction can &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DO NOTHING&lt;/code&gt; in case of conflict, it must lock the index to check whether the constraint is
violated in the first place. The other transaction tries to insert the same data, so it wants to lock the same index entry.
It waits until the first transaction releases the lock, so it can lock it afterward and perform the check.&lt;/p&gt;

&lt;p&gt;It’s not a big deal if it happens rarely, but it becomes a problem if the potential overlap between the rows inserted by
different transactions is significant.&lt;/p&gt;

&lt;p&gt;In my case, I needed to upsert the records (insert if they don’t conflict with existing ones, update otherwise).
To deal with this problem, I simply made sure that multiple transactions were not trying
to insert the same data, the challenge being that I couldn’t control this from the point where I received the data.
So, an additional step was necessary: I added an intermediate table without a unique constraint and inserted everything there.
Since I’m in the AWS ecosystem, and the parallel transactions run in the form of concurrent Lambda instances triggered by SQS
messages, I leveraged message groups to ensure that specific data is processed by a single instance at a time.
The transactions were selecting and locking specific sets of data, aggregating them into the target table,
and cleaning them up - all in one go.&lt;/p&gt;

&lt;h3 id=&quot;deadlocks&quot;&gt;Deadlocks&lt;/h3&gt;
&lt;p&gt;Deadlocks occur when your concurrent transactions block each other in a way that they can’t proceed.
Why does this ever happen?
There are many possible scenarios. In our previous example, it could have happened because the transactions are locking
index entries for the unique constraint in the opposite order, causing them to block each other.&lt;/p&gt;

&lt;p&gt;But let’s take a look at a different example, where we have the tables &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rovers&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;locations&lt;/code&gt;.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rovers&lt;/code&gt; table has column &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;location&lt;/code&gt; with a foreign key constraint to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;id&lt;/code&gt; column in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;locations&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;locations&lt;/code&gt; table contains the following data:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;id&lt;/th&gt;
      &lt;th&gt;name&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;Mercury&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;Venus&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;Earth&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;Moon&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;Mars&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;One transaction is trying to insert two records into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rovers&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;INSERT INTO rovers (id, name, location) VALUES
(1, &apos;LRV&apos;, 4),
(2, &apos;Curiosity&apos;, 5);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Another transaction is trying to insert two records at the same time:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;INSERT INTO rovers (id, name, location) VALUES
(1, &apos;Opportunity&apos;, 5),
(2, &apos;LRV&apos;, 4);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Each row that we insert triggers a foreign key validation, so it has to lock the referenced rows in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;locations&lt;/code&gt; table.
First transaction will validate the location ids: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;, and then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;. The other transaction wants to lock the ids in the
opposite order: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;, and then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;.
When the first transaction locks the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;locations&lt;/code&gt; table’s row with id &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;, the second transaction locks id &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;.
The first transaction wants to proceed with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;, but can’t, because it’s already locked by the second transaction.
The second transaction wants to proceed with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;, but also can’t, because it’s locked by the first transaction.&lt;/p&gt;

&lt;p&gt;There are many deadlock scenarios, but usually, they involve mutually attempting to lock resources already locked by other
transactions: rows, indexes… It can involve more than two transactions. Postgres is smart enough to detect when this
happens and roll back a transaction. But that’s not always what we want.&lt;/p&gt;

&lt;p&gt;The deadlock problem can also occur because of inefficient locking, for example, when the whole table is locked rather than
just the specific rows that are needed. This can be solved by adding some indexes, which reduces the probability of a deadlock,
but does not fully eliminate it.&lt;/p&gt;

&lt;p&gt;Probably anyone who has ever dealt with database deadlocks knows one of the most basic cures: &lt;strong&gt;sorting&lt;/strong&gt;.
The problem in our example can be solved by ensuring that all transactions obtain locks in the same order:
before inserting into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rovers&lt;/code&gt;, we can order the records by the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;location&lt;/code&gt; value.&lt;/p&gt;

&lt;p&gt;Sometimes, it’s not that simple. What if the table has two columns with foreign keys referencing the same column?
Deadlocks are sometimes unavoidable with certain constraint choices - something worth considering while designing the
database structure…&lt;/p&gt;

&lt;h3 id=&quot;composite-indexes-and-variance&quot;&gt;Composite indexes and variance&lt;/h3&gt;
&lt;p&gt;This is a small one, and it has to do with multi-column indexes.&lt;/p&gt;

&lt;p&gt;For example, we have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mission_log&lt;/code&gt; table with the columns: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;spacecraft&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;astronaut&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operation&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log&lt;/code&gt; (good examples are hard).
There’s a single spacecraft assigned to a mission, and there are multiple astronauts on a spacecraft, each astronaut
can have multiple tasks or operations on a mission that nobody else will have.&lt;/p&gt;

&lt;p&gt;Let’s say we’ve created a composite primary key on the columns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(spacecraft, astronaut, operation)&lt;/code&gt;.
However, there’s a greater variance of operations than there’s of astronauts, and a greater variance of astronauts
than of spacecrafts.&lt;/p&gt;

&lt;p&gt;To look up a specific &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log&lt;/code&gt;, it’s more efficient to start filtering by the column that
has the greatest variance. This way, we narrow down the lookup a lot faster by filtering by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;operation&lt;/code&gt; first,
rather than by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;spacecraft&lt;/code&gt;. The most efficient way to order the columns in this primary key would be:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(operation, astronaut, spacecraft)&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;There is no such thing as a universal solution to a problem. There are too many shapes and flavors of them, even in the
category of locks alone. These are some very specific use cases that I personally encountered, and yours can differ so significantly that my tips won’t help. However, it’s good to know about these potential problems before they
happen and have some idea of which direction to look in.&lt;/p&gt;

&lt;p&gt;Not all problems are even worth solving.&lt;br /&gt;
And often, too often, it comes down to thinking about your real use cases at the moment of designing the system.&lt;/p&gt;

&lt;p&gt;See you in the next one 😎.&lt;/p&gt;
</description>
            <pubDate>Fri, 24 Jan 2025 22:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2025/01/24/pg-notes-from-day-to-day-engineering.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2025/01/24/pg-notes-from-day-to-day-engineering.html</guid>
            
            
        </item>
        
        <item>
            <title>How JVM handles exceptions</title>
            <description>&lt;p&gt;&lt;a href=&quot;url&quot;&gt;&lt;img src=&quot;/assets/images/thumbnails/try-catch-finally.png&quot; width=&quot;600&quot; height=&quot;auto&quot; style=&quot;border-radius:2%&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s interesting to know how the JVM runs bytecode instructions… But do you know what is going on when an exception is thrown? How does the JVM handle the delegation of control? What does it look like in the bytecode?&lt;/p&gt;

&lt;p&gt;Let me quickly show you!&lt;/p&gt;

&lt;h3 id=&quot;example&quot;&gt;example&lt;/h3&gt;
&lt;p&gt;Here’s a simple bit of Java code that includes all the important actors in the exception-throwing game (try-catch-finally):&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// to make it less boring, let&apos;s have some branching logic&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Exception&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Exception message!&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Exception&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;doSomethingOnException&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;finally&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;doSomethingFinally&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;exception-table&quot;&gt;exception table&lt;/h3&gt;
&lt;p&gt;The resulting bytecode includes an interesting section in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Code&lt;/code&gt; attribute called the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Exception table&lt;/code&gt;. Each method can have its own exception table, and it’s only present when relevant. If there is no exception-handling logic in the method, it won’t have an exception table.&lt;/p&gt;

&lt;p&gt;This is how the exception table looks like for our example:&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  Exception table:
     from    to  target type
         2    16    22   Class java/lang/Exception
         2    16    32   any
        22    26    32   any
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The numbers point to the addresses of the bytecode instructions. Each line in this table shows a range of bytecode instructions (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;from&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;to&lt;/code&gt;) that is guarded by an exception handler. The handler itself is also just a set of bytecode instructions, and the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;target&lt;/code&gt; column points to the address where the handling code starts. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;type&lt;/code&gt; simply means the type of exception that can be handled by the specified handler.&lt;/p&gt;

&lt;h3 id=&quot;bytecode-instructions&quot;&gt;bytecode instructions&lt;/h3&gt;
&lt;p&gt;To see what exactly these addresses are pointing to, let’s take a look also at the set of method’s bytecode instructions (explanation below):&lt;/p&gt;
&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; 0: iconst_0
 1: istore_0
 2: iload_0
 3: ifne          16
 6: new           #12      // class java/lang/Exception
 9: dup
10: ldc           #14      // String Exception message!
12: invokespecial #16      // Method java/lang/Exception.&quot;&amp;lt;init&amp;gt;&quot;:(Ljava/lang/String;)V
15: athrow
16: invokestatic  #19      // Method doSomethingFinally:()V
19: goto          38
22: astore_1
23: invokestatic  #22      // Method doSomethingOnException:()V
26: invokestatic  #19      // Method doSomethingFinally:()V
29: goto          38
32: astore_2
33: invokestatic  #19      // Method doSomethingFinally:()V
36: aload_2
37: athrow
38: return
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let me walk you through.&lt;/p&gt;

&lt;p&gt;Instructions &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; - &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; are responsible for creating a variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;int a = 0;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then, we have an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ifne&lt;/code&gt;, which is a conditional jump, with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;16&lt;/code&gt; being an address where to jump. If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; is not equal to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;, we jump to instruction at the address &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;16&lt;/code&gt;. There, we find the contents of our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; block, followed by a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;goto&lt;/code&gt; instruction pointing to the end of the method.&lt;/p&gt;

&lt;p&gt;If the condition is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, we continue onto the next instruction. Instructions &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;6&lt;/code&gt; - &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;12&lt;/code&gt; handle the creation of an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Exception&lt;/code&gt; instance.
Note that the reference to this instance is duplicated, so by the end of this set of instructions, it appears twice on the operand stack.&lt;/p&gt;

&lt;p&gt;The instruction at the address &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt;, is responsible for actually throwing the exception! It “eats” one of the references to our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Exception&lt;/code&gt; instance from the operand stack, which tells it which exception to throw. In fact, it clears the whole stack, leaving only a single reference to the exception on top.&lt;/p&gt;

&lt;p&gt;When the JVM encounters &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt; instruction, it checks the method’s exception table in order to find the appropriate location to continue execution.&lt;/p&gt;

&lt;h3 id=&quot;try-catch-finally-flow&quot;&gt;try-catch-finally flow&lt;/h3&gt;
&lt;p&gt;Let’s take another look at the exception table now that we have more context.&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  Exception table:
     from    to  target type
         2    16    22   Class java/lang/Exception
         2    16    32   any
        22    26    32   any
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We encountered &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt; at address &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;15&lt;/code&gt;. This address is covered by the first two lines of the table, as it falls within the range [&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;16&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Why two handlers? One is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; block (target points to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;22&lt;/code&gt;, where the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; logic starts), and the other is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; block (target &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;32&lt;/code&gt; is pointing to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; logic).
The third line of this table covers the range of instructions containing our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; logic, and the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;target&lt;/code&gt; points to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; block. This means that if anything happens during the execution of a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; block, we still want to end up in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; block.&lt;/p&gt;

&lt;p&gt;When we are in a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; block (address &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;22&lt;/code&gt;), something from the operand stack is stored into a variable. We had an extra reference to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Exception&lt;/code&gt; instance on our stack, remember? Here, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;astore&lt;/code&gt; instruction saves it as a variable. Internally, a variable doesn’t have a name, but logically, this is our variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;e&lt;/code&gt;, which we can use in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; block to log it or do anything else with it.&lt;/p&gt;

&lt;h3 id=&quot;less-nice-flow&quot;&gt;less nice flow&lt;/h3&gt;
&lt;p&gt;This was a “nice” flow. The JVM looked into the exception table and found a handler that knew what to do with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Exception&lt;/code&gt;. If there was only a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handler, that wouldn’t have been enough.&lt;/p&gt;

&lt;p&gt;How does the JVM know if it’s a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; or a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handler? We can see that a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;type&lt;/code&gt; column for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handler contains &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;any&lt;/code&gt; type, meaning that it should be executed in any case, regardless of whether an exception is thrown. If an actual type is specified instead, it’s a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler. The type that the JVM is looking for is an exact type of the exception or its supertype.&lt;/p&gt;

&lt;p&gt;What if there is no appropriate handler? In that case, the JVM stops execution of the current frame and returns to the previous frame (to the method that called the current method). It continues going to the previous frames until it finds an appropriate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler for the given exception. Note that if it finds a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handler which is applicable by address range, it will execute it on the way too. If there is no &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler all the way through the stack, the JVM terminates the thread and prints out the stacktrace.&lt;/p&gt;

&lt;h3 id=&quot;summarized-flow&quot;&gt;summarized flow&lt;/h3&gt;
&lt;p&gt;The try-catch-finally mechanism can be summarized as follows:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt; instruction tells the JVM that an exception is thrown. Which exception? The one that’s on top of the operand stack.&lt;/li&gt;
  &lt;li&gt;When this happens, the JVM checks the exception table of this particular method. Given the address of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;athrow&lt;/code&gt; instruction, it can find the address of appropriate handler(s).&lt;/li&gt;
  &lt;li&gt;If a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler is found (the handler that has a correct exception type in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;type&lt;/code&gt; column), the reference to the exception is saved from the stack as a variable. Then, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; logic is executed.&lt;/li&gt;
  &lt;li&gt;If a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handler is found, it’s executed.&lt;/li&gt;
  &lt;li&gt;If no appropriate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler is found, the JVM terminates execution of the current frame and looks for a handler in the previous frame.&lt;/li&gt;
  &lt;li&gt;The JVM goes through all frames until it finds a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt; handler, executing any &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally&lt;/code&gt; handlers that it finds along the way.&lt;/li&gt;
  &lt;li&gt;If no handler is found, the program’s execution is terminated.
&lt;img src=&quot;/assets/images/supplies/exceptions-flow.png&quot; alt=&quot;try-catch-finally flow&quot; /&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s it for now!
See you in the next nerding session 🤓&lt;/p&gt;
</description>
            <pubDate>Sun, 15 Dec 2024 22:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/12/15/how-jvm-handles-exceptions.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/12/15/how-jvm-handles-exceptions.html</guid>
            
            
        </item>
        
        <item>
            <title>First months at Azul: how is it going?</title>
            <description>&lt;p&gt;It’s been over three months now since I started working at Azul. Everyone keeps telling me, “you’re in the right place,”
and I can’t agree more! I feel like I can use my skills and experience as a backend engineer, and also combine it with
the subject of my curiosity and strong interest — JVM internals.&lt;/p&gt;

&lt;p&gt;So, what am I doing, and how has it been going so far?&lt;/p&gt;

&lt;h3 id=&quot;the-team&quot;&gt;the team&lt;/h3&gt;
&lt;p&gt;Many know Azul as one of the vendors that provide JDK distributions (except Brazilians — they keep telling me it’s an
airline 😃). Well, JDKs are not the only thing Azul provides. For example, there’s also an &lt;a href=&quot;https://www.azul.com/products/intelligence-cloud/&quot;&gt;Intelligence Cloud&lt;/a&gt;
that performs analysis of Java applications at runtime and reports things like used components, vulnerabilities,
and more. I’ve joined the Intelligence Cloud team as a backend engineer. :)&lt;/p&gt;

&lt;p&gt;The team consists of really cool engineers, and I’m learning a lot from them. We work remotely, distributed around
the world. In order for us to get to know each other, we’ve actually met in person — which was pretty cool!&lt;/p&gt;

&lt;p&gt;Here’s an attempt to explain how Intelligence Cloud works without making it a marketing speech.&lt;/p&gt;

&lt;h3 id=&quot;the-idea&quot;&gt;the idea&lt;/h3&gt;
&lt;p&gt;Why analyze at runtime? Sure, you can do the vulnerability detection without any runtime information. As a result, you’ll
know which vulnerabilities are present in your codebase and which have the highest scores, so you can
immediately jump into fixing them. However, are these vulnerabilities even located in the code that your application is
actually using? Runtime analysis can answer this question and help prioritize the problems that are truly threatening right
now — and this is what Azul Vulnerability Detection does.&lt;/p&gt;

&lt;p&gt;Also, by collecting runtime information, it’s possible to see exactly when you were using certain classes or methods.
Or maybe they’re never used? In your source code, it may still look like something is calling this code, but maybe the
caller (together with the whole legacy flow) can be removed entirely. So these are the things that Code Inventory reports
try to address, and right now I’m mostly involved with this initiative.&lt;/p&gt;

&lt;p&gt;These are just two examples, and there are more, which work on a similar principle.&lt;/p&gt;

&lt;h3 id=&quot;the-principle&quot;&gt;the principle&lt;/h3&gt;
&lt;p&gt;In a nutshell, you run your applications in your environment as usual. If you’re using a non-Azul JVM, you’ll need to
run it with an agent, which sends out the JVM events that are used for analysis. All events from all your
runtimes go to the backend through Forwarder, another app that you run in your environment. Only Forwarder needs to be
able to talk to the outside world.
Our backend sits in AWS. There, we analyze the events, keep the data, and provide the reports through the API or Web UI.&lt;/p&gt;

&lt;p&gt;I think one of the most interesting parts of the flow is how the agent works. It does a lot of magic in order to track
the events that are interesting for the analysis. Even though I’m not working on the agent side, I often poke my nose
into their work, and sometimes brainstorm with them. This is where understanding JVM internals is really helpful.&lt;/p&gt;

&lt;h3 id=&quot;some-things-that-ive-learned&quot;&gt;some things that I’ve learned&lt;/h3&gt;
&lt;p&gt;This section is highly subjective and messy — please bear with me.&lt;/p&gt;

&lt;h4 id=&quot;aws&quot;&gt;AWS&lt;/h4&gt;
&lt;p&gt;This is actually my first experience with AWS. Some things are nice, and some are painful for me personally.&lt;/p&gt;

&lt;p&gt;For example, CloudWatch is difficult to use, problems are hard to debug (keep forgetting, where was that logging hidden
again?). To see why a Lambda has failed, you have to go through a labyrinth of monitors. It’s not the same as
just going to a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Log&lt;/code&gt; tab, guess I’m spoiled.&lt;/p&gt;

&lt;p&gt;Lambdas can be nice for the infancy of the project, but become painful as the project matures. To give you an example,
a Lambda can run for up to 15 minutes, and that limit can’t be increased.&lt;/p&gt;

&lt;p&gt;Navigating the platform in general is still difficult for me, but I’m getting used to it.&lt;/p&gt;

&lt;p&gt;Estimating the costs of different options becomes a routine exercise, and that feels… new.&lt;/p&gt;

&lt;h4 id=&quot;postgresql&quot;&gt;PostgreSQL&lt;/h4&gt;
&lt;p&gt;So much Postgres! At the start of my career, I worked on a product that was more than half written in PL/SQL, so I was
overly confident in my SQL skills for some reason. But here, I’ve seen some really cool things you can do with SQL.
I haven’t used such a rich SQL syntax before, and it’s been a while since I’ve seen people actually looking at the query plans
and taking query optimization seriously.&lt;/p&gt;

&lt;p&gt;In summary, SQL is rich and beautiful, PostgreSQL is cool (and can handle a lot) 💙&lt;/p&gt;

&lt;h4 id=&quot;code-quality--performance&quot;&gt;code quality &amp;amp; performance&lt;/h4&gt;
&lt;p&gt;I once submitted a PR to a known open-source project which was doing a lot of JVM-internal stuff… and was written
in Java. But that Java didn’t always look like Java, because it was using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UNSAFE&lt;/code&gt;, allocating memory, taking safepoints
into account… You know, it felt like C written in Java :)&lt;/p&gt;

&lt;p&gt;That PR took months of slow implementation, when at times I wasn’t sure I’d be able to make it work at all. Then, it took
three months of reviewing (and fixing) but didn’t get merged, because there was so much more than just “making it work”
or even “making it work right”. There was more of making it work perfectly, and superfast, which might involve techniques
that you don’t commonly see, but when performance is crucial, devs get creative.&lt;/p&gt;

&lt;p&gt;I’ve never worked in that domain before. In the domains where I worked, they just brought more servers in when necessary.&lt;/p&gt;

&lt;p&gt;It’s not exactly the same in that sense in my current team, because here I’m a backender, and things are a bit more
familiar. But the feeling of measuring each and every inch of performance is still there. This is the place where the
code reviews are not just a formality. They become brainstorms, they involve a lot of research and a lot of effort.
It’s cool to train the code quality muscle and see how it actually matters.&lt;/p&gt;

&lt;h4 id=&quot;jvm--the-java-community&quot;&gt;JVM &amp;amp; The Java Community&lt;/h4&gt;
&lt;p&gt;Last, but not least, I’ve learned a lot about JVMs — to the point that I finally realize how little I know.&lt;/p&gt;

&lt;p&gt;Now that my passion is my actual job, I find myself sharing less about it publicly. There are so many cool solutions
that I see every day, but unfortunately I can’t make a deep dive into those. I thought my usual deep dive format was an
expectation that everyone had from this blog, but in reality, it was my own expectation.&lt;/p&gt;

&lt;p&gt;I’ve learned that to contribute to the Java community, I don’t necessarily need to dig through pages and pages of
JVM specs. I can share exciting findings, interesting learnings, all things Java, but also beyond, into a broader
perspective. So let’s try that!&lt;/p&gt;

&lt;p&gt;Thank you for reading! I hope you found this interesting and got something for yourself from it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;P.S.: There’s a little kid in me that is making a comic story about debugging (because why not?). The story is still
in progress at the moment of writing, but will keep updating until it’s finished, so if you’re curious:
&lt;a href=&quot;/comics/debugging_underworld/&quot;&gt;Debugging Underworld&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
            <pubDate>Fri, 22 Nov 2024 10:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/11/22/azul-3-months.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/11/22/azul-3-months.html</guid>
            
            
        </item>
        
        <item>
            <title>Java Integer Caching: why and how</title>
            <description>&lt;p&gt;As Java developers, we know that we shouldn’t compare objects using the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;==&lt;/code&gt; operator because this way we compare the
references and not the actual values. That would also apply to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; objects:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This result can surprise nobody.&lt;/p&gt;

&lt;p&gt;However, Java has a little trick for us:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;127&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;127&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;what-is-going-on&quot;&gt;what is going on?&lt;/h3&gt;

&lt;p&gt;We are observing a mechanism called Integer Caching, which is one of the tricks that Java has for us in order to improve
performance and memory usage.&lt;/p&gt;

&lt;p&gt;Normally, when we create an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; object, we claim some space on the heap and put the object there —
for example, with the value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256&lt;/code&gt;. When we create another &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; object with the same value, we allocate some more space
on the heap and put there another &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; with value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256&lt;/code&gt;, even though such an object was already created previously.&lt;/p&gt;

&lt;p&gt;The idea behind Integer Caching is that certain small integer values are used a lot more often than others.
For example, we often use small integers as default values, counters etc. We could argue that they are usually primitives,
but often primitives are wrapped into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; objects, for example if we store them in a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;List&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; class is loaded, Java caches all &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; objects with values in range &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-128, 127]&lt;/code&gt; inclusive.
Every time we create an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; object, Java checks for us if this value is within the range, and if so, it’s not allocated
but taken from the cache instead.&lt;/p&gt;

&lt;p&gt;Two things are achieved this way:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;our application becomes faster because it doesn’t need to do all the work for extra value allocation;&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;potentially&lt;/em&gt;, less space is used because these values are stored only once.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;how-does-this-happen-exactly&quot;&gt;how does this happen exactly?&lt;/h3&gt;

&lt;p&gt;This simple piece of code &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer x = 127;&lt;/code&gt; is going to become the following in the bytecode:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; 0: bipush        127
 2: invokestatic  #7     // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
 5: astore_1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;First operation is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bipush&lt;/code&gt;, meaning that we take the byte value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;127&lt;/code&gt; and put it onto the operand stack as an integer.
Next, we see &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;invokestatic&lt;/code&gt;, which calls a static method &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer.valueOf&lt;/code&gt; that accepts a primitive &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;int&lt;/code&gt; value and
returns an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; object.
Finally, there is an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;astore&lt;/code&gt;, which simply stores the resulting value as a variable.&lt;/p&gt;

&lt;p&gt;What is the most interesting for us is that during compilation with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;javac&lt;/code&gt;, the code&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;127&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;is converted into&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;valueOf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;127&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The range checks are happening inside of that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer.valueOf&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;This is how it looks:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// IntegerCache.low = -128;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// IntegerCache.high = 127;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;valueOf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IntegerCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;low&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IntegerCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;high&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;IntegerCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(-&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;IntegerCache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;low&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The cache itself is a trivial array of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt;, and it’s populated when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; class is loaded.&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Since it’s a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;static final&lt;/code&gt; array, it’s kept around for as long as the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; class is loaded, so pretty much for
the lifetime of your application.&lt;/p&gt;

&lt;h3 id=&quot;what-if-this-range-is-insufficient&quot;&gt;what if this range is insufficient?&lt;/h3&gt;

&lt;p&gt;If you know you have a specific use-case where you’re often reusing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; values of a bigger range, say &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-1000, 1000]&lt;/code&gt;,
you can ask Java to cache a different range for you.
This can be achieved by running your app with a flag: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-XX:AutoBoxCacheMax=1000&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With all the benefits described above, one might wonder: why not cache more values by default, or even all of them?
Performance wins, less space is taken, so why not?&lt;/p&gt;

&lt;p&gt;Well, if we imagine caching the whole range of integers, it would result in storing over 4 billion objects!
They are not garbage collected, so we will have this large space occupied permanently. JVM will have difficulties managing
it efficiently. In summary, the cost of having such an enormous cache defeats the memory and performance benefits gained from it.&lt;/p&gt;

&lt;h3 id=&quot;summary&quot;&gt;summary&lt;/h3&gt;

&lt;p&gt;Java does a lot of things that are designed to sneakily improve performance and memory usage, and the Integer Cache is one of them.
A small range of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Integer&lt;/code&gt; objects (the ones that are considered frequently used) is stored all the time,
so we don’t need to reallocate these objects again and again. The range is small, so it doesn’t occupy too much space and
overwhelm the JVM.&lt;/p&gt;
</description>
            <pubDate>Sun, 13 Oct 2024 10:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/10/13/Java-integer-caching-how-and-why.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/10/13/Java-integer-caching-how-and-why.html</guid>
            
            
        </item>
        
        <item>
            <title>I won’t let Java confuse you #5: let&apos;s talk lambdas</title>
            <description>&lt;p&gt;Lambdas are interesting structures. What are they exactly? And why can’t we use non-final local variables in
lambda bodies?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Welcome back to the Java-unconfusing series! It’s our safe place to take a look at simple pieces of Java
code that don’t always behave exactly as we expect. We look under the hood in order to understand why
Java does what it does, so we are never confused again.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;context&quot;&gt;Context&lt;/h3&gt;
&lt;p&gt;Years ago, when we were only starting to use the &lt;a href=&quot;https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/package-summary.html&quot;&gt;Streams API&lt;/a&gt;
in Java, it took some time to switch the mindset and properly use the new approach.&lt;/p&gt;

&lt;p&gt;For example, in our lambda, we might have tried modifying a variable defined outside the lambda body,
which wasn’t possible. But why?&lt;/p&gt;

&lt;h3 id=&quot;what-are-lambdas&quot;&gt;What are lambdas&lt;/h3&gt;
&lt;p&gt;Suppose we have a method that accepts a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&amp;lt;Object&amp;gt;&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Supplier&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&lt;/code&gt; is one of the &lt;strong&gt;functional interfaces&lt;/strong&gt;. Functional interface is an interface that has one
unimplemented method. In this case, it’s a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get&lt;/code&gt; method, which doesn’t accept any arguments and returns an &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Object&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When we are writing a lambda, we are essentially writing an implementation of the specific functional
interface expected in the context.
So, the lambda like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;() -&amp;gt; 1&lt;/code&gt;, when provided to our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lambdaFun&lt;/code&gt; method, is considered as an implementation
of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&amp;lt;Object&amp;gt;&lt;/code&gt;, because that’s what &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lambdaFun&lt;/code&gt; expects.&lt;/p&gt;

&lt;p&gt;Depending on expected type, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;() -&amp;gt; 1&lt;/code&gt; can be a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&amp;lt;Integer&amp;gt;&lt;/code&gt; or even a custom type that we define
ourselves. Everything depends on the context.&lt;/p&gt;

&lt;h3 id=&quot;annoying-lambda-use-case&quot;&gt;Annoying lambda use-case&lt;/h3&gt;
&lt;p&gt;Let’s take a look at this code:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;});&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In this case, the compiler will give us the following error: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Variable used in lambda expression should be
final or effectively final&lt;/code&gt;. What does that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;effectively final&lt;/code&gt; even mean?&lt;/p&gt;

&lt;h3 id=&quot;what-is-effectively-final&quot;&gt;What is “effectively final”&lt;/h3&gt;

&lt;p&gt;The Java compiler does a lot of smart things during compilation. It can analyse the use of variables in
certain use-cases to determine if they are constant. The variable might not even be marked as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;final&lt;/code&gt;.
If it’s defined within a method body, then nothing from outside can modify this variable.
Then compiler only needs to check if it’s modified anywhere inside, and if it’s not, the compiler can safely conclude
that the variable is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;effectively final&lt;/code&gt;, in other words a constant value.&lt;/p&gt;

&lt;h3 id=&quot;why-is-that-a-problem-for-lambdas&quot;&gt;Why is that a problem for lambdas&lt;/h3&gt;

&lt;p&gt;Lambdas don’t allow the use of any variables from outside the lambda body if those variables are not
“final or effectively final”. It means they can use variables read-only. Why is that?&lt;/p&gt;

&lt;p&gt;Remember, when we write a lambda body, we’re implementing a functional interface? So, in our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&lt;/code&gt;
case, we’re saying: this is the body of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get&lt;/code&gt; method of that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&lt;/code&gt; interface implementation
that is magically created “in the air”.&lt;/p&gt;

&lt;p&gt;Let me explain.&lt;/p&gt;

&lt;p&gt;When we compile our code, under the hood a new separate method is created.
Say we have this code:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;() -&amp;gt; x&lt;/code&gt; becomes a method body, and in the bytecode this becomes a separate method named
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lambda$test$0&lt;/code&gt;, generated by the compiler, we can see it in the bytecode:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;private static java.lang.Object lambda$test$0(int);
descriptor: (I)Ljava/lang/Object;
flags: (0x100a) ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC
Code:
  stack=1, locals=1, args_size=1
     0: iload_0
     1: invokestatic  #28                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
     4: areturn
  LineNumberTable:
    line 7: 0
  LocalVariableTable:
    Start  Length  Slot  Name   Signature
        0       5     0     x   I
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The synthetic class that actually implements the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Supplier&lt;/code&gt; interface and uses this method as implementation
is generated later, at runtime. And then the actual instance is created.
It happens only in the case when the lambda is actually hit, saving up resources when it’s not.&lt;/p&gt;

&lt;p&gt;So, why can’t we normally use outer variables in our lambdas? Simply, because internally lambdas are little methods.
Any local variable that they can access, is passed to them (captured) as a method argument.
Inside a lambda body, we are viewing a copied value and not an actual variable.&lt;/p&gt;

&lt;h3 id=&quot;still-why-so-final&quot;&gt;Still, why so final?&lt;/h3&gt;

&lt;p&gt;It’s easy to see why the local variable defined outside can’t be modified inside the lambda body.
But why does it have to be final, in a sense that even after a lambda definition or even execution it can’t be modified?&lt;/p&gt;

&lt;p&gt;Let’s imagine this limitation doesn’t exist.&lt;/p&gt;

&lt;p&gt;We might want to define a lambda, then try and modify a variable that it uses.
The variable value is &lt;em&gt;actually&lt;/em&gt; captured at the moment when lambda is &lt;strong&gt;executed&lt;/strong&gt;,
so all changes between definition and execution should be taken into account.
After execution, no changes are visible to lambda, since it has already entered its
own stack with its own variable copy.&lt;/p&gt;

&lt;p&gt;This all might look really confusing to a developer.
The syntax makes us think that the values are captured at lambda definition, but that’s not true.&lt;/p&gt;

&lt;p&gt;We also need to prevent an expectation, that the changes to a variable after lambda
execution are visible in the lambda body. They can’t be.&lt;/p&gt;

&lt;p&gt;It becomes especially important in a multithreaded environment. We might want to execute a lambda in a new
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Thread&lt;/code&gt;, and modify the variable at the moment that looks to us like “after the lambda execution”.
But can we be so sure?
Did our new &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Thread&lt;/code&gt; already start and execute our lambda when we modified the variable?
Which value will actually be captured, the old one, or the amended one?&lt;/p&gt;

&lt;p&gt;Given all of the above, compiler is protecting us from confusions and wrong expectations.&lt;/p&gt;

&lt;h3 id=&quot;what-about-fields&quot;&gt;What about fields?&lt;/h3&gt;

&lt;p&gt;You might have noticed that there is no problem in reading and modifying the &lt;strong&gt;fields&lt;/strong&gt; from our lambdas.
Unlike a local variable, which exists with a certain state in a specific method frame, the field is visible
to all class members, in all the methods of the class, independent of any frame states.
As we remember, lambda body becomes a separate method under the hood. If the field is used in the lambda body,
it is not captured as an argument to that method. Instead, the method can read and overwrite that field
directly, just as any normal method can do.&lt;/p&gt;

&lt;p&gt;That is easy, when the field and the method are located in the same class.
Perhaps, we would like to use a reference to an external method in our lambda instead of generating one in
the bytecode? For example, like this:&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;Stream&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;of&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;forEach&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Then indeed no new method is created at compile time, and instead we will have an existing method
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;System.out.println()&lt;/code&gt; as our functional interface implementation.
However, the syntax wouldn’t allow us to pass any fields to the method reference, which the external method
might not even be able to access.&lt;/p&gt;

&lt;h3 id=&quot;lets-play&quot;&gt;Let’s play&lt;/h3&gt;

&lt;p&gt;Digging through &lt;a href=&quot;https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.22&quot;&gt;JLS&lt;/a&gt;
(the Java Language Specification), I stumbled upon a couple of interesting examples of lambda bodies
using local variables.&lt;/p&gt;

&lt;p&gt;Let’s have a look.&lt;/p&gt;

&lt;h4 id=&quot;1&quot;&gt;#1&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In this example, both &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; are “effectively final”. They are defined within the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m1&lt;/code&gt; method
(guaranteed to not be modified from outside). &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; gets a value when the method &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m1&lt;/code&gt; is called, and
it’s never modified afterward, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is also initialized only once.&lt;/p&gt;

&lt;h4 id=&quot;2&quot;&gt;#2&lt;/h4&gt;

&lt;p&gt;What about this one?&lt;/p&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is only initialized once, so it’s still effectively final. We’re good.&lt;/p&gt;

&lt;h4 id=&quot;3&quot;&gt;#3&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is initialized conditionally, in proper terms they call it &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;not definitely assigned&lt;/code&gt;.
We can’t use an uninitialized variable because then there’s no value for our lambda to capture (to feed
it as an argument into a method created under the hood). That won’t compile!&lt;/p&gt;

&lt;h4 id=&quot;4&quot;&gt;#4&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We do have a conditional assignment to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt;, but it’s guaranteed that in any condition there will be
&lt;em&gt;something&lt;/em&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;else&lt;/code&gt; covers all possible cases). There will be for sure some value that’s going to be
assigned to it once and only once. We’re good!&lt;/p&gt;

&lt;h4 id=&quot;5&quot;&gt;#5&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here we have a possibility that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; gets reassigned, meaning that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is not effectively final.
Won’t compile!&lt;/p&gt;

&lt;h4 id=&quot;6&quot;&gt;#6&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m6&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Even though &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; is modified after our lambda definition, it still means that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; is not effectively final.
Won’t compile!&lt;/p&gt;

&lt;h4 id=&quot;7&quot;&gt;#7&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m7&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Won’t compile either: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; is attempted to be modified within lambda body.&lt;/p&gt;

&lt;h4 id=&quot;8&quot;&gt;#8&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m8&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;What about this one? &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; is not having any value, so it can’t be captured by lambda.
And then, we are trying to modify it within the lambda body. None of that is going to work…&lt;/p&gt;

&lt;h4 id=&quot;9&quot;&gt;#9&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m9&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here, on each iteration we are creating new instance of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;String&lt;/code&gt;. Each of these instances is definitely
assigned a value, and it is guaranteed to happen only once. Everything is alright!&lt;/p&gt;

&lt;h4 id=&quot;10&quot;&gt;#10&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[]&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;]);&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Unlike in the previous example, here we are reusing the same variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; and modifying its value by
incrementing it on each iteration. Variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i&lt;/code&gt; is not effectively final, so this won’t work.&lt;/p&gt;

&lt;h4 id=&quot;11&quot;&gt;#11&lt;/h4&gt;

&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;m11&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lambdaFun&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I know, it looks like we are not changing the value of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y&lt;/code&gt; here, yet the value is getting overwritten,
meaning that the variable is not effectively final. This won’t compile!&lt;/p&gt;

&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Lambdas are interesting structures. But we can get a feeling of how they are going to behave simply by
realizing one thing: lambda body is, or becomes, a separate method. Any local variables
that we use in the lambda body are captured as method arguments, so we can access only the copies
of the values. Our compiler protects us, so we can’t use non-final local variables in our lambdas.&lt;/p&gt;

&lt;p&gt;Hope this was educative and fun! Here are the related &lt;a href=&quot;https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.22&quot;&gt;docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you liked this little post, take a look at the previous posts from the series:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/05/09/I-wont-let-Java-confuse-you-4.html&quot;&gt;Unreachable statements&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/05/01/I-wont-let-Java-confuse-you-3.html&quot;&gt;Widening&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/25/I-wont-let-Java-confuse-you-2.html&quot;&gt;Expressions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/16/I-wont-let-Java-confuse-you-1.html&quot;&gt;String operator &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/07/I-wont-let-Java-confuse-you-0.html&quot;&gt;Increment&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
            <pubDate>Sun, 30 Jun 2024 10:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/06/30/I-wont-let-Java-confuse-you-5.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/06/30/I-wont-let-Java-confuse-you-5.html</guid>
            
            
        </item>
        
        <item>
            <title>I won’t let Java confuse you #4: unreachable statements</title>
            <description>&lt;p&gt;Do you think Java consistently rejects all unreachable code? Well…&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Welcome back to the Java-unconfusing series! Usually here we take a look at the pieces of code which may look really
innocent, but not work as we expect. Or not compile at all. It’s good to dive into the reasons why it is a certain way,
so we can learn more about Java ideology and design decisions.
Let’s get unconfused together!&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;lets-talk-about-unreachable-statements&quot;&gt;Let’s talk about unreachable statements&lt;/h3&gt;
&lt;p&gt;There are a number of different use-cases when the code is considered &lt;em&gt;unreachable&lt;/em&gt;. The compiler doesn’t accept this
code. Examples include statements that follow &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;break&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;return&lt;/code&gt;, or infinite &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while(true)&lt;/code&gt; loops, for example.
We have all seen these.&lt;/p&gt;

&lt;p&gt;Let’s take a look at this particular example:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The compiler tells us that the loop condition is always &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, and that makes the loop body unreachable. Makes sense
that it doesn’t compile.&lt;/p&gt;

&lt;p&gt;What about the following example?&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The condition is always &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, which means that the body can never be executed. However, this piece of code
is accepted by the compiler! Technically, the Java compiler doesn’t even consider it ‘unreachable’.&lt;/p&gt;

&lt;h3 id=&quot;why-is-it-so&quot;&gt;Why is it so?&lt;/h3&gt;
&lt;p&gt;This choice has been made consciously.
When the condition is a constant &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; value, the compiler doesn’t add the contents of the entire conditional block to
the resulting set of the bytecode instructions. This allows developers to define flags such as:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;boolean&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;FEATURE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;And then use it in a condition.&lt;/p&gt;

&lt;p&gt;Later on, it’s easy to change the value of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FEATURE&lt;/code&gt; flag to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, but there’s one important detail to it. If the
flag itself and the conditional block are located in different classes, it’s important to recompile the class containing
the condition, since the whole new set of instructions might be added to the bytecode.&lt;/p&gt;

&lt;h3 id=&quot;when-is-it-so&quot;&gt;When is it so?&lt;/h3&gt;
&lt;p&gt;Coming back to our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;while (false)&lt;/code&gt; example, such behaviour is only happening when the condition is a &lt;strong&gt;constant&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt; value.&lt;/p&gt;

&lt;p&gt;So, this would work without any issue:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;While this wouldn’t compile:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The reason is that the compiler is performing optimisation called ‘constant folding’. All known (constant) values can be
used in order to pre-calculate anything where possible. If the values are constant, the assumptions can be safely made,
but not otherwise.&lt;/p&gt;

&lt;p&gt;So, in the example above, the compiler knows that our actual condition is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10 + 10 &amp;lt; 10&lt;/code&gt;, and it is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, and it can’t be
changed from anywhere else in the code. So it is safe to conclude that the code is invalid.&lt;/p&gt;

&lt;h3 id=&quot;crazy-thoughts&quot;&gt;Crazy thoughts&lt;/h3&gt;
&lt;p&gt;Curious minds might wonder: if &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if (false) {}&lt;/code&gt; block contents are not placed into the bytecode at all, does it mean that
the compilation of that block is skipped entirely? So any nonsense inside that block would not result in a compile error?
The answer is no. The compiler still diligently does its work and reports any compile errors within that block.&lt;/p&gt;

&lt;p&gt;Hope this was educative and fun! Here are the related &lt;a href=&quot;https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.22&quot;&gt;docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you liked this little post, take a look at the previous posts from the series:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/05/01/I-wont-let-Java-confuse-you-3.html&quot;&gt;Widening&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/25/I-wont-let-Java-confuse-you-2.html&quot;&gt;Expressions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/16/I-wont-let-Java-confuse-you-1.html&quot;&gt;String operator &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/07/I-wont-let-Java-confuse-you-0.html&quot;&gt;Increment&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
            <pubDate>Thu, 09 May 2024 10:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/05/09/I-wont-let-Java-confuse-you-4.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/05/09/I-wont-let-Java-confuse-you-4.html</guid>
            
            
        </item>
        
        <item>
            <title>I won’t let Java confuse you #3: widening</title>
            <description>&lt;p&gt;Welcome to the fourth episode of our Java-unconfusing series, where we look at some basic concepts in Java (in fact, it applies to many other languages too)
that result in confusing outcomes in certain cases. When that happens, most likely the code quality could do with some improvements.
In any case, it’s good to know what we can expect from Java and never be confused by it.&lt;/p&gt;

&lt;p&gt;Today, I would like to talk about ‘widening’…&lt;/p&gt;

&lt;h3 id=&quot;example&quot;&gt;Example&lt;/h3&gt;
&lt;p&gt;Assume we have two &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; values and we’d like to calculate their sum. It would make sense to write the following piece of code:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;However, this code does not compile. Java compiler considers the result of this expression as integer value instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt;.
We could, of course, cast the result to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt;, successfully compile it and get the expected result:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// c == 30000&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h3 id=&quot;why-do-we-have-to-cast&quot;&gt;Why do we have to cast?&lt;/h3&gt;
&lt;p&gt;If we look at the bytecode of the previous example, we will find a following piece:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;0: sipush        10000
3: istore_1
4: sipush        20000
7: istore_2
8: iload_1
9: iload_2
10: iadd
11: i2s
12: istore_3&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;It starts with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sipush&lt;/code&gt;, and the function of this bytecode operation is literally to push a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; onto the stack as an &lt;strong&gt;integer value&lt;/strong&gt;.
The following operation is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;istore_1&lt;/code&gt;, and it already tells us that it stores variable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a&lt;/code&gt; as integer. Same happens for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;b&lt;/code&gt;.
All the following operations are simply integer manipulations, including &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;iadd&lt;/code&gt; which sums two integer values.&lt;/p&gt;

&lt;p&gt;At the end, because we performed the casting, we find &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i2s&lt;/code&gt; (integer to short) casting operation, but still the final result that is
stored in the local variables is again an integer value.&lt;/p&gt;

&lt;h3 id=&quot;but-why&quot;&gt;But why?&lt;/h3&gt;
&lt;p&gt;What we have observed is called ‘widening primitive conversion’. The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; value, which takes two bytes, is put in a bigger ‘box’ of 4 bytes, which is an integer type.&lt;/p&gt;

&lt;p&gt;Why is this happening in this case? There are simply no bytecode instructions which would allow to perform operations directly on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; values, so they are converted to integers.&lt;/p&gt;

&lt;h3 id=&quot;omg-whats-that-though&quot;&gt;OMG, what’s that though?&lt;/h3&gt;
&lt;p&gt;If we write our original code without any casting, but make our variables &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;final&lt;/code&gt;, there is no problem compiling that!&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This behaviour is easy to explain. Let’s take a look at the relevant piece of bytecode:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt; 0: sipush        10000
 3: istore_1
 4: sipush        20000
 7: istore_2
 8: sipush        30000
11: istore_3&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;As we can see, all values including the resulting sum are considered as constant values. The sum is calculated during
compilation and placed directly into the bytecode. This is one of the compiler optimizations called ‘constant folding’.&lt;/p&gt;

&lt;p&gt;In this case, compiler could calculate the sum and see that the resulting value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;30000&lt;/code&gt; indeed fits into 2 bytes to be of a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; type.&lt;/p&gt;

&lt;p&gt;If we do a slight change to our code so the sum wouldn’t fit into a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; type, the compiler immediately starts to complain:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// won&apos;t compile, because 40000 doesn&apos;t fit in 2 bytes&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Note: if we had the same code, but all our values were integer, and the sum didn’t fit into an integer, 
we would have gotten a warning, but compiler would have accepted it anyway.&lt;/p&gt;

&lt;h3 id=&quot;cases-of-widening&quot;&gt;Cases of widening&lt;/h3&gt;
&lt;p&gt;There are different use-cases of widening primitive conversion. Often it is happening when one of the values in a single operation is of a wider type,
so the other value is widened to match.&lt;/p&gt;

&lt;p&gt;Also, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;byte&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;char&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;boolean&lt;/code&gt; values are always converted to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;int&lt;/code&gt; under the hood. 
There is simply no means of dealing with these types on the bytecode level.&lt;/p&gt;

&lt;h3 id=&quot;short-doesnt-exist&quot;&gt;Short doesn’t exist?&lt;/h3&gt;
&lt;p&gt;It’s a good question.&lt;/p&gt;

&lt;p&gt;We have seen from the above examples that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; is saved into the local variables as an integer value. 
So is it just a Java code sugar?&lt;/p&gt;

&lt;p&gt;Using the following code, we can try and figure out, what is the type of our primitive variable:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-java&quot; data-lang=&quot;java&quot;&gt;&lt;span class=&quot;kt&quot;&gt;short&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20000&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nc&quot;&gt;System&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;println&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(((&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getClass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getName&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;The code above outputs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;java.lang.Short&lt;/code&gt;. So did we get something wrong?&lt;/p&gt;

&lt;p&gt;If we look in the bytecode, we will find our answers:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;0: sipush        20000
3: istore_1
4: getstatic     #7                  // Field java/lang/System.out:Ljava/io/PrintStream;
7: iload_1
8: invokestatic  #13                 // Method java/lang/Short.valueOf:(S)Ljava/lang/Short;
11: invokevirtual #19                 // Method java/lang/Object.getClass:()Ljava/lang/Class;
14: invokevirtual #23                 // Method java/lang/Class.getName:()Ljava/lang/String;
17: invokevirtual #29                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;What is happening here is that we are saving our value as an integer variable. Then we load it onto the stack and
use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Short::valueOf&lt;/code&gt; method to make it &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; again. Compiler knows, that it’s a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt;, because we specified it in our code.
So it makes sure that our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; variables behave as they should. But in the end…&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;short&lt;/code&gt; is a lie :)&lt;/p&gt;

&lt;p&gt;(yes, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;byte&lt;/code&gt; as well)&lt;/p&gt;

&lt;p&gt;Hope this was educative and fun!&lt;/p&gt;

&lt;p&gt;If you liked this little post, take a look at the previous posts from the series:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/25/I-wont-let-Java-confuse-you-2.html&quot;&gt;Expressions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/16/I-wont-let-Java-confuse-you-1.html&quot;&gt;String operator &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2024/03/07/I-wont-let-Java-confuse-you-0.html&quot;&gt;Increment&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
            <pubDate>Wed, 01 May 2024 10:00:00 +0000</pubDate>
            <link>https://nataliiadziubenko.com/2024/05/01/I-wont-let-Java-confuse-you-3.html</link>
            <guid isPermaLink="true">https://nataliiadziubenko.com/2024/05/01/I-wont-let-Java-confuse-you-3.html</guid>
            
            
        </item>
        
    </channel>
</rss>