{"data":{"article":{"id":"19cc0c42-5288-55fa-abfe-4af1aeb242ca","frontmatter":{"category":"Engineering","title":"Rate Limiters and Thread blocking, is there an alternative?","date":"2022-07-18","summary":"There are some cases where you would like to limit the frequency that something happens to it work properly","thumbnail":null,"authorName":"Bruno Morais","authorDescription":"Bruno is a Senior Software Engineer at AUTO1 Group.","authorAvatar":{"relativePath":"pages/rate-limiters/avatar_Morais.jpeg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDAQX/xAAXAQEBAQEAAAAAAAAAAAAAAAABAwIE/9oADAMBAAIQAxAAAAGmbSadPSZMPIBLBy1//8QAHBAAAwABBQAAAAAAAAAAAAAAAQIDIQAQERIj/9oACAEBAAEFAqOVEql2047LLDc7A+i5H//EABcRAQEBAQAAAAAAAAAAAAAAAAEAEBL/2gAIAQMBAT8BC5jP/8QAGREAAwADAAAAAAAAAAAAAAAAAAECEBET/9oACAECAQE/AW9HSSsf/8QAGhAAAQUBAAAAAAAAAAAAAAAAAQACEBEhQf/aAAgBAQAGPwLBZRa4VFYt5Jj/xAAcEAADAAIDAQAAAAAAAAAAAAAAAREhURAxYXH/2gAIAQEAAT8ho6G+i0ElVBP0c6AzfMaH3OHLLoTIz//aAAwDAQACAAMAAAAQcC98/8QAGREAAwADAAAAAAAAAAAAAAAAABExEFGB/9oACAEDAQE/EGQbRPcf/8QAGxEAAgIDAQAAAAAAAAAAAAAAAAERMVFhscH/2gAIAQIBAT8QuM2dElucejs//8QAGxABAQEBAAMBAAAAAAAAAAAAAREAITFBYXH/2gAIAQEAAT8QEiRCoPrgpVComQJxnQidLcJrAFJfmh7Hwmff5oW4eD07h8orv//Z","width":50,"height":50,"src":"/static/7b4637bf5ab4eaf01facec045622cc5c/d2d31/avatar_Morais.jpeg","srcSet":"/static/7b4637bf5ab4eaf01facec045622cc5c/d2d31/avatar_Morais.jpeg 1x,\n/static/7b4637bf5ab4eaf01facec045622cc5c/0b804/avatar_Morais.jpeg 1.5x,\n/static/7b4637bf5ab4eaf01facec045622cc5c/753c3/avatar_Morais.jpeg 2x,\n/static/7b4637bf5ab4eaf01facec045622cc5c/31ca8/avatar_Morais.jpeg 3x"}}},"headerImage":{"relativePath":"pages/rate-limiters/header_Morais.jpg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAUBAwT/xAAVAQEBAAAAAAAAAAAAAAAAAAABAP/aAAwDAQACEAMQAAABtzsIJMMhP//EABoQAAIDAQEAAAAAAAAAAAAAAAECAAMREBL/2gAIAQEAAQUCNWyxTnkdKrP/xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/AT//xAAVEQEBAAAAAAAAAAAAAAAAAAAAEf/aAAgBAgEBPwFX/8QAGRAAAwADAAAAAAAAAAAAAAAAAAExEBEh/9oACAEBAAY/AuM04TMP/8QAGhAAAgIDAAAAAAAAAAAAAAAAAAERYRAhUf/aAAgBAQABPyFTTBRag4ywx57U/9oADAMBAAIAAwAAABAfP//EABYRAQEBAAAAAAAAAAAAAAAAAAEAEf/aAAgBAwEBPxDZNb//xAAWEQEBAQAAAAAAAAAAAAAAAAAAARH/2gAIAQIBAT8QTD//xAAbEAEBAQEBAAMAAAAAAAAAAAABESEAUTFxsf/aAAgBAQABPxC+laoo/XnLJVVmzJ2YRT5s/eDOI4g51avPO//Z","width":1280,"height":849,"src":"/static/d7fdf1093c10ccf7ff201925fb486d79/966a5/header_Morais.jpg","srcSet":"/static/d7fdf1093c10ccf7ff201925fb486d79/966a5/header_Morais.jpg 1x,\n/static/d7fdf1093c10ccf7ff201925fb486d79/aa36d/header_Morais.jpg 1.5x"}}}},"html":"<p>Let's talk about harmony! If you have a look at an English dictionary, you'll see that even though almost everyone has some knowledge of the meaning of the word harmony, it's not so simple to properly define it. There are many contexts that it may apply, such as people relationships, business, law, and so on.</p>\n<p>But, at the end of the day, this concept imported from the music means that something happens in a way or frequency that makes it pleasant and less error-prone. So I want you to focus on the idea that the proper frequency is a way to achieve harmony.</p>\n<p>There are some cases where you would like to limit the frequency that something happens to it work properly. Imagine that you have a coffee machine, it's obvious that you would like it to dispense coffee at a frequency that you can replace the cups and be able to serve all your guests.</p>\n<p>It happens everywhere, even on software. At least while we have limited resources, we have to orchestrate them to work in harmony. One strategy is to use Rate Limiters, a maneuver to control the frequency in which some action is handled.</p>\n<h2>Rate Limiters</h2>\n<p>A common pattern to achieve the Rate Limiter strategy is to use the Token Bucket algorithm. In a nutshell, the Token Bucket mimics a real bucket where Theme Park tickets are stored. To enter to play around at the Theme Park, you need to take a ticket. But if the bucket is empty, you have to wait until some new tickets are put in there. Doing like that, you become able to control the flow of people to the Theme Park by controlling the number of tickets that are put into the bucket and the time interval in which the refill occurs.</p>\n<p>If we put 10 tickets per minute on that bucket, it'll assure that at most 10 people will enter the Theme Park in each 1-minute interval.</p>\n<p>Libraries like Google Guava, Resilience4j, and Bucket4j are examples of how we can achieve rate-limiting in our Java software.</p>\n<p>Despite being a beta version by the time of this writing, using the Google Guava RateLimiter library is pretty straightforward. You create a RateLimiter object defining the number of permits per second and, for each task, you specify that it should \"acquire\" the token that allows it to proceed.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">final</span> <span class=\"token class-name\">RateLimiter</span> rateLimiter <span class=\"token operator\">=</span> <span class=\"token class-name\">RateLimiter</span><span class=\"token punctuation\">.</span><span class=\"token function\">create</span><span class=\"token punctuation\">(</span><span class=\"token number\">2.0</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// rate is \"2 permits per second\"</span>\n    <span class=\"token keyword\">void</span>  <span class=\"token function\">submitTasks</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span> tasks<span class=\"token punctuation\">,</span> <span class=\"token class-name\">Executor</span> executor<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">Runnable</span> task <span class=\"token operator\">:</span> tasks<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        rateLimiter<span class=\"token punctuation\">.</span><span class=\"token function\">acquire</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// may wait</span>\n        executor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span>task<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>For Resilience4J you need to create some configuration before and decorate your task:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"> <span class=\"token comment\">// Create a custom RateLimiter configuration</span>\n<span class=\"token class-name\">RateLimiterConfig</span> config <span class=\"token operator\">=</span> <span class=\"token class-name\">RateLimiterConfig</span><span class=\"token punctuation\">.</span><span class=\"token function\">custom</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">timeoutDuration</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Duration</span><span class=\"token punctuation\">.</span><span class=\"token function\">ofMillis</span><span class=\"token punctuation\">(</span><span class=\"token number\">100</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">limitRefreshPeriod</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Duration</span><span class=\"token punctuation\">.</span><span class=\"token function\">ofSeconds</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">limitForPeriod</span><span class=\"token punctuation\">(</span><span class=\"token number\">2</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">build</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token comment\">// Create a RateLimiter</span>\n<span class=\"token class-name\">RateLimiter</span> rateLimiter <span class=\"token operator\">=</span> <span class=\"token class-name\">RateLimiter</span><span class=\"token punctuation\">.</span><span class=\"token function\">of</span><span class=\"token punctuation\">(</span><span class=\"token operator\">*</span><span class=\"token operator\">*</span><span class=\"token string\">\"backendName\"</span><span class=\"token operator\">*</span><span class=\"token operator\">*</span><span class=\"token punctuation\">,</span> config<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// Decorate your call to BackendService.doSomething()</span>\n<span class=\"token class-name\">Supplier</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> restrictedSupplier <span class=\"token operator\">=</span> <span class=\"token class-name\">RateLimiter</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">decorateSupplier</span><span class=\"token punctuation\">(</span>rateLimiter<span class=\"token punctuation\">,</span> backendService<span class=\"token operator\">::</span><span class=\"token function\">doSomething</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// First call is successful</span>\n<span class=\"token class-name\">Try</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> firstTry <span class=\"token operator\">=</span> <span class=\"token class-name\">Try</span><span class=\"token punctuation\">.</span><span class=\"token function\">ofSupplier</span><span class=\"token punctuation\">(</span>restrictedSupplier<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>firstTry<span class=\"token punctuation\">.</span><span class=\"token function\">isSuccess</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">isTrue</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>In the same path, now using Bucket4j, you need to specify the refill interval and the limit:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token class-name\">Refill</span> refill <span class=\"token operator\">=</span> <span class=\"token class-name\">Refill</span><span class=\"token punctuation\">.</span><span class=\"token function\">intervally</span><span class=\"token punctuation\">(</span><span class=\"token number\">2</span><span class=\"token punctuation\">,</span> <span class=\"token class-name\">Duration</span><span class=\"token punctuation\">.</span><span class=\"token function\">ofSeconds</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token class-name\">Bandwidth</span> limit <span class=\"token operator\">=</span> <span class=\"token class-name\">Bandwidth</span><span class=\"token punctuation\">.</span><span class=\"token function\">classic</span><span class=\"token punctuation\">(</span><span class=\"token number\">2</span><span class=\"token punctuation\">,</span> refill<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token class-name\">Bucket</span> bucket <span class=\"token operator\">=</span> <span class=\"token class-name\">Bucket4j</span><span class=\"token punctuation\">.</span><span class=\"token function\">builder</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">addLimit</span><span class=\"token punctuation\">(</span>limit<span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">build</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>bucket<span class=\"token punctuation\">.</span><span class=\"token function\">tryConsume</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    executor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span>task<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>But if you want that the employees from the theme park's main entrance do other tasks while the customers are in the queue and still not allowed to enter, I mean if you want that your thread is used for other tasks, at least these 3 libraries have a pattern that may be a problem to you: they block the thread.</p>\n<h2>Thread Blocking</h2>\n<p>Now we are in the second part of this article, and as we are talking about Threads, it's good to know some basics about them. The first step is to know that they allow us to work concurrently, two tasks running virtually at the same time. But Threads are notoriously complex and error-prone, inaugurating a new sorts of problems like Deadlock, Race Condition, and so on.</p>\n<p>As we said at the start of this article, considering that we have limited resources, we have to use Threads with wisdom and be as clever as possible.</p>\n<p>If I and my wife are in the kitchen and we have just one knife available, it is appropriate that once one of us stop using the knife we leave it available to the other over the table, so that the other could start working with this piece of cutlery.</p>\n<p>When one forgets about this rule, the other one is kept waiting for the tool, and important work is not held, preventing the flow of a harmonious cuisine.</p>\n<p>The computer environment works like this kitchen, we have a limited number of Threads. And when something blocks one thread with a Thread.sleep() or LockSupport.parkNanos(), this Thread goes to the TIMED_WAITING state and during this time it can not be used. It is like the unused knife in the cooker's hand of an unharmonious kitchen.</p>\n<p>In practical terms, consider the following code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span> <span class=\"token keyword\">void</span> <span class=\"token function\">guavaRateLimiter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token class-name\">RateLimiter</span> rateLimiter <span class=\"token operator\">=</span> <span class=\"token class-name\">RateLimiter</span><span class=\"token punctuation\">.</span><span class=\"token function\">create</span><span class=\"token punctuation\">(</span><span class=\"token number\">2</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token function\">logWithThreadTimeStamped</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token class-name\">IntStream</span><span class=\"token punctuation\">.</span><span class=\"token function\">rangeClosed</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">forEach</span><span class=\"token punctuation\">(</span>i <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n    rateLimiter<span class=\"token punctuation\">.</span><span class=\"token function\">acquire</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token function\">logWithThreadTimeStamped</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Task n. \"</span> <span class=\"token operator\">+</span> i<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token function\">logWithThreadTimeStamped</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm blocked =(\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token function\">logWithThreadTimeStamped</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>It will output as follow:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">[12:01:31.972073] Starting Thread: main\n[12:01:31.978520] Task n. 1 Thread: main\n[12:01:32.471752] Task n. 2 Thread: main\n[12:01:32.967231] Task n. 3 Thread: main\n[12:01:33.470331] Task n. 4 Thread: main\n[12:01:33.470662] I'm blocked =( Thread: main\n[12:01:33.470845] Finishing Thread: main</code></pre></div>\n<p>What we wanted was that our 4 tasks were completed in a frequency of at most 2 for each second, but the Rate Limiter also has blocked the other tasks.</p>\n<p>You may ask, what to do? Perhaps, we should schedule instead of blocking!</p>\n<h2>Scheduling</h2>\n<p>Imagine when you need to go to the doctor. Unless there is an emergency, you will likely have to make an appointment. The schedules are spread in a timeline, considering the doctor's ability to do the entire checkup: anamnesis, some additional exams, and so on. So to say, if the doctor takes an average of 30 minutes to attend to a patient appointment, those appointments should be guaranteed in intervals of 30 minutes.</p>\n<p>With this in mind, we could refactor our previous code. If we need that our tasks are executed at a rate of 2 per second, it means that we should schedule our tasks for every 500 milliseconds, which is one second (1000 milliseconds) divided by 2.</p>\n<p>Now that we know our interval, we have to find a way to keep track of our \"appointments\", to avoid scheduling more than one task to the same interval. Let's use an AtomicInteger class for that.</p>\n<p>Let's scratch some code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span> <span class=\"token keyword\">void</span> <span class=\"token function\">taskScheduling</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token keyword\">var</span> scheduleExecutor <span class=\"token operator\">=</span> <span class=\"token class-name\">Executors</span><span class=\"token punctuation\">.</span><span class=\"token function\">newSingleThreadScheduledExecutor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> intervalDiary <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AtomicInteger</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> expectedInterval <span class=\"token operator\">=</span> <span class=\"token number\">500</span><span class=\"token punctuation\">;</span>\n<span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token class-name\">IntStream</span><span class=\"token punctuation\">.</span><span class=\"token function\">rangeClosed</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">forEach</span><span class=\"token punctuation\">(</span>i <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n    scheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">schedule</span><span class=\"token punctuation\">(</span>\n        <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Task n. \"</span> <span class=\"token operator\">+</span> i<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n        intervalDiary<span class=\"token punctuation\">.</span><span class=\"token function\">getAndAdd</span><span class=\"token punctuation\">(</span>expectedInterval<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n    <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm NOT blocked =D\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">private</span> <span class=\"token keyword\">void</span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> message<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token class-name\">System</span><span class=\"token punctuation\">.</span>out<span class=\"token punctuation\">.</span><span class=\"token function\">println</span><span class=\"token punctuation\">(</span>message <span class=\"token operator\">+</span> <span class=\"token string\">\" Thread: \"</span> <span class=\"token operator\">+</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">.</span><span class=\"token function\">currentThread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">getName</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>It will output as follows:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">Starting - Thread: main\nI'm NOT blocked =D Thread: main\nFinishing - Thread: main\nTask n. 1 - Thread: pool-1-thread-1\nTask n. 2 - Thread: pool-1-thread-1\nTask n. 3 - Thread: pool-1-thread-1\nTask n. 4 - Thread: pool-1-thread-1</code></pre></div>\n<p>Oh, it worked, but seems like we are cheating, because we just added a new thread to the game. How can we know for sure if that new thread is not being blocked? Well, we can test it like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span> <span class=\"token keyword\">void</span> <span class=\"token function\">taskSchedulingV2</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token keyword\">var</span> scheduleExecutor <span class=\"token operator\">=</span> <span class=\"token class-name\">Executors</span><span class=\"token punctuation\">.</span><span class=\"token function\">newSingleThreadScheduledExecutor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> intervalDiary <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AtomicInteger</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> expectedInterval <span class=\"token operator\">=</span> <span class=\"token number\">500</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token class-name\">IntStream</span><span class=\"token punctuation\">.</span><span class=\"token function\">rangeClosed</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">forEach</span><span class=\"token punctuation\">(</span>i <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n    scheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">schedule</span><span class=\"token punctuation\">(</span>\n        <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Task n. \"</span> <span class=\"token operator\">+</span> i<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n        intervalDiary<span class=\"token punctuation\">.</span><span class=\"token function\">getAndAdd</span><span class=\"token punctuation\">(</span>expectedInterval<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n    <span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm NOT blocked =D\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>And voilà:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">Starting Thread: pool-1-thread-1\nTask n. 1 Thread: pool-1-thread-1\nI'm NOT blocked =D Thread: pool-1-thread-1\nFinishing Thread: pool-1-thread-1\nTask n. 2 Thread: pool-1-thread-1\nTask n. 3 Thread: pool-1-thread-1\nTask n. 4 Thread: pool-1-thread-1</code></pre></div>\n<p>The downside of this approach is that the ScheduledExecutorService, that we receive from the newSingleThreadScheduledExecutor() method of the Executors class, uses an unbounded queue. This means that no task will ever be rejected (by the meaning of the unbounded word, it is like an unlimited queue), and because of that, we have the risk of consuming too much memory if we receive tasks more quickly than we can handle them.</p>\n<p>Of course, we can avoid that in many ways. One approach could be to track the number of scheduled tasks and reject new tasks if we hit the specified threshold. First of all, let's refactor our code so that we use a queue of tasks as the source to be used by the scheduler.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span> <span class=\"token keyword\">void</span> <span class=\"token function\">taskSchedulingV3</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token keyword\">var</span> scheduleExecutor <span class=\"token operator\">=</span> <span class=\"token class-name\">Executors</span><span class=\"token punctuation\">.</span><span class=\"token function\">newSingleThreadScheduledExecutor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> myTasks <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> EXPECTED_INTERVAL <span class=\"token operator\">=</span> <span class=\"token number\">500</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">scheduleAtFixedRate</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span>\n    <span class=\"token function\">ofNullable</span><span class=\"token punctuation\">(</span>myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">poll</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">ifPresent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Runnable</span><span class=\"token operator\">::</span><span class=\"token function\">run</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span><span class=\"token punctuation\">,</span> EXPECTED_INTERVAL<span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token class-name\">IntStream</span><span class=\"token punctuation\">.</span><span class=\"token function\">rangeClosed</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> <span class=\"token number\">4</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">forEach</span><span class=\"token punctuation\">(</span>i <span class=\"token operator\">-></span>\n    myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Task n.\"</span> <span class=\"token operator\">+</span> i<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm NOT blocked =D\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Our log:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">Starting Thread: pool-1-thread-1\nTask n.1 Thread: pool-1-thread-1\nI'm NOT blocked =D Thread: pool-1-thread-1\nFinishing Thread: pool-1-thread-1\nTask n.2 Thread: pool-1-thread-1\nTask n.3 Thread: pool-1-thread-1\nTask n.4 Thread: pool-1-thread-1</code></pre></div>\n<p>Now in this version, we are using the scheduleAtFixedRate() method, which frees us from keeping track of the already used intervals. It now checks for new tasks for every expected interval.</p>\n<p>But what would happen if we have more tasks coming than we are able to handle? The following code creates a new task for each 250ms but handles new tasks just in an interval of 500ms.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span>  <span class=\"token keyword\">void</span>  <span class=\"token function\">taskSchedulingOverload</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token keyword\">var</span> scheduleExecutor <span class=\"token operator\">=</span> <span class=\"token class-name\">Executors</span><span class=\"token punctuation\">.</span><span class=\"token function\">newSingleThreadScheduledExecutor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> myTasks <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> EXPECTED_INTERVAL <span class=\"token operator\">=</span> <span class=\"token number\">500</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> SMALLER_INTERVAL <span class=\"token operator\">=</span> <span class=\"token number\">250</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">scheduleAtFixedRate</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span>\n    <span class=\"token function\">ofNullable</span><span class=\"token punctuation\">(</span>myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">poll</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">ifPresent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Runnable</span><span class=\"token operator\">::</span><span class=\"token function\">run</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span><span class=\"token punctuation\">,</span> EXPECTED_INTERVAL<span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">scheduleAtFixedRate</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span>\n    myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Fast Task! Task lasting: \"</span> <span class=\"token operator\">+</span> myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">size</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span><span class=\"token punctuation\">,</span> SMALLER_INTERVAL<span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm NOT blocked =D\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Our output would be something like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">Starting Thread: pool-1-thread-1\nI'm NOT blocked =D Thread: pool-1-thread-1\nFinishing Thread: pool-1-thread-1\nFast Task! Task lasting: 1 Thread: pool-1-thread-1\nFast Task! Task lasting: 2 Thread: pool-1-thread-1\nFast Task! Task lasting: 3 Thread: pool-1-thread-1\nFast Task! Task lasting: 4 Thread: pool-1-thread-1\nFast Task! Task lasting: 5 Thread: pool-1-thread-1\nFast Task! Task lasting: 6 Thread: pool-1-thread-1\nFast Task! Task lasting: 7 Thread: pool-1-thread-1\nFast Task! Task lasting: 8 Thread: pool-1-thread-1\nFast Task! Task lasting: 9 Thread: pool-1-thread-1\n\n(...)</code></pre></div>\n<p>The size of the queue will not stop raising, leading us to an out-of-memory error. Oh, but don't be so afraid my friend, as we said we can limit the schedule based on that queue. Like if you call the doctor to make an appointment and they answer you: \"sorry, for the next 10 years all our schedules are already taken, please call in another day (or year).\"</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span>  <span class=\"token keyword\">void</span>  <span class=\"token function\">taskSchedulingLimitingByQueueSize</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n<span class=\"token keyword\">var</span> scheduleExecutor <span class=\"token operator\">=</span> <span class=\"token class-name\">Executors</span><span class=\"token punctuation\">.</span><span class=\"token function\">newSingleThreadScheduledExecutor</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> myTasks <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> EXPECTED_INTERVAL <span class=\"token operator\">=</span> <span class=\"token number\">500</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> SMALLER_INTERVAL <span class=\"token operator\">=</span> <span class=\"token number\">250</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">var</span> QUEUE_LIMIT <span class=\"token operator\">=</span> <span class=\"token number\">4</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Starting\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">scheduleAtFixedRate</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span>\n    <span class=\"token function\">ofNullable</span><span class=\"token punctuation\">(</span>myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">poll</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">ifPresent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Runnable</span><span class=\"token operator\">::</span><span class=\"token function\">run</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span><span class=\"token punctuation\">,</span> EXPECTED_INTERVAL<span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">scheduleAtFixedRate</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">size</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">&lt;</span> QUEUE_LIMIT<span class=\"token punctuation\">)</span>\n        myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Fast Task! Task lasting: \"</span> <span class=\"token operator\">+</span> myTasks<span class=\"token punctuation\">.</span><span class=\"token function\">size</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">else</span>\n        <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I was rejected =(\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span><span class=\"token punctuation\">,</span> SMALLER_INTERVAL<span class=\"token punctuation\">,</span> <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS\n<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"I'm NOT blocked =D\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\nscheduleExecutor<span class=\"token punctuation\">.</span><span class=\"token function\">execute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">logWithThread</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Finishing\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Our output:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">Starting Thread: pool-1-thread-1\nI'm NOT blocked =D Thread: pool-1-thread-1\nFinishing Thread: pool-1-thread-1\nFast Task! Task lasting: 1 Thread: pool-1-thread-1\nFast Task! Task lasting: 2 Thread: pool-1-thread-1\nFast Task! Task lasting: 3 Thread: pool-1-thread-1\nI was rejected =( Thread: pool-1-thread-1\nFast Task! Task lasting: 3 Thread: pool-1-thread-1\nI was rejected =( Thread: pool-1-thread-1\nFast Task! Task lasting: 3 Thread: pool-1-thread-1\nI was rejected =( Thread: pool-1-thread-1\nFast Task! Task lasting: 3 Thread: pool-1-thread-1</code></pre></div>\n<p>Here we have to talk about backpressure. Remember that this problem about memory only occurs if always the input of tasks is faster than the output. If the input of tasks was faster in just a point of time, this surplus of tasks will be kept on the queue and properly handled in the following time. So with this approach, our application could control the rate of events so that fast producers (sending new tasks) does not overwhelm our consumer.</p>\n<p>In a blocking approach, the producer will be forced to wait. In the scheduling approach, the new tasks will be handled in time, and only if it overloads that some of them will be queued.</p>\n<p>You could say, but how long should be my queue? Well, I may say that it depends on your use case. A doctor could have a schedule book for all the current year. And if it shows to be not enough, the doctor can buy a new schedule book for the next year. As in your application service, if you can afford more memory, your queues can be as long as you want.</p>\n<p>But in the case of a traveling circus, if it will be in the town for just 3 weeks it doesn't make sense to accept schedules for the next month. The same as your application, if its capacity of handling tasks isn't fast enough at a point that the handling of an older schedule task starts to become unmeaningful, you should shrink your queue.</p>\n<h2>Conclusion</h2>\n<p>We can conclude that scheduling is a good approach for rate-limiting without the downside of blocking the thread. It gives us the opportunity of controlling the flow of incoming tasks, queueing peaks, and always handle the tasks in harmony with all other components.</p>","fields":{"slug":"/rate-limiters/","tags":["auto1","engineering","RateLimiter","Thread","Scheduling"]}},"categoryArticles":{"edges":[{"node":{"id":"cb45e6dc-ba61-576d-adc2-ba609b0e722a","frontmatter":{"category":"Engineering","title":"Go 1.23: the new Pattern property in http.Request","date":"2024-11-26","summary":"A short review of the new Pattern property in net/http.Request","thumbnail":null,"authorName":"Andrei Gusev","authorDescription":"Senior Software Engineer at AUTO1 Group","authorAvatar":{"relativePath":"pages/go-123-the-new-pattern-property-in-http-request/avatar_Andrei.jpg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAUBBgT/xAAWAQEBAQAAAAAAAAAAAAAAAAAAAQL/2gAMAwEAAhADEAAAAaeTsi2mDmfWV0wzf//EAB0QAAICAQUAAAAAAAAAAAAAAAECAAMEEBESEyH/2gAIAQEAAQUCtYiUvyE71ZkuQNuzaYvuQTP/xAAUEQEAAAAAAAAAAAAAAAAAAAAg/9oACAEDAQE/AR//xAAUEQEAAAAAAAAAAAAAAAAAAAAg/9oACAECAQE/AR//xAAcEAACAgIDAAAAAAAAAAAAAAABEQACEBIhMTL/2gAIAQEABj8C4KnprGnRhqdnHWpWKPH/xAAdEAACAgMAAwAAAAAAAAAAAAABEQAhEEFRMXGB/9oACAEBAAE/IRoFjyQHGILdksEYAYLXeSuANz4mvAhI736hHP/aAAwDAQACAAMAAAAQNBc+/8QAFhEAAwAAAAAAAAAAAAAAAAAAABAR/9oACAEDAQE/ECv/xAAUEQEAAAAAAAAAAAAAAAAAAAAg/9oACAECAQE/EB//xAAcEAEBAAMBAAMAAAAAAAAAAAABEQAhUTEQYaH/2gAIAQEAAT8Q0H5agDhjJzCu2+nxvKetJ9/fd9x0k6GIzjdTPf69KX9xcAAKlBR2wEDDmf/Z","width":50,"height":50,"src":"/static/479e481648d69b84a342bd2575a225d4/d2d31/avatar_Andrei.jpg","srcSet":"/static/479e481648d69b84a342bd2575a225d4/d2d31/avatar_Andrei.jpg 1x,\n/static/479e481648d69b84a342bd2575a225d4/0b804/avatar_Andrei.jpg 1.5x,\n/static/479e481648d69b84a342bd2575a225d4/753c3/avatar_Andrei.jpg 2x,\n/static/479e481648d69b84a342bd2575a225d4/31ca8/avatar_Andrei.jpg 3x"}}},"headerImage":null},"html":"<h1>Go 1.23: the new Pattern property in http.Request</h1>\n<p>In Go 1.23, a new <code class=\"language-text\">Pattern</code> property in <code class=\"language-text\">net/http.Request</code> was added.\nIt contains the route pattern used to handle the request. This improvement may have gone unnoticed by many, but it can\nsimplify request processing and improve performance in cases where we need to obtain the matched routing pattern\nfor the current request. Let’s see how we can use this feature.</p>\n<p>At AUTO1, we have more than 200 microservices, some of which are written in Go and include an HTTP server.\nIt is critically important for us to collect metrics from these services in order to quickly respond to incidents,\nmake data-driven decisions, and optimize system performance.\nFor example, we collect <code class=\"language-text\">http_requests_total</code> metric:</p>\n<div class=\"gatsby-highlight\" data-language=\"go\"><pre class=\"language-go\"><code class=\"language-go\">requestsTotal <span class=\"token operator\">=</span> promauto<span class=\"token punctuation\">.</span><span class=\"token function\">NewCounterVec</span><span class=\"token punctuation\">(</span>prometheus<span class=\"token punctuation\">.</span>CounterOpts<span class=\"token punctuation\">{</span>\n\t\tName<span class=\"token punctuation\">:</span> <span class=\"token string\">\"http_requests_total\"</span><span class=\"token punctuation\">,</span>\n\t\tHelp<span class=\"token punctuation\">:</span> <span class=\"token string\">\"total request count\"</span><span class=\"token punctuation\">,</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token builtin\">string</span><span class=\"token punctuation\">{</span><span class=\"token string\">\"path\"</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"method\"</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"code\"</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>Obviously, for the <code class=\"language-text\">path</code> label, we should store the path template, not the specific value, for example, <code class=\"language-text\">/test/{id}</code> instead of <code class=\"language-text\">/test/123</code>.\nOtherwise, we risk a cardinality explosion, which can significantly increase the amount of stored data. You can read how to choose labels properly in <a href=\"https://prometheus.io/docs/practices/naming/#labels\">\"Prometheus best practices\"</a>.</p>\n<h2>Before v1.23</h2>\n<p>Previously, to extract the route pattern, we had to pass the multiplexer to a middleware function:</p>\n<div class=\"gatsby-highlight\" data-language=\"go\"><pre class=\"language-go\"><code class=\"language-go\"><span class=\"token keyword\">func</span> <span class=\"token function\">metricsMiddleware</span><span class=\"token punctuation\">(</span>next http<span class=\"token punctuation\">.</span>Handler<span class=\"token punctuation\">,</span> mux <span class=\"token operator\">*</span>http<span class=\"token punctuation\">.</span>ServeMux<span class=\"token punctuation\">)</span> http<span class=\"token punctuation\">.</span>Handler <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">return</span> http<span class=\"token punctuation\">.</span><span class=\"token function\">HandlerFunc</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">func</span><span class=\"token punctuation\">(</span>w http<span class=\"token punctuation\">.</span>ResponseWriter<span class=\"token punctuation\">,</span> r <span class=\"token operator\">*</span>http<span class=\"token punctuation\">.</span>Request<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\t<span class=\"token boolean\">_</span><span class=\"token punctuation\">,</span> pattern <span class=\"token operator\">:=</span> mux<span class=\"token punctuation\">.</span><span class=\"token function\">Handler</span><span class=\"token punctuation\">(</span>r<span class=\"token punctuation\">)</span>\n\t\t\n\t\t<span class=\"token operator\">...</span>\n\t\trequestsTotal<span class=\"token punctuation\">.</span><span class=\"token function\">WithLabelValues</span><span class=\"token punctuation\">(</span>pattern<span class=\"token punctuation\">,</span> method<span class=\"token punctuation\">,</span> statusCode<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">Inc</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In this approach, we matched the request to the route a second time, and that negatively affected performance.</p>\n<h2>Since 1.23</h2>\n<p>Starting with Go 1.23, we can get the route pattern directly from the request, without passing the multiplexer to the middleware:</p>\n<div class=\"gatsby-highlight\" data-language=\"go\"><pre class=\"language-go\"><code class=\"language-go\"><span class=\"token keyword\">func</span> <span class=\"token function\">middleware</span><span class=\"token punctuation\">(</span>f http<span class=\"token punctuation\">.</span>Handler<span class=\"token punctuation\">)</span> http<span class=\"token punctuation\">.</span>Handler <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">return</span> http<span class=\"token punctuation\">.</span><span class=\"token function\">HandlerFunc</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">func</span><span class=\"token punctuation\">(</span>w http<span class=\"token punctuation\">.</span>ResponseWriter<span class=\"token punctuation\">,</span> r <span class=\"token operator\">*</span>http<span class=\"token punctuation\">.</span>Request<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\tpattern <span class=\"token operator\">:=</span> r<span class=\"token punctuation\">.</span>Pattern\n\t\t\n\t\t<span class=\"token operator\">...</span>\n\t\trequestsTotal<span class=\"token punctuation\">.</span><span class=\"token function\">WithLabelValues</span><span class=\"token punctuation\">(</span>pattern<span class=\"token punctuation\">,</span> method<span class=\"token punctuation\">,</span> statusCode<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">Inc</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>This significantly simplifies the middleware, making the code cleaner and more readable. We are no longer dependent on <code class=\"language-text\">ServeMux</code> and no longer need to re-match the request.</p>\n<h2>Limitations</h2>\n<p>It is important to remember that <code class=\"language-text\">Request.Pattern</code> is only available after the request has been matched to a route. For example:</p>\n<div class=\"gatsby-highlight\" data-language=\"go\"><pre class=\"language-go\"><code class=\"language-go\"><span class=\"token keyword\">func</span> <span class=\"token function\">main</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\tmux <span class=\"token operator\">:=</span> http<span class=\"token punctuation\">.</span><span class=\"token function\">NewServeMux</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\tmux<span class=\"token punctuation\">.</span><span class=\"token function\">Handle</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"/test/{id}\"</span><span class=\"token punctuation\">,</span> <span class=\"token function\">routeMiddleware</span><span class=\"token punctuation\">(</span><span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n\n\tsrv <span class=\"token operator\">:=</span> http<span class=\"token punctuation\">.</span>Server<span class=\"token punctuation\">{</span>\n\t\tAddr<span class=\"token punctuation\">:</span>    <span class=\"token string\">\":8080\"</span><span class=\"token punctuation\">,</span>\n\t\tHandler<span class=\"token punctuation\">:</span> <span class=\"token function\">globalMiddleware</span><span class=\"token punctuation\">(</span>mux<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n\t<span class=\"token punctuation\">}</span>\n\n\t<span class=\"token keyword\">if</span> err <span class=\"token operator\">:=</span> srv<span class=\"token punctuation\">.</span><span class=\"token function\">ListenAndServe</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token operator\">!</span>errors<span class=\"token punctuation\">.</span><span class=\"token function\">Is</span><span class=\"token punctuation\">(</span>err<span class=\"token punctuation\">,</span> http<span class=\"token punctuation\">.</span>ErrServerClosed<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\tlog<span class=\"token punctuation\">.</span><span class=\"token function\">Fatalf</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"server error: %s\"</span><span class=\"token punctuation\">,</span> err<span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">func</span> <span class=\"token function\">routeMiddleware</span><span class=\"token punctuation\">(</span>h http<span class=\"token punctuation\">.</span>Handler<span class=\"token punctuation\">)</span> http<span class=\"token punctuation\">.</span>Handler <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">return</span> http<span class=\"token punctuation\">.</span><span class=\"token function\">HandlerFunc</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">func</span><span class=\"token punctuation\">(</span>w http<span class=\"token punctuation\">.</span>ResponseWriter<span class=\"token punctuation\">,</span> r <span class=\"token operator\">*</span>http<span class=\"token punctuation\">.</span>Request<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\tlog<span class=\"token punctuation\">.</span><span class=\"token function\">Printf</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"ROUTE pattern: %s\"</span><span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>Pattern<span class=\"token punctuation\">)</span>\n\t\th<span class=\"token punctuation\">.</span><span class=\"token function\">ServeHTTP</span><span class=\"token punctuation\">(</span>w<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">func</span> <span class=\"token function\">globalMiddleware</span><span class=\"token punctuation\">(</span>h http<span class=\"token punctuation\">.</span>Handler<span class=\"token punctuation\">)</span> http<span class=\"token punctuation\">.</span>Handler <span class=\"token punctuation\">{</span>\n\t<span class=\"token keyword\">return</span> http<span class=\"token punctuation\">.</span><span class=\"token function\">HandlerFunc</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">func</span><span class=\"token punctuation\">(</span>w http<span class=\"token punctuation\">.</span>ResponseWriter<span class=\"token punctuation\">,</span> r <span class=\"token operator\">*</span>http<span class=\"token punctuation\">.</span>Request<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t\tlog<span class=\"token punctuation\">.</span><span class=\"token function\">Printf</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"GLOBAL pattern: %s\"</span><span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>Pattern<span class=\"token punctuation\">)</span>\n\t\th<span class=\"token punctuation\">.</span><span class=\"token function\">ServeHTTP</span><span class=\"token punctuation\">(</span>w<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">)</span>\n\t\tlog<span class=\"token punctuation\">.</span><span class=\"token function\">Printf</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"GLOBAL pattern after: %s\"</span><span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>Pattern<span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>If we send a request <code class=\"language-text\">GET http://localhost:8080/test/123</code>, in logs we will see:</p>\n<div class=\"gatsby-highlight\" data-language=\"text\"><pre class=\"language-text\"><code class=\"language-text\">2024/11/10 13:20:37 GLOBAL pattern: \n2024/11/10 13:20:37 ROUTE pattern: /test/{id}\n2024/11/10 13:20:37 GLOBAL pattern after: /test/{id}</code></pre></div>\n<p>This is the expected behavior. The multiplexer implements the <code class=\"language-text\">http.Handler</code> interface, and inside the <code class=\"language-text\">ServeHTTP</code> method, it searches for the handler that matches the request. Starting from Go 1.23, it fills the <code class=\"language-text\">Pattern</code> property of the request with the matching route pattern:</p>\n<div class=\"gatsby-highlight\" data-language=\"go\"><pre class=\"language-go\"><code class=\"language-go\"><span class=\"token comment\">// net/http/server.go</span>\n<span class=\"token keyword\">func</span> <span class=\"token punctuation\">(</span>mux <span class=\"token operator\">*</span>ServeMux<span class=\"token punctuation\">)</span> <span class=\"token function\">ServeHTTP</span><span class=\"token punctuation\">(</span>w ResponseWriter<span class=\"token punctuation\">,</span> r <span class=\"token operator\">*</span>Request<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token operator\">...</span>\n\t<span class=\"token keyword\">var</span> h Handler\n\t<span class=\"token keyword\">if</span> use121 <span class=\"token punctuation\">{</span>\n\t\th<span class=\"token punctuation\">,</span> <span class=\"token boolean\">_</span> <span class=\"token operator\">=</span> mux<span class=\"token punctuation\">.</span>mux121<span class=\"token punctuation\">.</span><span class=\"token function\">findHandler</span><span class=\"token punctuation\">(</span>r<span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n\t\th<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>Pattern<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>pat<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">.</span>matches <span class=\"token operator\">=</span> mux<span class=\"token punctuation\">.</span><span class=\"token function\">findHandler</span><span class=\"token punctuation\">(</span>r<span class=\"token punctuation\">)</span>\n\t<span class=\"token punctuation\">}</span>\n\th<span class=\"token punctuation\">.</span><span class=\"token function\">ServeHTTP</span><span class=\"token punctuation\">(</span>w<span class=\"token punctuation\">,</span> r<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Thus, the <code class=\"language-text\">r.Pattern</code> is filled only after the <code class=\"language-text\">ServeHTTP</code> method of the multiplexer has been called, and the logs confirm this behavior.</p>\n<h2>Conclusion</h2>\n<p>In the last two Go releases, the <code class=\"language-text\">net/http</code> package has received significant improvements that reduced the gap with third-party packages, like <code class=\"language-text\">gorilla/mux</code>. Now, <code class=\"language-text\">net/http.ServeMux</code> supports HTTP methods and wildcards in routing patterns, bringing its functionality closer to what third-party packages previously provided.</p>\n<p>Additionally, the introduction of the <code class=\"language-text\">net/http.Request.Pattern</code> property in Go 1.23 has simplified middleware development by allowing us to access the route pattern without needing to re-match the request, improving performance and reducing code complexity.</p>\n<p>With each of these improvements, there are fewer reasons to choose third-party routers. While the choice between the standard package and third-party routers used to be more obvious, today I would recommend starting with the standard <code class=\"language-text\">net/http</code> package.</p>","fields":{"slug":"/go-123-the-new-pattern-property-in-http-request/","tags":["auto1","go","network_programming"]}}},{"node":{"id":"9720ef25-7d81-5307-9ea5-229d55ec766f","frontmatter":{"category":"Engineering","title":"Android JetPack Compose + Paging 3","date":"2024-03-29","summary":"A short trip around the AUTO1 Application Cockpit data model","thumbnail":null,"authorName":"Sergey Bakhtiarov","authorDescription":"Senior Android Developer at AUTO1 Group","authorAvatar":{"relativePath":"pages/android-compose-pagination/avatar_Sergey.jpeg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAbABQDASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAAAAIEBgX/xAAWAQEBAQAAAAAAAAAAAAAAAAABAgD/2gAMAwEAAhADEAAAAessVEW4wzlnkZ2tJg3/xAAdEAACAQQDAAAAAAAAAAAAAAABAgMABCExECIz/9oACAEBAAEFAsAAq1EVIe0OSdtKzEXEgbfMHh//xAAXEQADAQAAAAAAAAAAAAAAAAAQERIh/9oACAEDAQE/AZxhj//EABURAQEAAAAAAAAAAAAAAAAAABEg/9oACAECAQE/AWP/xAAdEAACAgEFAAAAAAAAAAAAAAABEQAQAiAhImFx/9oACAEBAAY/AtzOJt9U3GCtGHk//8QAGxABAAIDAQEAAAAAAAAAAAAAAQARECExQVH/2gAIAQEAAT8hd4gIS0NTZPIjUV1DC40rgQLqvDjL0fpeUqrP/9oADAMBAAIAAwAAABD/APKz/8QAFREBAQAAAAAAAAAAAAAAAAAAEBH/2gAIAQMBAT8QBR//xAAXEQEBAQEAAAAAAAAAAAAAAAABEBEh/9oACAECAQE/EOnIBP/EAB0QAQEBAAMAAwEAAAAAAAAAAAERACExQVFhcdH/2gAIAQEAAT8QaCJVXrPnop5ivjMtoBBeM7oBFG2x3Zjtir0D+518AlC+E9yQMgcPsxpw/mVwqOXf/9k=","width":50,"height":50,"src":"/static/27c2b15cdd840519c853a653e9b049f0/d2d31/avatar_Sergey.jpeg","srcSet":"/static/27c2b15cdd840519c853a653e9b049f0/d2d31/avatar_Sergey.jpeg 1x,\n/static/27c2b15cdd840519c853a653e9b049f0/0b804/avatar_Sergey.jpeg 1.5x,\n/static/27c2b15cdd840519c853a653e9b049f0/753c3/avatar_Sergey.jpeg 2x,\n/static/27c2b15cdd840519c853a653e9b049f0/31ca8/avatar_Sergey.jpeg 3x"}}},"headerImage":null},"html":"<h1>Android JetPack Compose + Paging 3</h1>\n<h2>About pagination</h2>\n<p>Paginated APIs, often encountered when dealing with servers and databases, break down large datasets into manageable chunks or pages. This methodology not only optimizes resource usage but also enhances the overall user experience by delivering content progressively. However, integrating and managing paginated data in a mobile app can be a challenge, from maintaining loading states to ensuring a seamless transition between pages and supporting content filtering.</p>\n<p>In this guide I will show you how to work with paginated APIs in Android with Jetpack Compose and Paging 3 libraries. </p>\n<p><img src=\"/static/paging_demo-a325402259bf9864dced311c9eafa7c8.gif\" alt=\"Paging UI\"></p>\n<h2>Basics, architecture overview</h2>\n<p><br></br>\n<img src=\"https://developer.android.com/static/topic/libraries/architecture/images/paging3-library-architecture.svg\" alt=\"Paging library overview\"></p>\n<p>The key components of the Paging 3 architecture include</p>\n<h3>PagingSource</h3>\n<ul>\n<li>The foundational element responsible for loading data in chunks.</li>\n<li>Developers implement a custom PagingSource, defining how to retrieve data from a particular source or use implementation provided by a library supporting Paging 3. (Room can generate a paging source for your data query)</li>\n</ul>\n<h3>Remote Mediator</h3>\n<ul>\n<li>An integral part of the Paging 3 architecture, RemoteMediator manages the coordination between remote data sources, typically backed by a network service, and the local database.</li>\n<li>Responsible for loading pages of data from the network and storing them in the local database, ensuring efficient and reliable pagination.</li>\n</ul>\n<h3>Paging Data</h3>\n<ul>\n<li>Represents the paginated data stream emitted by the PagingSource.</li>\n<li>A Flow of PagingData is observed in the UI layer, enabling dynamic updates as new data is loaded or existing data is invalidated.</li>\n</ul>\n<h3>Pager</h3>\n<ul>\n<li>Coordinates the interaction between the PagingSource and the UI layer.</li>\n<li>Configures the pagination parameters, such as page size, prefetch distance, and initial load size, providing fine-grained control over the loading behavior.</li>\n</ul>\n<h2>Data layer</h2>\n<p>We start with the data layer and define a Retrofit API for fetching movies from network service.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">interface</span> MoviesApi <span class=\"token punctuation\">{</span>\n  <span class=\"token annotation builtin\">@GET</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"/3/discover/movie?language=en-US&amp;sort_by=popularity.desc\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">discover</span><span class=\"token punctuation\">(</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"api_key\"</span><span class=\"token punctuation\">)</span> api_key<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"page\"</span><span class=\"token punctuation\">)</span> page<span class=\"token operator\">:</span> Int<span class=\"token punctuation\">,</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"with_genres\"</span><span class=\"token punctuation\">)</span> genres<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Response<span class=\"token operator\">&lt;</span>MoviesNetworkResponse<span class=\"token operator\">></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Next, we will leverage the Room library, which is compatible with Paging 3, to create a local paging source. </p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token annotation builtin\">@Dao</span>\n<span class=\"token keyword\">interface</span> MoviesDao <span class=\"token punctuation\">{</span>\n  <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"SELECT * FROM movies ORDER BY id ASC\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">fun</span> <span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> DataSource<span class=\"token punctuation\">.</span>Factory<span class=\"token operator\">&lt;</span>Int<span class=\"token punctuation\">,</span> MovieDbEntity<span class=\"token operator\">></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>It's important to highlight that we utilize <code class=\"language-text\">DataSource.Factory</code> as the return type instead of <code class=\"language-text\">PagingSource</code>. This choice is made specifically because <code class=\"language-text\">DataSource.Factory</code> offers the <code class=\"language-text\">map()</code> method, enabling us to map <code class=\"language-text\">MovieDbEntity</code> instances into domain layer models.</p>\n<p>Now we need to put together local and remote data sources in Remote mediator.</p>\n<ol>\n<li>Determine which page to load depending on the loadType and next page value. Next page number (<code class=\"language-text\">getRemoteKey().nextPage</code>) is stored in the database after each successful network request.</li>\n</ol>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">val</span> page <span class=\"token operator\">=</span> <span class=\"token keyword\">when</span> <span class=\"token punctuation\">(</span>loadType<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        LoadType<span class=\"token punctuation\">.</span>REFRESH <span class=\"token operator\">-></span> <span class=\"token number\">1</span>\n        LoadType<span class=\"token punctuation\">.</span>PREPEND <span class=\"token operator\">-></span> <span class=\"token keyword\">null</span>\n        LoadType<span class=\"token punctuation\">.</span>APPEND <span class=\"token operator\">-></span> repository<span class=\"token punctuation\">.</span><span class=\"token function\">getRemoteKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?</span><span class=\"token punctuation\">.</span>nextPage\n      <span class=\"token punctuation\">}</span> <span class=\"token operator\">?:</span> <span class=\"token keyword\">return</span> <span class=\"token function\">Success</span><span class=\"token punctuation\">(</span>endOfPaginationReached <span class=\"token operator\">=</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>For bidirectional pagination support, provide the preceding page number for the PREPEND load type. The REFRESH load type is employed when content is refreshed, initiating loading from the initial page.</p>\n<ol start=\"2\">\n<li>Request data from network</li>\n</ol>\n<p>Call our network data source method to fetch a page of data from the server.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">val</span> movies <span class=\"token operator\">=</span> moviesDataSource<span class=\"token punctuation\">.</span><span class=\"token function\">discover</span><span class=\"token punctuation\">(</span>page<span class=\"token punctuation\">)</span></code></pre></div>\n<ol start=\"3\">\n<li>Insert data into the database or refresh database if loadType is refresh</li>\n</ol>\n<p>The RemoteMediator code will appear as follows:</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">class</span> <span class=\"token function\">MoviesRemoteMediator</span><span class=\"token punctuation\">(</span>\n  <span class=\"token keyword\">private</span> <span class=\"token keyword\">val</span> repository<span class=\"token operator\">:</span> MoviesRepository<span class=\"token punctuation\">,</span>\n  <span class=\"token keyword\">private</span> <span class=\"token keyword\">val</span> moviesDataSource<span class=\"token operator\">:</span> NetworkMoviesDataSource<span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">)</span> <span class=\"token operator\">:</span> RemoteMediator<span class=\"token operator\">&lt;</span>Int<span class=\"token punctuation\">,</span> Movie<span class=\"token operator\">></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\n  <span class=\"token keyword\">override</span> <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">load</span><span class=\"token punctuation\">(</span>loadType<span class=\"token operator\">:</span> LoadType<span class=\"token punctuation\">,</span> state<span class=\"token operator\">:</span> PagingState<span class=\"token operator\">&lt;</span>Int<span class=\"token punctuation\">,</span> Movie<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> MediatorResult <span class=\"token punctuation\">{</span>\n\n    <span class=\"token keyword\">return</span> <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n\n      <span class=\"token keyword\">val</span> page <span class=\"token operator\">=</span> <span class=\"token keyword\">when</span> <span class=\"token punctuation\">(</span>loadType<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        LoadType<span class=\"token punctuation\">.</span>REFRESH <span class=\"token operator\">-></span> <span class=\"token number\">1</span>\n        LoadType<span class=\"token punctuation\">.</span>PREPEND <span class=\"token operator\">-></span> <span class=\"token keyword\">null</span>\n        LoadType<span class=\"token punctuation\">.</span>APPEND <span class=\"token operator\">-></span> repository<span class=\"token punctuation\">.</span><span class=\"token function\">getRemoteKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?</span><span class=\"token punctuation\">.</span>nextPage\n      <span class=\"token punctuation\">}</span> <span class=\"token operator\">?:</span> <span class=\"token keyword\">return</span> <span class=\"token function\">Success</span><span class=\"token punctuation\">(</span>endOfPaginationReached <span class=\"token operator\">=</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">)</span>\n\n      <span class=\"token keyword\">val</span> movies <span class=\"token operator\">=</span> moviesDataSource<span class=\"token punctuation\">.</span><span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span>page<span class=\"token punctuation\">)</span>\n\n      <span class=\"token keyword\">val</span> nextPage <span class=\"token operator\">=</span> <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>movies<span class=\"token punctuation\">.</span><span class=\"token function\">isNotEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> page <span class=\"token operator\">+</span> <span class=\"token number\">1</span> <span class=\"token keyword\">else</span> <span class=\"token keyword\">null</span>\n\n      repository<span class=\"token punctuation\">.</span><span class=\"token function\">insertMovies</span><span class=\"token punctuation\">(</span>movies<span class=\"token punctuation\">,</span> nextPage<span class=\"token punctuation\">,</span> loadType <span class=\"token operator\">==</span> LoadType<span class=\"token punctuation\">.</span>REFRESH<span class=\"token punctuation\">)</span>\n\n      <span class=\"token function\">Success</span><span class=\"token punctuation\">(</span>endOfPaginationReached <span class=\"token operator\">=</span> movies<span class=\"token punctuation\">.</span><span class=\"token function\">isEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>e<span class=\"token operator\">:</span> Exception<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      MediatorResult<span class=\"token punctuation\">.</span><span class=\"token function\">Error</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>RemoteMediator uses the repository to store movies list and next page number in the database.\nRepository also takes care of clearing the database table when data is refreshed:</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">class</span> <span class=\"token function\">MoviesRepositoryImpl</span><span class=\"token punctuation\">(</span>\n  <span class=\"token keyword\">private</span> <span class=\"token keyword\">val</span> database<span class=\"token operator\">:</span> MoviesDatabase\n<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> MoviesRepository <span class=\"token punctuation\">{</span>\n\n  <span class=\"token keyword\">override</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=</span> database<span class=\"token punctuation\">.</span><span class=\"token function\">movies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">map</span> <span class=\"token punctuation\">{</span> it<span class=\"token punctuation\">.</span><span class=\"token function\">toDomain</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">override</span> <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">insertMovies</span><span class=\"token punctuation\">(</span>movies<span class=\"token operator\">:</span> List<span class=\"token operator\">&lt;</span>Movie<span class=\"token operator\">></span><span class=\"token punctuation\">,</span> nextPage<span class=\"token operator\">:</span> Int<span class=\"token operator\">?</span><span class=\"token punctuation\">,</span> clear<span class=\"token operator\">:</span> Boolean<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n\n    database<span class=\"token punctuation\">.</span><span class=\"token function\">withTransaction</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>clear<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        database<span class=\"token punctuation\">.</span><span class=\"token function\">movies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">clear</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n      <span class=\"token punctuation\">}</span>\n\n      database<span class=\"token punctuation\">.</span><span class=\"token function\">movies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">putMovies</span><span class=\"token punctuation\">(</span>movies<span class=\"token punctuation\">.</span><span class=\"token function\">map</span> <span class=\"token punctuation\">{</span> it<span class=\"token punctuation\">.</span><span class=\"token function\">toDbEntity</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n      <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>nextPage <span class=\"token operator\">!=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        database<span class=\"token punctuation\">.</span><span class=\"token function\">remoteKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">insertKey</span><span class=\"token punctuation\">(</span><span class=\"token function\">RemoteKey</span><span class=\"token punctuation\">(</span>MoviesDatabase<span class=\"token punctuation\">.</span>MOVIES_REMOTE_KEY<span class=\"token punctuation\">,</span> nextPage<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n      <span class=\"token punctuation\">}</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<h2>UI layer</h2>\n<p>The Pager object serves as a bridge between remote and local data sources. It is managing the page loading, prefetching, and handling the transitions between various data sources to provide a seamless and responsive flow of paginated content within your application. You can configure the page loading behavior with the following parameters:</p>\n<ul>\n<li><strong>pageSize</strong> parameter defines the number of items loaded in each page of data.</li>\n<li><strong>initialLoadSize</strong> is the number of items loaded initially when the paging library is first initialized.</li>\n<li><strong>prefetchDistance</strong> parameter determines the distance from the edge of the loaded content at which the next page should start loading.</li>\n</ul>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">class</span> <span class=\"token function\">MoviesScreenViewModel</span><span class=\"token punctuation\">(</span>\n  moviesSource<span class=\"token operator\">:</span> MoviesRemoteMediator<span class=\"token punctuation\">,</span>\n  repository<span class=\"token operator\">:</span> MoviesRepository<span class=\"token punctuation\">,</span>\n  <span class=\"token keyword\">private</span> <span class=\"token keyword\">val</span> movieDetails<span class=\"token operator\">:</span> MovieDetailsApi<span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">)</span> <span class=\"token operator\">:</span> <span class=\"token function\">ViewModel</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">val</span> moviesFlow <span class=\"token operator\">=</span> <span class=\"token function\">Pager</span><span class=\"token punctuation\">(</span>\n      config <span class=\"token operator\">=</span> <span class=\"token function\">PagingConfig</span><span class=\"token punctuation\">(</span>\n        pageSize <span class=\"token operator\">=</span> PAGE_SIZE<span class=\"token punctuation\">,</span>\n        prefetchDistance <span class=\"token operator\">=</span> PREFETCH_DISTANCE<span class=\"token punctuation\">,</span>\n        initialLoadSize <span class=\"token operator\">=</span> INITIAL_LOAD<span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      remoteMediator <span class=\"token operator\">=</span> moviesSource<span class=\"token punctuation\">,</span>\n      pagingSourceFactory <span class=\"token operator\">=</span> repository<span class=\"token punctuation\">.</span><span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">asPagingSourceFactory</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span>flow<span class=\"token punctuation\">.</span><span class=\"token function\">cachedIn</span><span class=\"token punctuation\">(</span>viewModelScope<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<h3>Consuming paging data in Jetpack Compose UI</h3>\n<p>Now, let's explore how to consume the paginated data in your Compose UI.</p>\n<p>Use the <code class=\"language-text\">collectAsLazyPagingItems</code> extension function to collect the <code class=\"language-text\">PagingData</code> and observe changes.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">val</span> movies <span class=\"token operator\">=</span> viewModel<span class=\"token punctuation\">.</span>moviesFlow<span class=\"token punctuation\">.</span><span class=\"token function\">collectAsLazyPagingItems</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>Use the <code class=\"language-text\">LazyColumn</code> or <code class=\"language-text\">LazyVerticalGrid</code> to efficiently display paginated data in your Compose UI.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token function\">LazyVerticalGrid</span><span class=\"token punctuation\">(</span>\n      modifier <span class=\"token operator\">=</span> Modifier\n        <span class=\"token punctuation\">.</span><span class=\"token function\">fillMaxSize</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n        <span class=\"token punctuation\">.</span><span class=\"token function\">padding</span><span class=\"token punctuation\">(</span><span class=\"token number\">16</span><span class=\"token punctuation\">.</span>dp<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      columns <span class=\"token operator\">=</span> GridCells<span class=\"token punctuation\">.</span><span class=\"token function\">Fixed</span><span class=\"token punctuation\">(</span><span class=\"token number\">3</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      horizontalArrangement <span class=\"token operator\">=</span> Arrangement<span class=\"token punctuation\">.</span><span class=\"token function\">spacedBy</span><span class=\"token punctuation\">(</span><span class=\"token number\">16</span><span class=\"token punctuation\">.</span>dp<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      verticalArrangement <span class=\"token operator\">=</span> Arrangement<span class=\"token punctuation\">.</span><span class=\"token function\">spacedBy</span><span class=\"token punctuation\">(</span><span class=\"token number\">16</span><span class=\"token punctuation\">.</span>dp<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\n      <span class=\"token function\">items</span><span class=\"token punctuation\">(</span>\n        count <span class=\"token operator\">=</span> movies<span class=\"token punctuation\">.</span>itemCount<span class=\"token punctuation\">,</span>\n        key <span class=\"token operator\">=</span> movies<span class=\"token punctuation\">.</span><span class=\"token function\">itemKey</span> <span class=\"token punctuation\">{</span> it<span class=\"token punctuation\">.</span>id <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span> index <span class=\"token operator\">-></span>\n\n        movies<span class=\"token punctuation\">[</span>index<span class=\"token punctuation\">]</span><span class=\"token operator\">?</span><span class=\"token punctuation\">.</span><span class=\"token function\">let</span> <span class=\"token punctuation\">{</span> movie <span class=\"token operator\">-></span>\n          <span class=\"token function\">MovieCardSmall</span><span class=\"token punctuation\">(</span>\n            movie <span class=\"token operator\">=</span> movie<span class=\"token punctuation\">,</span>\n            onClick <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> <span class=\"token function\">onClick</span><span class=\"token punctuation\">(</span>movie<span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n          <span class=\"token punctuation\">)</span>\n        <span class=\"token punctuation\">}</span>\n      <span class=\"token punctuation\">}</span>\n    <span class=\"token punctuation\">}</span></code></pre></div>\n<hr>\n<blockquote>\n<p><em>Note the usage of the key property for items. The key property uniquely identifies each item, allowing Compose to efficiently update and recycle composables as data changes.</em></p>\n</blockquote>\n<hr>\n<h3>Paging state handling</h3>\n<p>LazyPagingItems offers insights into the ongoing data loading process, allowing you to effectively manage errors during pagination. By examining the loadState.append property, you can determine the loading state when appending new items and present a user-friendly indication of the current status.</p>\n<p>For instance, the following code snippet demonstrates how to react to different loading states during item appending:</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">when</span> <span class=\"token punctuation\">(</span>movies<span class=\"token punctuation\">.</span>loadState<span class=\"token punctuation\">.</span>append<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">is</span> LoadState<span class=\"token punctuation\">.</span>Loading <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span> <span class=\"token function\">ProgressFooter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">is</span> LoadState<span class=\"token punctuation\">.</span>Error <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span> <span class=\"token function\">ErrorFooter</span><span class=\"token punctuation\">(</span>onRetryClick <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> movies<span class=\"token punctuation\">.</span><span class=\"token function\">retry</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Similarly, you can assess the loading status when the list data is refreshed by checking the loadState.refresh property. Extension functions isError() and isLoading() provide convenient checks for error and loading states, respectively.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">fun</span> LazyPagingItems<span class=\"token operator\">&lt;</span>Movie<span class=\"token operator\">></span><span class=\"token punctuation\">.</span><span class=\"token function\">isError</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Boolean <span class=\"token operator\">=</span> \n    loadState<span class=\"token punctuation\">.</span>refresh <span class=\"token keyword\">is</span> LoadState<span class=\"token punctuation\">.</span>Error <span class=\"token operator\">&amp;&amp;</span> itemSnapshotList<span class=\"token punctuation\">.</span><span class=\"token function\">isEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword\">fun</span> LazyPagingItems<span class=\"token operator\">&lt;</span>Movie<span class=\"token operator\">></span><span class=\"token punctuation\">.</span><span class=\"token function\">isLoading</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Boolean <span class=\"token operator\">=</span> \n    loadState<span class=\"token punctuation\">.</span>refresh <span class=\"token keyword\">is</span> LoadState<span class=\"token punctuation\">.</span>Loading <span class=\"token operator\">&amp;&amp;</span> itemSnapshotList<span class=\"token punctuation\">.</span><span class=\"token function\">isEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>Incorporate these checks into your UI logic to display appropriate screens based on the loading or error states. The following code snippet demonstrates how to handle loading and error states along with providing a retry option:</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">when</span> <span class=\"token punctuation\">{</span>\n   movies<span class=\"token punctuation\">.</span><span class=\"token function\">isLoading</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token function\">LoadingScreen</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n   movies<span class=\"token punctuation\">.</span><span class=\"token function\">isError</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> ErrorScreen <span class=\"token punctuation\">{</span> movies<span class=\"token punctuation\">.</span><span class=\"token function\">retry</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span>\n   <span class=\"token keyword\">else</span> <span class=\"token operator\">-></span> <span class=\"token function\">MoviesGrid</span><span class=\"token punctuation\">(</span>movies <span class=\"token operator\">=</span> movies<span class=\"token punctuation\">,</span> onClick <span class=\"token operator\">=</span> viewModel<span class=\"token operator\">::</span>onMovieClick<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Additionally, <code class=\"language-text\">LazyPagingItems</code> offers a convenient <code class=\"language-text\">retry()</code> method, allowing you to retry the last failed data loading attempt with ease.</p>\n<h3>Adding filters</h3>\n<p>Now lets add filters to our movie list to see paginated list of movies filtered by genre.</p>\n<p><img src=\"/static/paging_demo_filters-ff80a7606fb30961e2bda56bd6ed9985.gif\" alt=\"Filters UI\"></p>\n<p>We start with requesting genres from the server and saving them in our database. We will keep genre data and selection in the database so that we can observe it from our domain and UI layers.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">interface</span> MoviesApi <span class=\"token punctuation\">{</span>\n  <span class=\"token annotation builtin\">@GET</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"/3/genre/movie/list?language=en-US\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">genres</span><span class=\"token punctuation\">(</span><span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"api_key\"</span><span class=\"token punctuation\">)</span> api_key<span class=\"token operator\">:</span> String<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Response<span class=\"token operator\">&lt;</span>GenresNetworkResponse<span class=\"token operator\">></span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token annotation builtin\">@Dao</span>\n<span class=\"token keyword\">interface</span> GenresDao <span class=\"token punctuation\">{</span>\n\n  <span class=\"token annotation builtin\">@Insert</span><span class=\"token punctuation\">(</span>onConflict <span class=\"token operator\">=</span> OnConflictStrategy<span class=\"token punctuation\">.</span>REPLACE<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">putGenres</span><span class=\"token punctuation\">(</span>genres<span class=\"token operator\">:</span> List<span class=\"token operator\">&lt;</span>GenreDbEntity<span class=\"token operator\">></span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token annotation builtin\">@Upsert</span><span class=\"token punctuation\">(</span>entity <span class=\"token operator\">=</span> GenreDbEntity<span class=\"token operator\">::</span><span class=\"token keyword\">class</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">updateGenres</span><span class=\"token punctuation\">(</span>genres<span class=\"token operator\">:</span> List<span class=\"token operator\">&lt;</span>GenreDbUpdateEntity<span class=\"token operator\">></span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"SELECT * FROM genres\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">getGenres</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> List<span class=\"token operator\">&lt;</span>GenreDbEntity<span class=\"token operator\">></span>\n\n  <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"SELECT * FROM genres\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">fun</span> <span class=\"token function\">observeGenres</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Flow<span class=\"token operator\">&lt;</span>List<span class=\"token operator\">&lt;</span>GenreDbEntity<span class=\"token operator\">></span><span class=\"token operator\">></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Now we can add <code class=\"language-text\">with_genres</code> parameter to our network request:</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\">  <span class=\"token annotation builtin\">@GET</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"/3/discover/movie?language=en-US&amp;sort_by=popularity.desc\"</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">discover</span><span class=\"token punctuation\">(</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"page\"</span><span class=\"token punctuation\">)</span> page<span class=\"token operator\">:</span> Int<span class=\"token punctuation\">,</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"with_genres\"</span><span class=\"token punctuation\">)</span> genres<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span>\n    <span class=\"token annotation builtin\">@Query</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"api_key\"</span><span class=\"token punctuation\">)</span> api_key<span class=\"token operator\">:</span> String<span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Response<span class=\"token operator\">&lt;</span>MoviesNetworkResponse<span class=\"token operator\">></span></code></pre></div>\n<p>Remote mediator will get selected genres from the repository</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\">  <span class=\"token operator\">..</span><span class=\"token punctuation\">.</span>\n  <span class=\"token keyword\">val</span> genres <span class=\"token operator\">=</span> repository<span class=\"token punctuation\">.</span><span class=\"token function\">getGenreSelection</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">val</span> movies <span class=\"token operator\">=</span> moviesDataSource<span class=\"token punctuation\">.</span><span class=\"token function\">getMovies</span><span class=\"token punctuation\">(</span>page<span class=\"token punctuation\">,</span> genres<span class=\"token punctuation\">)</span>\n  <span class=\"token operator\">..</span><span class=\"token punctuation\">.</span></code></pre></div>\n<p>Every time user selects a new filter we stave it in the database and restart pagination by clearing movies in the database and resetting the page to 1.</p>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">class</span> MoviesScreenViewModel <span class=\"token punctuation\">{</span>\n\n  <span class=\"token keyword\">fun</span> <span class=\"token function\">onGenreClick</span><span class=\"token punctuation\">(</span>genreItem<span class=\"token operator\">:</span> GenreItem<span class=\"token punctuation\">)</span> <span class=\"token operator\">=</span> viewModelScope<span class=\"token punctuation\">.</span><span class=\"token function\">launch</span> <span class=\"token punctuation\">{</span>\n    genresProvider<span class=\"token punctuation\">.</span><span class=\"token function\">setSelection</span><span class=\"token punctuation\">(</span>genreItem<span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">,</span> <span class=\"token operator\">!</span>genreItem<span class=\"token punctuation\">.</span>isSelected<span class=\"token punctuation\">)</span>\n    repository<span class=\"token punctuation\">.</span><span class=\"token function\">clearMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n  \n<span class=\"token punctuation\">}</span></code></pre></div>\n<div class=\"gatsby-highlight\" data-language=\"kotlin\"><pre class=\"language-kotlin\"><code class=\"language-kotlin\"><span class=\"token keyword\">class</span> MoviesRepositoryImpl <span class=\"token punctuation\">{</span>\n\n  <span class=\"token keyword\">override</span> <span class=\"token keyword\">suspend</span> <span class=\"token keyword\">fun</span> <span class=\"token function\">clearMovies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=</span> <span class=\"token function\">withContext</span><span class=\"token punctuation\">(</span>Dispatchers<span class=\"token punctuation\">.</span>IO<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    database<span class=\"token punctuation\">.</span><span class=\"token function\">withTransaction</span> <span class=\"token punctuation\">{</span>\n      database<span class=\"token punctuation\">.</span><span class=\"token function\">movies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">clear</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n      database<span class=\"token punctuation\">.</span><span class=\"token function\">remoteKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">insertKey</span><span class=\"token punctuation\">(</span><span class=\"token function\">RemoteKey</span><span class=\"token punctuation\">(</span>MoviesDatabase<span class=\"token punctuation\">.</span>MOVIES_REMOTE_KEY<span class=\"token punctuation\">,</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n\n<span class=\"token punctuation\">}</span></code></pre></div>\n<h3>Links</h3>\n<p><br>Source code: <a href=\"https://github.com/auto1-oss/android-compose-paging\">https://github.com/auto1-oss/android-compose-paging</a></br>\n<br>Official documentation: <a href=\"https://developer.android.com/topic/libraries/architecture/paging/v3-overview\">https://developer.android.com/topic/libraries/architecture/paging/v3-overview</a></br></p>","fields":{"slug":"/android-compose-pagination/","tags":["auto1","mobile","Android"]}}},{"node":{"id":"2cda3518-ba96-5257-97f4-6f0ec1f69eb1","frontmatter":{"category":"Engineering","title":"Bug Police Officer","date":"2023-11-21","summary":"What I present today is how to use police techniques and their mindset to detect and solve bugs in software, so that you can be the best software developer that society can provide.","thumbnail":{"relativePath":"pages/bug-police-officer/bug-police-officer.png","childImageSharp":{"resolutions":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAAC20lEQVQ4y32S208TURCHF6rvvPpI/Ad8MzFIIlESaAuoAZVehEppd7fQFqjhIgiBQhEUaoFy6wUCghRrCFKQi4orhgQ0XOIFA8FoqOKTaHyg7e54zpYWUOsks2fOmd98Z85mCOIPqyNtUQf33Xp7XOZl+7oEua3AfvpgzkTZo4hIVq9oC8PQGluh7M4hpdYh0fl2aFFfh1a1AcQX2oGUWV0ol2si7bH/auAQsFptE+C4VesUZUnscPxMMxyLa2FXikXsKnIc4zOca9M5hVhbs1cT0fKzuniBkbTnSqU2iBeaA/KMZg47jmVSB9RSDjXW6BXdgv8+mf8vpDMar02qzlMG+gGkKz1cunI06Lkergid3VF1xR3URrRG2k48HZziRf31wxVrzCI01I4HZNQYh73RNBF4P7sAvUZXGdZMOMajcU1E2G3aRjDuJ4I9oAV+fQPY2fB9fbsE2OHHhg9+bkOP0dWENdP9k4JbtIP4C2qinfzq0LQTN8i+I8HTE0eZoak18H8B3/dN1rezyeKYGZx8h5L8pVjbr7EcYoTpnryG8AVLhuqYLk2Dtir/nnfrzQqA7xMLvs/s1uoylObd91ZRvboPRZUxIX2oNtxpB+osZDV0j44mR7wfKy+CRVsHGsM0++oxAwsTL8BgGGUTVAxc0r0EinJ7jXSvLlQXZmBqCTUQHBW6h1YWMhBPLkKfvsi/XprAJimfQbLCw4kVY9xZ5Qxco0ZZCenxn6MYyCmcAwSlcS1m8B3yHzXw066nh8dTtfOQSD3fldETsF12Emq1Fi6BmueSNLNcJjXDjZVL4GEJCSJybjcFaQtQDd8ZYuwDCQgOtWpgMl35CMRZrkCi3MMN5athuVgIomwPpGS7QCx3Q7WmGKrIm1ySfCSAZhNwTfCtQOwDY8v5DrVXO9wZGZ2Qkmb2J6fe5SipGV6XXIE8tKI9CNPMIEy1otjKiZAGa3ENz0MMzPoNzyOqI3a+TN4AAAAASUVORK5CYII=","width":460,"height":325,"src":"/static/19a57f273a6f7441d951955ce11fae27/b3029/bug-police-officer.png","srcSet":"/static/19a57f273a6f7441d951955ce11fae27/b3029/bug-police-officer.png 1x"}}},"authorName":"Bruno Morais","authorDescription":"Bruno is a Senior Software Engineer at AUTO1 Group.","authorAvatar":{"relativePath":"pages/bug-police-officer/avatar.jpeg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDAQX/xAAXAQEBAQEAAAAAAAAAAAAAAAABAwIE/9oADAMBAAIQAxAAAAGmbSadPSZMPIBLBy1//8QAHBAAAwABBQAAAAAAAAAAAAAAAQIDIQAQERIj/9oACAEBAAEFAqOVEql2047LLDc7A+i5H//EABcRAQEBAQAAAAAAAAAAAAAAAAEAEBL/2gAIAQMBAT8BC5jP/8QAGREAAwADAAAAAAAAAAAAAAAAAAECEBET/9oACAECAQE/AW9HSSsf/8QAGhAAAQUBAAAAAAAAAAAAAAAAAQACEBEhQf/aAAgBAQAGPwLBZRa4VFYt5Jj/xAAcEAADAAIDAQAAAAAAAAAAAAAAAREhURAxYXH/2gAIAQEAAT8ho6G+i0ElVBP0c6AzfMaH3OHLLoTIz//aAAwDAQACAAMAAAAQcC98/8QAGREAAwADAAAAAAAAAAAAAAAAABExEFGB/9oACAEDAQE/EGQbRPcf/8QAGxEAAgIDAQAAAAAAAAAAAAAAAAERMVFhscH/2gAIAQIBAT8QuM2dElucejs//8QAGxABAQEBAAMBAAAAAAAAAAAAAREAITFBYXH/2gAIAQEAAT8QEiRCoPrgpVComQJxnQidLfOE1gCkvzQ9j4TPv80LcHh6dw+UV3//2Q==","width":50,"height":50,"src":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg","srcSet":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg 1x,\n/static/8d7223890dda036e0121799406a35506/0b804/avatar.jpeg 1.5x,\n/static/8d7223890dda036e0121799406a35506/753c3/avatar.jpeg 2x,\n/static/8d7223890dda036e0121799406a35506/31ca8/avatar.jpeg 3x"}}},"headerImage":{"relativePath":"pages/bug-police-officer/bug-police-officer.png","childImageSharp":{"resolutions":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAAC20lEQVQ4y32S208TURCHF6rvvPpI/Ad8MzFIIlESaAuoAZVehEppd7fQFqjhIgiBQhEUaoFy6wUCghRrCFKQi4orhgQ0XOIFA8FoqOKTaHyg7e54zpYWUOsks2fOmd98Z85mCOIPqyNtUQf33Xp7XOZl+7oEua3AfvpgzkTZo4hIVq9oC8PQGluh7M4hpdYh0fl2aFFfh1a1AcQX2oGUWV0ol2si7bH/auAQsFptE+C4VesUZUnscPxMMxyLa2FXikXsKnIc4zOca9M5hVhbs1cT0fKzuniBkbTnSqU2iBeaA/KMZg47jmVSB9RSDjXW6BXdgv8+mf8vpDMar02qzlMG+gGkKz1cunI06Lkergid3VF1xR3URrRG2k48HZziRf31wxVrzCI01I4HZNQYh73RNBF4P7sAvUZXGdZMOMajcU1E2G3aRjDuJ4I9oAV+fQPY2fB9fbsE2OHHhg9+bkOP0dWENdP9k4JbtIP4C2qinfzq0LQTN8i+I8HTE0eZoak18H8B3/dN1rezyeKYGZx8h5L8pVjbr7EcYoTpnryG8AVLhuqYLk2Dtir/nnfrzQqA7xMLvs/s1uoylObd91ZRvboPRZUxIX2oNtxpB+osZDV0j44mR7wfKy+CRVsHGsM0++oxAwsTL8BgGGUTVAxc0r0EinJ7jXSvLlQXZmBqCTUQHBW6h1YWMhBPLkKfvsi/XprAJimfQbLCw4kVY9xZ5Qxco0ZZCenxn6MYyCmcAwSlcS1m8B3yHzXw066nh8dTtfOQSD3fldETsF12Emq1Fi6BmueSNLNcJjXDjZVL4GEJCSJybjcFaQtQDd8ZYuwDCQgOtWpgMl35CMRZrkCi3MMN5athuVgIomwPpGS7QCx3Q7WmGKrIm1ySfCSAZhNwTfCtQOwDY8v5DrVXO9wZGZ2Qkmb2J6fe5SipGV6XXIE8tKI9CNPMIEy1otjKiZAGa3ENz0MMzPoNzyOqI3a+TN4AAAAASUVORK5CYII=","width":600,"height":424,"src":"/static/19a57f273a6f7441d951955ce11fae27/b7ca8/bug-police-officer.png","srcSet":"/static/19a57f273a6f7441d951955ce11fae27/b7ca8/bug-police-officer.png 1x"}}}},"html":"<h3>Table of contents:</h3>\n<ol>\n<li>\n<p>Sense of Security</p>\n<ol>\n<li>Why does feeling safe matter?</li>\n<li>Strategic actions</li>\n<li>A test as a Cop</li>\n</ol>\n</li>\n<li>\n<p>Treat the injured first</p>\n<ol>\n<li>Prioritizing what matters</li>\n<li>The appropriate Mental Model</li>\n<li>Ask before trying to find out</li>\n</ol>\n</li>\n<li>\n<p>Trust your tools</p>\n<ol>\n<li>When less is more</li>\n<li>Efficient distribution of efforts</li>\n<li>Confidence that avoids shame</li>\n</ol>\n</li>\n<li>\n<p>Communication via Radio</p>\n<ol>\n<li>Q-code</li>\n<li>The Language and the Domain</li>\n</ol>\n</li>\n<li>Bug is in jail</li>\n</ol>\n<p><strong>What I present today is how to use police techniques and their mindset to detect and solve bugs in software, so that you can be the best software developer that society can provide.</strong></p>\n<p>For some years, I worked as a police officer in Brazil and I can say that it is a challenging career. The first step was to pass a national test, where knowledge of various laws was required. Criminal laws, traffic laws, and even the laws of physics.</p>\n<p>The second step was to pass a battery of medical exams. Almost perfect health was necessary to be able to practice the profession, in addition to having most of the parts of the human body.</p>\n<p>The third step was the psychological examination. It was necessary to have a clear mind and not have impulses different from those expected from a person who must protect other people.</p>\n<p>As a fourth part, there was also the fitness test, a test in which career candidates had to prove they had sufficient strength and speed to carry out daily police tasks. Running, pull-ups, sit-ups and long jump are examples of what was required.</p>\n<p>The last stage was the Police Academy, where for three months those from now on known as students would learn and prove the learning of several new skills: first aid, use of firearms (pistols, carbines, submachine guns, etc.), non-lethal weapons, martial arts, public policy, and many other disciplines.</p>\n<p>All this so that society receives the best police officer that its people can provide. So, what about using some of the following principles and techniques to become the best software developer that society can provide?</p>\n<h2>Sense of Security</h2>\n<h3>Why does feeling safe matter?</h3>\n<p>Without needing to be a security expert, you already know that it is impossible to have a completely safe city. Even if we reached the point of having perfect police officers, which in itself is impossible, we would not have a police officer for every citizen. In general, the recommendation is 300 police officers for every 100 thousand inhabitants.</p>\n<p>Aware of this limitation, that it is not possible to guarantee complete security for all citizens, police agencies work with the concept of a sense of security. Through strategic actions to combat crime, citizens' feeling that they are safe is increased. This mental condition gives them peace of mind when working, studying, and carrying out their daily tasks.</p>\n<h3>Strategic actions</h3>\n<p>This sense of security also affects criminals. The common visibility of police officers carrying out their duties in strategic places, as well as effective actions to combat crime, make criminals stay away from that place.</p>\n<p>Notice that ending 100% of crime is impossible, what we do well is limit its actions. From here we can extract our first lesson when dealing with software: perfect code, totally bug-free, is impossible.</p>\n<p>Despite this conclusion, the fact that it is impossible does not mean that we should simply ignore the problem. On the contrary, we can, like the police, create strategic actions to combat Bugs. To the point that Bugs themselves will run away from our code.</p>\n<h3>A test as a Cop</h3>\n<p>Test Driven Development - TDD is a strategic action that provides a feeling of security in your code. Before the crime occurs, you position police officers in a specific region. Before the Bug occurs, you position the test in a specific place in your code.</p>\n<p>Robert C. Martin, in his book \"Clean Code: A HandBook of Agile Software Craftsmanship\", teaches us that writing unit tests before writing production code is just the tip of the iceberg in defining TDD. There must be a continuous cycle of improvement, in which there is always a test covering the code you are developing and this security that the code is protected allows you to play with it, and work with it. After all, whatever problem may happen, there is a police-test there to protect you.</p>\n<h2>Treat the injured first</h2>\n<h3>Prioritizing what matters</h3>\n<p>One of the functions of Highway Police Officers is to provide first aid in the event of traffic accidents. There are often serious injuries that must be treated as urgently as possible, as even 1 minute can make the difference between life and death.</p>\n<p>The first step when arriving at a traffic accident site is to mark the location appropriately to prevent other accidents. We must use lighting devices and other appliances to make it clear to other vehicles that there is a danger there.</p>\n<p>The police officer must then check the condition of all the injured to prioritize them according to the severity of each situation.</p>\n<p>Once the treatment of each injured person has been completed and, if necessary, they have been taken to the hospital, it is time to survey the accident site. At this stage, the police officer begins to collect all the information relating to the accident to have sufficient information so that a decision can be made on the cause of the accident and, when applicable, any culprits.</p>\n<h3>The appropriate Mental Model</h3>\n<p>This is the mental model that you and I must adopt when we are faced with a Bug. Although several procedures have been adopted to prevent it from occurring, it is a fatality that can happen. It's like when the highway was well designed, the vehicles were up to date with maintenance, but even so, due to carelessness or misunderstanding on the part of the driver, an accident happens.</p>\n<p>As in the case of traffic accidents, the first step to take is to secure the environment so that the Bug does not cause other problems. If possible, we can revert the application version to one in which the Bug did not appear. We can use a feature flag to temporarily disable a feature. Regardless of the method used to stop the bleeding, the important thing is that we must focus on treating the injured first rather than looking for culprits.</p>\n<p>We have to agree with David Thomas and Andrew Hunt, in their work \"The Pragmatic Programmer: your journey to mastery\" that facing Bugs is a sensitive subject for most developers. Instead of treating the issue as a problem to be solved, some approach it with denial, pointing fingers, lame excuses, or simply apathy. It's exactly the opposite of what is expected!</p>\n<p>Instead of looking for the culprit in a traffic accident, we must first assist the victims and stop the bleeding. In software, instead of finding out who inserted the Bug, we must solve it.</p>\n<h3>Ask before trying to find out</h3>\n<p>When treating an injured person in an emergency, one approach is to use the Glasgow Scale to determine the patient's consciousness. On this scale, one of the components is the verbal response.</p>\n<p>The injured person is asked simple questions, and by analyzing the responses, we can assess the level of consciousness and consequently the level of urgency of their care.</p>\n<p>You and I must carefully read every error message that is displayed during the Bug, it may contain vital information so that we can resolve the problem.</p>\n<p>You may be thinking, but what if there is no error message? If we are just faced with an incorrect result? Well, this also happens in traffic accidents, it is not uncommon for there to be an unconscious victim who cannot answer questions.</p>\n<p>When we discussed the sense of security, we talked about the importance of tests in our application. Go and build a test that can reproduce that Bug, so you can extract the information you need to solve it.</p>\n<p>Think of these tests like the motor tests that highway patrol officers perform on unconscious victims to check their level of consciousness: do the eyes open in response to pain? Is there a pupillary response to light stimulation? Mentally translate this into software language: Does the Bug repeat itself when I enter this and that parameter? And if I insert this new argument, does it happen too?</p>\n<p>To decide on a Bug, data is needed. If you don't receive this data, you must extract it.</p>\n<h2>Trust your tools</h2>\n<h3>When less is more</h3>\n<p>Police work is very complex and your day-to-day job involves the fight for life and protection of the most important assets for society. There would be no point in having a modern and efficient selection and training process for the development of police officers if they were not given the appropriate tools for their work.</p>\n<p>And when I say appropriate, I don't mean they are minimally capable of performing the task, as the result delivered is directly related to the quality and safety of the tools. For an excellent result, not only the police officers but their tools must also be excellent.</p>\n<p>In the police agency I worked for, one of the work tools used was an Austrian pistol known worldwide for its safety and efficiency. The Glock 17 pistol was developed to meet the strict criteria of the Austrian army who wanted to replace the model used during the Second World War.</p>\n<p>In addition to requirements on durability, efficiency, and reliability, safety against accidental firing was one of the pivots of the new model.</p>\n<p>But how did a knife factory manage to deliver the pistol model that would prove to be the safest? Well, it can be said that, in addition to intense testing, the secret to reliability was simplicity and maintainability. The person responsible for the project designed the equipment with as few parts as possible, minimizing complexity. Today the Glock pistol is made with an average of 35 parts, which is a much smaller quantity than other pistols on the market.</p>\n<p>With a simpler design, so-called first-level maintenance is much easier. Equipment users can easily perform maintenance procedures, making the equipment's efficiency last for decades.</p>\n<p>Of course, you must already remember the principle with the acronym KISS, which stands for Keep it Simple (omitting the last word because I don't want to offend the reader). The secret of that renowned pistol model was not in the used materials, but in being simple. The secret of maintaining your software in good shape is to keep it simple, having a specific component for each task. When a problem arises, you will know exactly which component to look for, as each component has a responsibility, this is the principle of Single Responsibility.</p>\n<p>Because of all this, when you are at a shooting range practicing your aim, the police officer knows that if he is not hitting the target, most likely, the error is in his procedure and not in the equipment.</p>\n<p>Allan Kelly, in one of his contributions to the Book \"97 Things Every Programmer Should Know\", corroborates this idea that we should trust our tools when dealing with Bugs. Considering our tools are widely used, mature, and in use by multiple companies, we have little reason to doubt their quality.</p>\n<p>Of course, a prototype, version 0.1, is much more fragile than a library that has been on the market for several years. We are also not saying that it is impossible to have bugs in compilers.</p>\n<p>But considering how rare compiler bugs are, what we are saying is that in the search for a Bug solution, we should trust our tools and look at our piece of code first.</p>\n<h3>Efficient distribution of efforts</h3>\n<p>Imagine it as an efficient distribution of efforts. The library or compiler code has already been reviewed and tested for many years by countless people. As for that little piece of code of yours, only God knows who besides you has looked at it on your team.</p>\n<p>On one of those days, I managed to solve an unpleasant bug that occurred in one of our services. It was a non-deterministic error in our test suite, that is, the Bug only pushed out its head when no one was looking.</p>\n<p>This type of non-deterministic error generally involves three types of origin: multithread, time sensitivity, and dissynchrony between construction and cleaning of test data.</p>\n<p>Analyzing the body of the failed test, after several hours, of course, I began to strongly distrust the way we created timestamps with a native Java library. After all, the test seemed perfect to me, if there was an error it must have been somewhere else.</p>\n<h3>Confidence that avoids shame</h3>\n<p>But, aware of this lesson that we should trust our tools, especially since the component in question had been in Java for 9 years, I ignored this distrust. This saved me a lot of time and embarrassment, as I'm going to share that the error was elsewhere.</p>\n<p>Our test suite ran all tests in a single thread, so it wouldn't be a concurrency issue. But it also ran each test in a deterministic but unpredictable order. Therefore, the source of the intermittent problem must be in some specific order in which the tests were performed.</p>\n<p>After several hours of analyzing the logs, I was able to identify two tests that failed when run in sequence. It turned out that, although our tests performed a test data cleaning routine after each execution, a simple typo had silently overwritten the cleaning method in one of the tests, which generated data inconsistency if such tests were executed in a specific order.</p>\n<h2>Communication via Radio</h2>\n<h3>Q-code</h3>\n<p>I remember that one of the first systems I developed when I worked in the police was one to replace the sending of statistics through radio communication. Many years ago, each police station was supposed to send daily work statistics via radio. Data such as number of people and vehicles inspected, car accidents, etc.</p>\n<p>This took a lot of time as the audio quality of radio communications was not always ideal. The interlocutors spent a lot of time transmitting and confirming each piece of information. All this using Q-Code</p>\n<p>The Q-Code is a standardized collection of three-letter codes used in radio communication. The use of Q-code even in voice transmissions makes communication safer and more efficient. Each set of three letters, always starting with the letter Q, has a specific meaning that is known to the interlocutors.</p>\n<p>I could see that two of those codes were widely used among police officers in radio communication: QAP and QSL.</p>\n<p>QAP was used when you wanted to transmit a message. Let's say someone wanted to talk to me, so he said on the radio: \"Bruno, QAP?\". This could be translated as \"Bruno, are you ready to hear a message?\"</p>\n<p>My answer could be QAP or for example QRM. If I responded with QAP, I was signaling that yes, I was ready to receive the message. If you responded with QRM, I would be informing you that at that moment the communication is being interfered with.</p>\n<p>During communication, the second most used Q-Code appears, QSL. At the end of each message, the sender ends it with the QSL. This means that he is asking the receiver to confirm whether they received the message. It would be something like: \"There is a suspicious vehicle heading towards your team, QSL?\" If I had understood the entire message, I should respond with a simple \"QSL\". In the absence of a response, the sender repeats the message until receiving confirmation from the receiver.</p>\n<p>Each message is concluded with a QSL, and its reception is confirmed with a QSL. Does this remind you of any transmission control protocol out here, used on the internet?</p>\n<p>The main thing here is that a large amount of knowledge is condensed into three letters, in a language that provides interlocutors with efficiency and security. Eric Evans, the author of \"Domain-Driven Design: Tackling Complexity in the Heart of Software\", would agree with me that there is a principle here that should also be adopted in software development.</p>\n<h3>The Language and the Domain</h3>\n<p>A language specific to the domain, which considers possible interference from the environment, a ubiquitous language that is known by all interlocutors, can be the difference between life and death, between success and damnation of a project.</p>\n<p>When a project does not have its own language for that domain, this creates the need for numerous translations between interlocutors. Developers have to translate for domain experts. These, in turn, have to translate their demands to developers. Even among developers, there may be a need for translations.</p>\n<p>All these translations make concepts confusing and the consequences of a lack of mutual understanding can be disastrous.</p>\n<p>The importance of this in trying to arrest a Bug goes much further than compilation errors or exceptions. It goes through the swampy characteristic that the software may be logically working almost perfectly, but it is not delivering what was expected by the stakeholder.</p>\n<p>Let's look at the following pieces of code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>order<span class=\"token punctuation\">.</span>status <span class=\"token operator\">!=</span> completed<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token comment\">// (...)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>order<span class=\"token punctuation\">.</span><span class=\"token function\">isFullyRefunded</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token comment\">// (...)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Here we have a small example of two ways of expressing the same situation. In the second piece of code, a common language between developers and domain experts was used. Here, possible logical errors can be easily noticed, without the need to keep in mind what the possible states of the Order are and what the expected state is for that case.</p>\n<p>See the following code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token class-name\">Payment</span> newPayment <span class=\"token operator\">=</span> payment<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>What do you expect from this code? Does it add ten dollars to the payment? Ten transactions, inbound or outbound? Will the method create a new payment object or will it just change the value of the payment variable and create a new reference called newPayment?</p>\n<p>A lesson also taken from the book \"Clean Code: A HandBook of Agile Software Craftsmanship\" shows that clear communication must also take place between software developers. Functions must communicate exactly what they are doing.</p>\n<p>If you have to look at the function's implementation to know what it's actually doing, that's a big sign that you need to rename it.</p>\n<h2>Bug is in jail</h2>\n<p>I'm very grateful that you've made it this far, you've certainly learned a lot about police activity and how some of its principles can be applied to combat and remove Bugs from your software.</p>\n<p>By applying this knowledge you will be able to work more confidently in your code, giving you peace in your daily life and also allowing you to experiment and discover new things.</p>\n<p>Your aim will be improved and you will get straight to the point, avoiding damage instead of first looking for the culprits. You become bolder and go further because you know you can trust your tools. This leaves you more time to refine your code and seek excellence.</p>\n<p>Finally, not only will your code be safe and efficient, but its result will also be in line with what your customers expect because through effective communication you can accurately deliver what was demanded from you.</p>\n<p>The result of all this is that Bug is in jail, lives are no longer in danger, and you can go home at the end of your shift to enjoy the rest of the day with your family which is looking forward to welcoming their hero back.</p>","fields":{"slug":"/bug-police-officer/","tags":["debugging","testing","TDD","DDD"]}}}]},"authorArticles":{"totalCount":2,"edges":[{"node":{"id":"2cda3518-ba96-5257-97f4-6f0ec1f69eb1","frontmatter":{"category":"Engineering","title":"Bug Police Officer","date":"2023-11-21","summary":"What I present today is how to use police techniques and their mindset to detect and solve bugs in software, so that you can be the best software developer that society can provide.","thumbnail":{"relativePath":"pages/bug-police-officer/bug-police-officer.png","childImageSharp":{"resolutions":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAAC20lEQVQ4y32S208TURCHF6rvvPpI/Ad8MzFIIlESaAuoAZVehEppd7fQFqjhIgiBQhEUaoFy6wUCghRrCFKQi4orhgQ0XOIFA8FoqOKTaHyg7e54zpYWUOsks2fOmd98Z85mCOIPqyNtUQf33Xp7XOZl+7oEua3AfvpgzkTZo4hIVq9oC8PQGluh7M4hpdYh0fl2aFFfh1a1AcQX2oGUWV0ol2si7bH/auAQsFptE+C4VesUZUnscPxMMxyLa2FXikXsKnIc4zOca9M5hVhbs1cT0fKzuniBkbTnSqU2iBeaA/KMZg47jmVSB9RSDjXW6BXdgv8+mf8vpDMar02qzlMG+gGkKz1cunI06Lkergid3VF1xR3URrRG2k48HZziRf31wxVrzCI01I4HZNQYh73RNBF4P7sAvUZXGdZMOMajcU1E2G3aRjDuJ4I9oAV+fQPY2fB9fbsE2OHHhg9+bkOP0dWENdP9k4JbtIP4C2qinfzq0LQTN8i+I8HTE0eZoak18H8B3/dN1rezyeKYGZx8h5L8pVjbr7EcYoTpnryG8AVLhuqYLk2Dtir/nnfrzQqA7xMLvs/s1uoylObd91ZRvboPRZUxIX2oNtxpB+osZDV0j44mR7wfKy+CRVsHGsM0++oxAwsTL8BgGGUTVAxc0r0EinJ7jXSvLlQXZmBqCTUQHBW6h1YWMhBPLkKfvsi/XprAJimfQbLCw4kVY9xZ5Qxco0ZZCenxn6MYyCmcAwSlcS1m8B3yHzXw066nh8dTtfOQSD3fldETsF12Emq1Fi6BmueSNLNcJjXDjZVL4GEJCSJybjcFaQtQDd8ZYuwDCQgOtWpgMl35CMRZrkCi3MMN5athuVgIomwPpGS7QCx3Q7WmGKrIm1ySfCSAZhNwTfCtQOwDY8v5DrVXO9wZGZ2Qkmb2J6fe5SipGV6XXIE8tKI9CNPMIEy1otjKiZAGa3ENz0MMzPoNzyOqI3a+TN4AAAAASUVORK5CYII=","width":460,"height":325,"src":"/static/19a57f273a6f7441d951955ce11fae27/b3029/bug-police-officer.png","srcSet":"/static/19a57f273a6f7441d951955ce11fae27/b3029/bug-police-officer.png 1x"}}},"authorName":"Bruno Morais","authorDescription":"Bruno is a Senior Software Engineer at AUTO1 Group.","authorAvatar":{"relativePath":"pages/bug-police-officer/avatar.jpeg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDAQX/xAAXAQEBAQEAAAAAAAAAAAAAAAABAwIE/9oADAMBAAIQAxAAAAGmbSadPSZMPIBLBy1//8QAHBAAAwABBQAAAAAAAAAAAAAAAQIDIQAQERIj/9oACAEBAAEFAqOVEql2047LLDc7A+i5H//EABcRAQEBAQAAAAAAAAAAAAAAAAEAEBL/2gAIAQMBAT8BC5jP/8QAGREAAwADAAAAAAAAAAAAAAAAAAECEBET/9oACAECAQE/AW9HSSsf/8QAGhAAAQUBAAAAAAAAAAAAAAAAAQACEBEhQf/aAAgBAQAGPwLBZRa4VFYt5Jj/xAAcEAADAAIDAQAAAAAAAAAAAAAAAREhURAxYXH/2gAIAQEAAT8ho6G+i0ElVBP0c6AzfMaH3OHLLoTIz//aAAwDAQACAAMAAAAQcC98/8QAGREAAwADAAAAAAAAAAAAAAAAABExEFGB/9oACAEDAQE/EGQbRPcf/8QAGxEAAgIDAQAAAAAAAAAAAAAAAAERMVFhscH/2gAIAQIBAT8QuM2dElucejs//8QAGxABAQEBAAMBAAAAAAAAAAAAAREAITFBYXH/2gAIAQEAAT8QEiRCoPrgpVComQJxnQidLfOE1gCkvzQ9j4TPv80LcHh6dw+UV3//2Q==","width":50,"height":50,"src":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg","srcSet":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg 1x,\n/static/8d7223890dda036e0121799406a35506/0b804/avatar.jpeg 1.5x,\n/static/8d7223890dda036e0121799406a35506/753c3/avatar.jpeg 2x,\n/static/8d7223890dda036e0121799406a35506/31ca8/avatar.jpeg 3x"}}},"headerImage":{"relativePath":"pages/bug-police-officer/bug-police-officer.png","childImageSharp":{"resolutions":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAAC20lEQVQ4y32S208TURCHF6rvvPpI/Ad8MzFIIlESaAuoAZVehEppd7fQFqjhIgiBQhEUaoFy6wUCghRrCFKQi4orhgQ0XOIFA8FoqOKTaHyg7e54zpYWUOsks2fOmd98Z85mCOIPqyNtUQf33Xp7XOZl+7oEua3AfvpgzkTZo4hIVq9oC8PQGluh7M4hpdYh0fl2aFFfh1a1AcQX2oGUWV0ol2si7bH/auAQsFptE+C4VesUZUnscPxMMxyLa2FXikXsKnIc4zOca9M5hVhbs1cT0fKzuniBkbTnSqU2iBeaA/KMZg47jmVSB9RSDjXW6BXdgv8+mf8vpDMar02qzlMG+gGkKz1cunI06Lkergid3VF1xR3URrRG2k48HZziRf31wxVrzCI01I4HZNQYh73RNBF4P7sAvUZXGdZMOMajcU1E2G3aRjDuJ4I9oAV+fQPY2fB9fbsE2OHHhg9+bkOP0dWENdP9k4JbtIP4C2qinfzq0LQTN8i+I8HTE0eZoak18H8B3/dN1rezyeKYGZx8h5L8pVjbr7EcYoTpnryG8AVLhuqYLk2Dtir/nnfrzQqA7xMLvs/s1uoylObd91ZRvboPRZUxIX2oNtxpB+osZDV0j44mR7wfKy+CRVsHGsM0++oxAwsTL8BgGGUTVAxc0r0EinJ7jXSvLlQXZmBqCTUQHBW6h1YWMhBPLkKfvsi/XprAJimfQbLCw4kVY9xZ5Qxco0ZZCenxn6MYyCmcAwSlcS1m8B3yHzXw066nh8dTtfOQSD3fldETsF12Emq1Fi6BmueSNLNcJjXDjZVL4GEJCSJybjcFaQtQDd8ZYuwDCQgOtWpgMl35CMRZrkCi3MMN5athuVgIomwPpGS7QCx3Q7WmGKrIm1ySfCSAZhNwTfCtQOwDY8v5DrVXO9wZGZ2Qkmb2J6fe5SipGV6XXIE8tKI9CNPMIEy1otjKiZAGa3ENz0MMzPoNzyOqI3a+TN4AAAAASUVORK5CYII=","width":600,"height":424,"src":"/static/19a57f273a6f7441d951955ce11fae27/b7ca8/bug-police-officer.png","srcSet":"/static/19a57f273a6f7441d951955ce11fae27/b7ca8/bug-police-officer.png 1x"}}}},"html":"<h3>Table of contents:</h3>\n<ol>\n<li>\n<p>Sense of Security</p>\n<ol>\n<li>Why does feeling safe matter?</li>\n<li>Strategic actions</li>\n<li>A test as a Cop</li>\n</ol>\n</li>\n<li>\n<p>Treat the injured first</p>\n<ol>\n<li>Prioritizing what matters</li>\n<li>The appropriate Mental Model</li>\n<li>Ask before trying to find out</li>\n</ol>\n</li>\n<li>\n<p>Trust your tools</p>\n<ol>\n<li>When less is more</li>\n<li>Efficient distribution of efforts</li>\n<li>Confidence that avoids shame</li>\n</ol>\n</li>\n<li>\n<p>Communication via Radio</p>\n<ol>\n<li>Q-code</li>\n<li>The Language and the Domain</li>\n</ol>\n</li>\n<li>Bug is in jail</li>\n</ol>\n<p><strong>What I present today is how to use police techniques and their mindset to detect and solve bugs in software, so that you can be the best software developer that society can provide.</strong></p>\n<p>For some years, I worked as a police officer in Brazil and I can say that it is a challenging career. The first step was to pass a national test, where knowledge of various laws was required. Criminal laws, traffic laws, and even the laws of physics.</p>\n<p>The second step was to pass a battery of medical exams. Almost perfect health was necessary to be able to practice the profession, in addition to having most of the parts of the human body.</p>\n<p>The third step was the psychological examination. It was necessary to have a clear mind and not have impulses different from those expected from a person who must protect other people.</p>\n<p>As a fourth part, there was also the fitness test, a test in which career candidates had to prove they had sufficient strength and speed to carry out daily police tasks. Running, pull-ups, sit-ups and long jump are examples of what was required.</p>\n<p>The last stage was the Police Academy, where for three months those from now on known as students would learn and prove the learning of several new skills: first aid, use of firearms (pistols, carbines, submachine guns, etc.), non-lethal weapons, martial arts, public policy, and many other disciplines.</p>\n<p>All this so that society receives the best police officer that its people can provide. So, what about using some of the following principles and techniques to become the best software developer that society can provide?</p>\n<h2>Sense of Security</h2>\n<h3>Why does feeling safe matter?</h3>\n<p>Without needing to be a security expert, you already know that it is impossible to have a completely safe city. Even if we reached the point of having perfect police officers, which in itself is impossible, we would not have a police officer for every citizen. In general, the recommendation is 300 police officers for every 100 thousand inhabitants.</p>\n<p>Aware of this limitation, that it is not possible to guarantee complete security for all citizens, police agencies work with the concept of a sense of security. Through strategic actions to combat crime, citizens' feeling that they are safe is increased. This mental condition gives them peace of mind when working, studying, and carrying out their daily tasks.</p>\n<h3>Strategic actions</h3>\n<p>This sense of security also affects criminals. The common visibility of police officers carrying out their duties in strategic places, as well as effective actions to combat crime, make criminals stay away from that place.</p>\n<p>Notice that ending 100% of crime is impossible, what we do well is limit its actions. From here we can extract our first lesson when dealing with software: perfect code, totally bug-free, is impossible.</p>\n<p>Despite this conclusion, the fact that it is impossible does not mean that we should simply ignore the problem. On the contrary, we can, like the police, create strategic actions to combat Bugs. To the point that Bugs themselves will run away from our code.</p>\n<h3>A test as a Cop</h3>\n<p>Test Driven Development - TDD is a strategic action that provides a feeling of security in your code. Before the crime occurs, you position police officers in a specific region. Before the Bug occurs, you position the test in a specific place in your code.</p>\n<p>Robert C. Martin, in his book \"Clean Code: A HandBook of Agile Software Craftsmanship\", teaches us that writing unit tests before writing production code is just the tip of the iceberg in defining TDD. There must be a continuous cycle of improvement, in which there is always a test covering the code you are developing and this security that the code is protected allows you to play with it, and work with it. After all, whatever problem may happen, there is a police-test there to protect you.</p>\n<h2>Treat the injured first</h2>\n<h3>Prioritizing what matters</h3>\n<p>One of the functions of Highway Police Officers is to provide first aid in the event of traffic accidents. There are often serious injuries that must be treated as urgently as possible, as even 1 minute can make the difference between life and death.</p>\n<p>The first step when arriving at a traffic accident site is to mark the location appropriately to prevent other accidents. We must use lighting devices and other appliances to make it clear to other vehicles that there is a danger there.</p>\n<p>The police officer must then check the condition of all the injured to prioritize them according to the severity of each situation.</p>\n<p>Once the treatment of each injured person has been completed and, if necessary, they have been taken to the hospital, it is time to survey the accident site. At this stage, the police officer begins to collect all the information relating to the accident to have sufficient information so that a decision can be made on the cause of the accident and, when applicable, any culprits.</p>\n<h3>The appropriate Mental Model</h3>\n<p>This is the mental model that you and I must adopt when we are faced with a Bug. Although several procedures have been adopted to prevent it from occurring, it is a fatality that can happen. It's like when the highway was well designed, the vehicles were up to date with maintenance, but even so, due to carelessness or misunderstanding on the part of the driver, an accident happens.</p>\n<p>As in the case of traffic accidents, the first step to take is to secure the environment so that the Bug does not cause other problems. If possible, we can revert the application version to one in which the Bug did not appear. We can use a feature flag to temporarily disable a feature. Regardless of the method used to stop the bleeding, the important thing is that we must focus on treating the injured first rather than looking for culprits.</p>\n<p>We have to agree with David Thomas and Andrew Hunt, in their work \"The Pragmatic Programmer: your journey to mastery\" that facing Bugs is a sensitive subject for most developers. Instead of treating the issue as a problem to be solved, some approach it with denial, pointing fingers, lame excuses, or simply apathy. It's exactly the opposite of what is expected!</p>\n<p>Instead of looking for the culprit in a traffic accident, we must first assist the victims and stop the bleeding. In software, instead of finding out who inserted the Bug, we must solve it.</p>\n<h3>Ask before trying to find out</h3>\n<p>When treating an injured person in an emergency, one approach is to use the Glasgow Scale to determine the patient's consciousness. On this scale, one of the components is the verbal response.</p>\n<p>The injured person is asked simple questions, and by analyzing the responses, we can assess the level of consciousness and consequently the level of urgency of their care.</p>\n<p>You and I must carefully read every error message that is displayed during the Bug, it may contain vital information so that we can resolve the problem.</p>\n<p>You may be thinking, but what if there is no error message? If we are just faced with an incorrect result? Well, this also happens in traffic accidents, it is not uncommon for there to be an unconscious victim who cannot answer questions.</p>\n<p>When we discussed the sense of security, we talked about the importance of tests in our application. Go and build a test that can reproduce that Bug, so you can extract the information you need to solve it.</p>\n<p>Think of these tests like the motor tests that highway patrol officers perform on unconscious victims to check their level of consciousness: do the eyes open in response to pain? Is there a pupillary response to light stimulation? Mentally translate this into software language: Does the Bug repeat itself when I enter this and that parameter? And if I insert this new argument, does it happen too?</p>\n<p>To decide on a Bug, data is needed. If you don't receive this data, you must extract it.</p>\n<h2>Trust your tools</h2>\n<h3>When less is more</h3>\n<p>Police work is very complex and your day-to-day job involves the fight for life and protection of the most important assets for society. There would be no point in having a modern and efficient selection and training process for the development of police officers if they were not given the appropriate tools for their work.</p>\n<p>And when I say appropriate, I don't mean they are minimally capable of performing the task, as the result delivered is directly related to the quality and safety of the tools. For an excellent result, not only the police officers but their tools must also be excellent.</p>\n<p>In the police agency I worked for, one of the work tools used was an Austrian pistol known worldwide for its safety and efficiency. The Glock 17 pistol was developed to meet the strict criteria of the Austrian army who wanted to replace the model used during the Second World War.</p>\n<p>In addition to requirements on durability, efficiency, and reliability, safety against accidental firing was one of the pivots of the new model.</p>\n<p>But how did a knife factory manage to deliver the pistol model that would prove to be the safest? Well, it can be said that, in addition to intense testing, the secret to reliability was simplicity and maintainability. The person responsible for the project designed the equipment with as few parts as possible, minimizing complexity. Today the Glock pistol is made with an average of 35 parts, which is a much smaller quantity than other pistols on the market.</p>\n<p>With a simpler design, so-called first-level maintenance is much easier. Equipment users can easily perform maintenance procedures, making the equipment's efficiency last for decades.</p>\n<p>Of course, you must already remember the principle with the acronym KISS, which stands for Keep it Simple (omitting the last word because I don't want to offend the reader). The secret of that renowned pistol model was not in the used materials, but in being simple. The secret of maintaining your software in good shape is to keep it simple, having a specific component for each task. When a problem arises, you will know exactly which component to look for, as each component has a responsibility, this is the principle of Single Responsibility.</p>\n<p>Because of all this, when you are at a shooting range practicing your aim, the police officer knows that if he is not hitting the target, most likely, the error is in his procedure and not in the equipment.</p>\n<p>Allan Kelly, in one of his contributions to the Book \"97 Things Every Programmer Should Know\", corroborates this idea that we should trust our tools when dealing with Bugs. Considering our tools are widely used, mature, and in use by multiple companies, we have little reason to doubt their quality.</p>\n<p>Of course, a prototype, version 0.1, is much more fragile than a library that has been on the market for several years. We are also not saying that it is impossible to have bugs in compilers.</p>\n<p>But considering how rare compiler bugs are, what we are saying is that in the search for a Bug solution, we should trust our tools and look at our piece of code first.</p>\n<h3>Efficient distribution of efforts</h3>\n<p>Imagine it as an efficient distribution of efforts. The library or compiler code has already been reviewed and tested for many years by countless people. As for that little piece of code of yours, only God knows who besides you has looked at it on your team.</p>\n<p>On one of those days, I managed to solve an unpleasant bug that occurred in one of our services. It was a non-deterministic error in our test suite, that is, the Bug only pushed out its head when no one was looking.</p>\n<p>This type of non-deterministic error generally involves three types of origin: multithread, time sensitivity, and dissynchrony between construction and cleaning of test data.</p>\n<p>Analyzing the body of the failed test, after several hours, of course, I began to strongly distrust the way we created timestamps with a native Java library. After all, the test seemed perfect to me, if there was an error it must have been somewhere else.</p>\n<h3>Confidence that avoids shame</h3>\n<p>But, aware of this lesson that we should trust our tools, especially since the component in question had been in Java for 9 years, I ignored this distrust. This saved me a lot of time and embarrassment, as I'm going to share that the error was elsewhere.</p>\n<p>Our test suite ran all tests in a single thread, so it wouldn't be a concurrency issue. But it also ran each test in a deterministic but unpredictable order. Therefore, the source of the intermittent problem must be in some specific order in which the tests were performed.</p>\n<p>After several hours of analyzing the logs, I was able to identify two tests that failed when run in sequence. It turned out that, although our tests performed a test data cleaning routine after each execution, a simple typo had silently overwritten the cleaning method in one of the tests, which generated data inconsistency if such tests were executed in a specific order.</p>\n<h2>Communication via Radio</h2>\n<h3>Q-code</h3>\n<p>I remember that one of the first systems I developed when I worked in the police was one to replace the sending of statistics through radio communication. Many years ago, each police station was supposed to send daily work statistics via radio. Data such as number of people and vehicles inspected, car accidents, etc.</p>\n<p>This took a lot of time as the audio quality of radio communications was not always ideal. The interlocutors spent a lot of time transmitting and confirming each piece of information. All this using Q-Code</p>\n<p>The Q-Code is a standardized collection of three-letter codes used in radio communication. The use of Q-code even in voice transmissions makes communication safer and more efficient. Each set of three letters, always starting with the letter Q, has a specific meaning that is known to the interlocutors.</p>\n<p>I could see that two of those codes were widely used among police officers in radio communication: QAP and QSL.</p>\n<p>QAP was used when you wanted to transmit a message. Let's say someone wanted to talk to me, so he said on the radio: \"Bruno, QAP?\". This could be translated as \"Bruno, are you ready to hear a message?\"</p>\n<p>My answer could be QAP or for example QRM. If I responded with QAP, I was signaling that yes, I was ready to receive the message. If you responded with QRM, I would be informing you that at that moment the communication is being interfered with.</p>\n<p>During communication, the second most used Q-Code appears, QSL. At the end of each message, the sender ends it with the QSL. This means that he is asking the receiver to confirm whether they received the message. It would be something like: \"There is a suspicious vehicle heading towards your team, QSL?\" If I had understood the entire message, I should respond with a simple \"QSL\". In the absence of a response, the sender repeats the message until receiving confirmation from the receiver.</p>\n<p>Each message is concluded with a QSL, and its reception is confirmed with a QSL. Does this remind you of any transmission control protocol out here, used on the internet?</p>\n<p>The main thing here is that a large amount of knowledge is condensed into three letters, in a language that provides interlocutors with efficiency and security. Eric Evans, the author of \"Domain-Driven Design: Tackling Complexity in the Heart of Software\", would agree with me that there is a principle here that should also be adopted in software development.</p>\n<h3>The Language and the Domain</h3>\n<p>A language specific to the domain, which considers possible interference from the environment, a ubiquitous language that is known by all interlocutors, can be the difference between life and death, between success and damnation of a project.</p>\n<p>When a project does not have its own language for that domain, this creates the need for numerous translations between interlocutors. Developers have to translate for domain experts. These, in turn, have to translate their demands to developers. Even among developers, there may be a need for translations.</p>\n<p>All these translations make concepts confusing and the consequences of a lack of mutual understanding can be disastrous.</p>\n<p>The importance of this in trying to arrest a Bug goes much further than compilation errors or exceptions. It goes through the swampy characteristic that the software may be logically working almost perfectly, but it is not delivering what was expected by the stakeholder.</p>\n<p>Let's look at the following pieces of code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>order<span class=\"token punctuation\">.</span>status <span class=\"token operator\">!=</span> completed<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token comment\">// (...)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>order<span class=\"token punctuation\">.</span><span class=\"token function\">isFullyRefunded</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n     <span class=\"token comment\">// (...)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Here we have a small example of two ways of expressing the same situation. In the second piece of code, a common language between developers and domain experts was used. Here, possible logical errors can be easily noticed, without the need to keep in mind what the possible states of the Order are and what the expected state is for that case.</p>\n<p>See the following code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token class-name\">Payment</span> newPayment <span class=\"token operator\">=</span> payment<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>What do you expect from this code? Does it add ten dollars to the payment? Ten transactions, inbound or outbound? Will the method create a new payment object or will it just change the value of the payment variable and create a new reference called newPayment?</p>\n<p>A lesson also taken from the book \"Clean Code: A HandBook of Agile Software Craftsmanship\" shows that clear communication must also take place between software developers. Functions must communicate exactly what they are doing.</p>\n<p>If you have to look at the function's implementation to know what it's actually doing, that's a big sign that you need to rename it.</p>\n<h2>Bug is in jail</h2>\n<p>I'm very grateful that you've made it this far, you've certainly learned a lot about police activity and how some of its principles can be applied to combat and remove Bugs from your software.</p>\n<p>By applying this knowledge you will be able to work more confidently in your code, giving you peace in your daily life and also allowing you to experiment and discover new things.</p>\n<p>Your aim will be improved and you will get straight to the point, avoiding damage instead of first looking for the culprits. You become bolder and go further because you know you can trust your tools. This leaves you more time to refine your code and seek excellence.</p>\n<p>Finally, not only will your code be safe and efficient, but its result will also be in line with what your customers expect because through effective communication you can accurately deliver what was demanded from you.</p>\n<p>The result of all this is that Bug is in jail, lives are no longer in danger, and you can go home at the end of your shift to enjoy the rest of the day with your family which is looking forward to welcoming their hero back.</p>","fields":{"slug":"/bug-police-officer/","tags":["debugging","testing","TDD","DDD"]}}},{"node":{"id":"d53c49b4-fba1-5071-b078-79bbf0f23344","frontmatter":{"category":"Engineering","title":"A wild Thread appeared! Multithreaded Testing and Thread-safety","date":"2023-02-24","summary":"Today we'll talk a little about how threads work on computers and how to extract more value from concurrent tasks. For this, I will present techniques on how to develop and especially how to test code that uses multiple threads, avoiding the main pitfalls that involve this theme. Of course, along the way, you'll also learn more about Java's Concurrent package, non-blocking algorithms, immutability, and more. However, we need to start by talking a little bit about butter.","thumbnail":null,"authorName":"Bruno Morais","authorDescription":"Bruno is a Senior Software Engineer at AUTO1 Group.","authorAvatar":{"relativePath":"pages/a-wild-thread-appeared-multithreaded-testing-and-thread-safety/avatar.jpeg","childImageSharp":{"resolutions":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAUABQDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAQDAQX/xAAXAQEBAQEAAAAAAAAAAAAAAAABAwIE/9oADAMBAAIQAxAAAAGmbSadPSZMPIBLBy1//8QAHBAAAwABBQAAAAAAAAAAAAAAAQIDIQAQERIj/9oACAEBAAEFAqOVEql2047LLDc7A+i5H//EABcRAQEBAQAAAAAAAAAAAAAAAAEAEBL/2gAIAQMBAT8BC5jP/8QAGREAAwADAAAAAAAAAAAAAAAAAAECEBET/9oACAECAQE/AW9HSSsf/8QAGhAAAQUBAAAAAAAAAAAAAAAAAQACEBEhQf/aAAgBAQAGPwLBZRa4VFYt5Jj/xAAcEAADAAIDAQAAAAAAAAAAAAAAAREhURAxYXH/2gAIAQEAAT8ho6G+i0ElVBP0c6AzfMaH3OHLLoTIz//aAAwDAQACAAMAAAAQcC98/8QAGREAAwADAAAAAAAAAAAAAAAAABExEFGB/9oACAEDAQE/EGQbRPcf/8QAGxEAAgIDAQAAAAAAAAAAAAAAAAERMVFhscH/2gAIAQIBAT8QuM2dElucejs//8QAGxABAQEBAAMBAAAAAAAAAAAAAREAITFBYXH/2gAIAQEAAT8QEiRCoPrgpVComQJxnQidLfOE1gCkvzQ9j4TPv80LcHh6dw+UV3//2Q==","width":50,"height":50,"src":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg","srcSet":"/static/8d7223890dda036e0121799406a35506/d2d31/avatar.jpeg 1x,\n/static/8d7223890dda036e0121799406a35506/0b804/avatar.jpeg 1.5x,\n/static/8d7223890dda036e0121799406a35506/753c3/avatar.jpeg 2x,\n/static/8d7223890dda036e0121799406a35506/31ca8/avatar.jpeg 3x"}}},"headerImage":null},"html":"<h1>A wild Thread appeared! Multithreaded Testing and Thread-safety</h1>\n<p><a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/0fc0ab78e60b645d61810b733618e058/a231e/wild_appeared.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 568px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 73.94366197183098%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAPCAYAAADkmO9VAAAACXBIWXMAAAsSAAALEgHS3X78AAAC60lEQVQ4y4VTzU8TURDfszev/jV6MzHxaGLi0YsHSTDGaKBUY2LUGhC/QBCUSktrAWkLLVDaSkERTCr02wKlBftBMUDbLbu03RnnPdgGNOgkv8y8eTO/mZ15K9RqtX2C/C8oisI1AMiSLMuIyG2mD+8rpAuEZoEukBzI9Elg90yyuU0MhiIYCkdxKRjBdDaHqhwWvyuwYDKAgWxQ7T99lAObm3mIL6/C7Nw8DBqMYB91gry/D4eEEkHLCavVKhCYk+NoZ+ysauYTxTJ+GLKi0TSIU14f7knSUcKDDll1tXWFksrlMpYlmYKUOplKyEbY129Gg8GE0Vic5zJ/nZB5fiZXIBELY6kk4ox3HOdnxnHBacHMxro6n3qnlUoFI9EfGPi2gDvb238T6nuHUNfwCJy6x/iiTYcPHj7BtrZ2DLxrxWxylROycVRrhGqF2/VFKDU+rmOEugc6PH3qDGgabkHns1a413wHmm7egOeNVyG5HOfLYEmHYzkJrPsDwm7tfbx09gLoNC04+8mD3iEDfveO4RfPJP88Vfyhr+iasaF3zkkYR/fnUZyYtmImvw5ra0ncLexKFKYVLp+/jhfPXYH2xmvwtEUDrikf1KiqvF+BYrEIdrsdbDY7mC0m6HrTAa+7O0h3kn4FnV0v4ePIMFgsFszlctLeXlkrmE0WHDCYwdTfD/19b8HpdIDDMUZwkO2EkZERlqCQrbgmXYp7yq143B6u2dlqtdZcLpcyPDwsuiYnWgSfbxp3drahWCpBJpuDZDJ5bD7ssxcXFzEajWImk8FIhP6UUJCfE4lE/cmRX8rn8xphaWkJ11PrkM1mIR6Pw8rKCtBbA1EU+TKIEAqFAi+0tbVF81qDYDAIgUAANjY2gK+YJBaLSel0ulmgQPT7/VQ1hOFwGFOpFLIi7Mze3v9E/c8pXqY5Ngl6vX5vYGBANJvNosFgEFXbaDSWyOagOZZoOXXYbDYOsoukizRfsben59d7vf72b8fyJLW9nd3vAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n    ></span>\n    <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;box-shadow:inset 0px 0px 0px 400px white;\"\n        alt=\"wild-appeared\"\n        title=\"\"\n        src=\"/static/0fc0ab78e60b645d61810b733618e058/a231e/wild_appeared.png\"\n        srcset=\"/static/0fc0ab78e60b645d61810b733618e058/01db7/wild_appeared.png 148w,\n/static/0fc0ab78e60b645d61810b733618e058/ede92/wild_appeared.png 295w,\n/static/0fc0ab78e60b645d61810b733618e058/a231e/wild_appeared.png 568w\"\n        sizes=\"(max-width: 568px) 100vw, 568px\"\n      />\n  </span>\n  </a></p>\n<p>Today we'll talk a little about how threads work on computers and how to extract more value from concurrent tasks. For this, I will present techniques on how to develop and especially how to test code that uses multiple threads, avoiding the main pitfalls that involve this theme.</p>\n<p>Of course, along the way, you'll also learn more about Java's Concurrent package, non-blocking algorithms, immutability, and more. However, we need to start by talking a little bit about butter.</p>\n<p>Butter is a product that is part of everyday life for many people. Present in cookies, cakes, bread, sweets, and snacks, as well as other culinary items that make our mouths water just imagining.</p>\n<p>Butter is not recent; we have historical records of its manufacturing process over 2500 BC. Most often made with cow's milk but it can also be produced with the milk of other mammals such as sheep, goats, and buffalo.</p>\n<p>Salt has been added to butter since ancient times as a method of preservation, but over time salt has lost this importance as the supply chain has become generally refrigerated. Today, so to speak, salt is added only for taste.</p>\n<p>Sometimes food colorings are added to butter, in Brazil, for example, it is common to use Annatto seeds.</p>\n<p>And one thing I really like to eat is bread and butter. In fact, a delicious slice of bread just out of the oven with a little butter on top, which starts to melt on the hot bread. Oh, how delicious!</p>\n<p>Sadly, my wife happens to like hazelnut cream on top of her bread. And this created a problem with our breakfast, now we have to get two knives dirty to apply the toppings that we like. A knife for the butter, and another knife for the hazelnut cream.</p>\n<p>However, our concern for the environment and its natural resources, which are not unlimited, made us rethink this process.</p>\n<p>Let's turn this problem into a software. After all, Moore's law has given us processors with more and more cores, and as nowadays virtually all computers have multiple execution cores, a computer must be able to simulate my kitchen.</p>\n<p>First, we need a straightforward Bread that takes 50 milliseconds to be ready (what a blazing fast oven, huh!?)</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">public</span> <span class=\"token keyword\">class</span> <span class=\"token class-name\">Bread</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">private</span> <span class=\"token class-name\">String</span> name <span class=\"token operator\">=</span> <span class=\"token string\">\"bread\"</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token class-name\">TimeUnit</span><span class=\"token punctuation\">.</span>MILLISECONDS<span class=\"token punctuation\">.</span><span class=\"token function\">sleep</span><span class=\"token punctuation\">(</span><span class=\"token number\">50</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">InterruptedException</span> e<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">.</span><span class=\"token function\">currentThread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">interrupt</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token keyword\">void</span> <span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> toppingName<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name <span class=\"token operator\">+=</span> <span class=\"token string\">\" with \"</span> <span class=\"token operator\">+</span> toppingName<span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token annotation punctuation\">@Override</span>\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">String</span> <span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name<span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Now we need a naive knife that can apply the topping to our bread.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">public</span> <span class=\"token keyword\">class</span> <span class=\"token class-name\">Knife</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">private</span> <span class=\"token class-name\">String</span> topping<span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> topping<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>topping <span class=\"token operator\">=</span> topping<span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">this</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Bread</span> bread<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>topping <span class=\"token operator\">!=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           bread<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span>topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n           topping <span class=\"token operator\">=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">this</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>We can verify that everything is working using a test. I'm using the <a href=\"https://assertj.github.io/doc/\"><ins>AssertJ</ins></a> library, a java assertion library which I do recommend that you have a look on at, as it could enhance your tests and improve readability.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenKnifeWhenApplyToppingToThenChangeBreadName</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"bread with butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>It seems good, lets's see what happens when we are hungry and want 10 pieces of bread made at the same time! For that, we will need a basket where we will put all the cooked bread.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenHungryThenCook10BreadsAtTheSameTime</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Bread</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">int</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> <span class=\"token number\">10</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span>\n               <span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       basket<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>basket<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">isNotEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">allSatisfy</span><span class=\"token punctuation\">(</span>bread <span class=\"token operator\">-></span> <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"bread with butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Oops!, it worked, but it took too much time. Each bread takes 50 milliseconds to be ready, so now the whole process is taking 500 milliseconds. If we consider the real-world cook time for bread, it could take hours to cook all those pieces of bread like this.</p>\n<h2>Multiple Threads</h2>\n<p>I know what to do, we just need more workforce! I will call my wife to help me. As I said, the majority of current computer machines have more than one core, which allows us to work in parallel. Joshua Bloch, in his book Effective Java, warns that we should prefer executors, tasks, and streams to threads, but for simplicity let me demonstrate this problem using threads by hand.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenHungryThenCook10BreadsWithMyWife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Bread</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token class-name\">Runnable</span> preparation <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span>\n               <span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       basket<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">int</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> <span class=\"token number\">5</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">var</span> me <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">var</span> myWife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       me<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       myWife<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>basket<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">isNotEmpty</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">allSatisfy</span><span class=\"token punctuation\">(</span>bread <span class=\"token operator\">-></span> <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"bread with butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>But wait, the test is failing, what is going wrong?</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpecting actual not to be empty</code></pre></div>\n<p>It is like the basket is empty, but we didn't change the process at all despite adding the new threads. Yes, it is a common problem that every software engineer faces when starting to work with multiple threads (or multi-thread apps).</p>\n<h2>Java's Concurrent Package</h2>\n<p>In fact, there is a thread that is responsible for running the test suite which executes each step on our test in sequential order. But when we delegate part of the process to other threads, it follows its flow without waiting for them to finish their job. When it reaches the assertion, the previously created threads have not finished creating their bread. That is why our basket is empty.</p>\n<p>Please, don't listen to this evil inner thought suggesting that it is just a matter of creating a Thread.sleep() or something like that, so that the assertion waits for the other threads. It will give you a slow and fragile test. On one hand, if you give it a big delay time, it will slow down your tests. On the other hand, with a small delay, the result could vary depending on the processing power of the machine where the tests are being executed.</p>\n<h3>Testing</h3>\n<p>The answer for cases like those is to use some tools from java's concurrent package. We have to ensure that both workers start to do their job at the same time. As a second requirement, we need that the test thread verifies the assertion only after the job is done by the other threads. For this, we can use a CountDownLatch like those below. CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. It does it by holding the thread until the count reaches 0.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenHungryThenCook10BreadsWithMyWife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">throws</span> <span class=\"token class-name\">InterruptedException</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Bread</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> startGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> endGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token class-name\">Runnable</span> preparation <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n           startGate<span class=\"token punctuation\">.</span><span class=\"token function\">await</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">InterruptedException</span> e<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">RuntimeException</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n       <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span>\n               <span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       basket<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       endGate<span class=\"token punctuation\">.</span><span class=\"token function\">countDown</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">int</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> <span class=\"token number\">5</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">var</span> me <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">var</span> myWife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       me<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       myWife<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   startGate<span class=\"token punctuation\">.</span><span class=\"token function\">countDown</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   endGate<span class=\"token punctuation\">.</span><span class=\"token function\">await</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>basket<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">hasSize</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">allSatisfy</span><span class=\"token punctuation\">(</span>bread <span class=\"token operator\">-></span> <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"bread with butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The startGate will hold all threads so that they start virtually at the same time when the test execution reaches the startGate.countDown(). After that, the assertion will not be verified before the endGate reaches zero, which will only happen when all threads have finished their tasks.</p>\n<p>The bad news is that we have a problem with this current implementation. If you are unlucky enough (or simply repeat this test a few times), you will face the following error:</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpected size:&lt;10&gt; but was:&lt;6&gt; in:\n&lt;[bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with butter]&gt;</code></pre></div>\n<p>It happened because we are using as our basket an ArrayList, which states in its documentation:</p>\n<p>\"<em>Note that this implementation <strong>is not synchronized</strong>. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.</em>\"</p>\n<h3>Synchronized Collections</h3>\n<p>In other words, this implementation of the List interface is not thread-safe. Once more, to face this issue, we have at our disposal other collection implementations on the concurrent package. Instead of ArrayList, we could use CopyOnWriteArrayList or a ConcurrentLinkedQueue.</p>\n<p>As the first one is more efficient in use cases where mutations are less frequent than other operations, let's stick with ConcurrentLinkedQueue.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>But as soon as you execute the test repeatedly, you will see errors like those:</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpecting all elements of:\n  &lt;[bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with null,\n    bread with null,\n    bread with butter,\n    bread with butter,\n    bread with butter,\n    bread with butter]&gt;\nto satisfy given requirements, but these elements did not:\n\n  &lt;bread with null&gt; \nExpecting actual&#39;s toString() to return:\n  &lt;&quot;bread with butter&quot;&gt;\nbut was:\n  &lt;bread with null&gt;</code></pre></div>\n<p>We should have a problem in another part of the code, could you imagine where it is?</p>\n<p>Things get worse when my wife starts to make her bread with hazelnut cream:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenHungryThenCook10BreadsWithMyWife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">throws</span> <span class=\"token class-name\">InterruptedException</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> startGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> endGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token class-name\">Function</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">,</span> <span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span> preparation <span class=\"token operator\">=</span> topping <span class=\"token operator\">-></span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n           startGate<span class=\"token punctuation\">.</span><span class=\"token function\">await</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">InterruptedException</span> e<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">RuntimeException</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n       <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span>topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       basket<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       endGate<span class=\"token punctuation\">.</span><span class=\"token function\">countDown</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">int</span> i <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> <span class=\"token number\">5</span><span class=\"token punctuation\">;</span> i<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">var</span> me <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">.</span><span class=\"token function\">apply</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       me<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">var</span> myWife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Thread</span><span class=\"token punctuation\">(</span>preparation<span class=\"token punctuation\">.</span><span class=\"token function\">apply</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"hazelnut cream\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       myWife<span class=\"token punctuation\">.</span><span class=\"token function\">start</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   startGate<span class=\"token punctuation\">.</span><span class=\"token function\">countDown</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   endGate<span class=\"token punctuation\">.</span><span class=\"token function\">await</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>basket<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">hasSize</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">haveExactly</span><span class=\"token punctuation\">(</span><span class=\"token number\">5</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Condition</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>bread <span class=\"token operator\">-></span> bread<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">contains</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"butter\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"butter bread\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">haveExactly</span><span class=\"token punctuation\">(</span><span class=\"token number\">5</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Condition</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>bread <span class=\"token operator\">-></span> bread<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">contains</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"hazelnut\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"hazelnutcream bread\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>First, notice the use of a new helper method from AssertJ, we specified that the collection should have exactly 5 items that satisfy a condition.</p>\n<p>The Condition entity from the AssertJ library helps us to create a whole new set of assertions. If you are interested, please take a look at a delicious example in the appendix of this article.</p>\n<p>But let's come back to our bread story. After executing the test now with hazelnut cream, sometimes we face errors that are even strange:</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpecting elements:\n&lt;[bread with hazelnut cream,\n    bread with hazelnut cream,\n    bread with hazelnut cream,\n    bread with hazelnut cream,\n    bread with butter,\n    bread with hazelnut cream,\n    bread with butter,\n    bread with butter,\n    bread with hazelnut cream,\n    bread with hazelnut cream]&gt;\n to have exactly 5 times &lt;butter bread&gt;</code></pre></div>\n<p>Why do we have only 3 bread with butter, but 7 bread with hazelnut cream?</p>\n<h2>Summary so far</h2>\n<p>Before advancing, let's recap what we have seen until now:</p>\n<ul>\n<li>\n<p>Most today's computers have multiple cores, allowing us to get even more value from concurrent tasks;</p>\n</li>\n<li>\n<p>Working with multiple threads creates some difficulties when we depend on timing to verify our tests' assertions, nothing that couldn't be handled using tools from java's Concurrent package, like CountDownLatch;</p>\n</li>\n<li>\n<p>AssertJ is a java assertion library that helps us to improve our tests also on their readability.</p>\n</li>\n<li>\n<p>We should keep in mind that not all classes are thread-safe, like ArrayList for example. When many threads will share access to a common collection, we should use one of the thread-safe Collection implementations from the Concurrent package;</p>\n</li>\n</ul>\n<p>Ok, with all that knowledge in mind let's figure out what is the reason for the weird errors that we are facing.</p>\n<h2>Thread-safety</h2>\n<h3>Race Condition</h3>\n<p>First of all, this is a typical symptom of a Race Condition, or more specifically, a Data Race. Quoting Brian Goetz, in the book Java Concurrency in Practice</p>\n<p>\"<em>A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, when getting the right answer relies on lucky timing.</em>\"</p>\n<p>On our baking issue, we have multiple threads fighting to access the same shared property. My wife and I are fighting for toppings at the same knife.</p>\n<p>In the real world, one could think of it like this:</p>\n<ol>\n<li>\n<p>I get my knife and put butter on that;</p>\n</li>\n<li>\n<p>Just when I leave the knife to take the bread, my wife gets that knife and puts hazelnut cream on it;</p>\n</li>\n<li>\n<p>I take back the knife and, with tears in my eyes, realize that I'm topping my bread with some strange brown cream;</p>\n</li>\n<li>\n<p>Now my wife with her bread in hand stares at an empty knife, trying to figure out who is sabotaging her.</p>\n</li>\n</ol>\n<p><a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/1ff9d1c27bf3ef283302379138cd5bed/f680c/Race-Condition.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 420px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 70.95238095238095%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAACJElEQVQ4y21TyY7TQBDNJ/EjCPEViAtXOCEOiOXGjobRhJFgBpGQ3fHSbXe3ux3b8WQYBBckLnxJPbqdzZ5weKpyLa+2dsefTIgHnPwZp2DWlDGFHqfxSNL7jxUdnS5pMhIUeGvfNobNGZ1/NTQYpMS9KXVUFFEhNDxviZlFU24xmVYYjFdr+7wdFwYFuue/0BteYZFE6ER+RB/mPyCFomWaUKEElamo5RalRaVjWghZo1Rtv8tbakEiZNThvk/B9AiCM9KJQX94AR5lWEiJTKgaTvfnOb70LyG5bvkcTB2TQkYMHc+P6Y1XYhwZKm1gFCyQxmkrKVcSLMwQ+Hltv14sE86m1oRJEFImjTOSc7rkw4S1LBq+vEXcIBRhRMZUyKR2+2kRXe+m6XOjq90kDUI2m9PrkzMEVhZpWjvzTcJoYi85K6CTfaf1+EGGs953CGbq2BahN/ao+/YRhv0+ldrYBe+7Go4rTGdle5+bYm7X/x2Z2UfdjX9jygt7FNEIkDDJXs/EFutu27tu7tAeZaViFDKh3RHknmix0bdJmZAH+zy8sjLQsSbnMPavqYPtu8pTXQc65KlZ6yptdCtbxTaEEalwYY2ajCzwp3yIv9U9VPkKT+/cxPO7t3B1+RPdZw9w//YNaM52hXJL7uD0wkrFODrh1CMZJfaDkWQCF/IYlTyxj1vg88sn6B2/ck8K37rv8OnFY8gwRMrjOrkJZ+NzH/8AC+N/l13ojqEAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n    ></span>\n    <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;box-shadow:inset 0px 0px 0px 400px white;\"\n        alt=\"Race-Condition\"\n        title=\"\"\n        src=\"/static/1ff9d1c27bf3ef283302379138cd5bed/f680c/Race-Condition.png\"\n        srcset=\"/static/1ff9d1c27bf3ef283302379138cd5bed/4c3b3/Race-Condition.png 148w,\n/static/1ff9d1c27bf3ef283302379138cd5bed/d72a6/Race-Condition.png 295w,\n/static/1ff9d1c27bf3ef283302379138cd5bed/f680c/Race-Condition.png 420w\"\n        sizes=\"(max-width: 420px) 100vw, 420px\"\n      />\n  </span>\n  </a></p>\n<p>It could only work if each one of us does the topping at the perfect timing, that is, only getting the knife when the work of the other one is done.</p>\n<p><a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/9eb569fa960bd58a894af409fce7ccca/f680c/Race-Condition-Lucky-timming.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-wrapper\"\n    style=\"position: relative; display: block;  max-width: 420px; margin-left: auto; margin-right: auto;\"\n  >\n    <span\n      class=\"gatsby-resp-image-background-image\"\n      style=\"padding-bottom: 70.95238095238095%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsSAAALEgHS3X78AAACKklEQVQ4y3VSy47TQBDMt/Ax/AcnjnBHSFwBiQMs4iGR5UACyZJsYo8f47E9Mx4/kpDdRUJCe0f8RhczdhI57O6h1D1d45ruag/C5ZJEJCj0BUV+FzukFDNBi3NJ70439P7zmpbneVtzXLS7kwQJjSeGZjNNgnk0UJxTkxdgbA3fgu2wz4NgjaW3wXyxhedvDvz+Thw1GI5/YTq/QpVxDHjI6WPwEzJXtNYZNSqnlXbocpOpNnfcyp6bW+C4dZFTHic0EGFIkfcBuUioyAzO5j+QcgOdanz7fgHfb1ArCZMrlHfAcZXUkDzBgIUpnbAVFtzQSkrwqEKRadjOWjEnXNl6X6B/7nJpo+oEsyimUhpXJEe6blzs532Rfayl7An3BPOYkzEblLKgKpd3dlHJY3EpCqhD9z3BxA/ozacRIhsbrXfkzRHDoLab3iCz/oq4xJfpJfLEtJ0eCbIFo+HbZ5ifndGqMNbgjnTYC7qPEisymW1bT5Xtznl968iJ/amH6TU80dil5Df86sNkPX/t3ds9tEvZqhSNzKgTOfaw2l0ue7HFf7XjLSuDItXUvaZxM9qOtOmsUPqQ16o4PNAT5KTiyo5TUq0U/mwf4rp5YTuo8Xf7AL/rV6iLC/DZVzy6fw9sfApvNMRjmyfzKVambqdo7EMqERjEHiPJU3cgLTgu1QmabAItElyp16jTSbuIyH48fP4EwluCTUY4ffkUKfMtl7VCWqQQQYh/P3d/SRDg4P0AAAAASUVORK5CYII='); background-size: cover; display: block;\"\n    ></span>\n    <img\n        class=\"gatsby-resp-image-image\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;box-shadow:inset 0px 0px 0px 400px white;\"\n        alt=\"Race-Condition-Lucky-timming\"\n        title=\"\"\n        src=\"/static/9eb569fa960bd58a894af409fce7ccca/f680c/Race-Condition-Lucky-timming.png\"\n        srcset=\"/static/9eb569fa960bd58a894af409fce7ccca/4c3b3/Race-Condition-Lucky-timming.png 148w,\n/static/9eb569fa960bd58a894af409fce7ccca/d72a6/Race-Condition-Lucky-timming.png 295w,\n/static/9eb569fa960bd58a894af409fce7ccca/f680c/Race-Condition-Lucky-timming.png 420w\"\n        sizes=\"(max-width: 420px) 100vw, 420px\"\n      />\n  </span>\n  </a></p>\n<p>About our code, we have at least two problems in it: 1) we set the topping and add it to the bread in two different steps; and 2) when we add the topping to the bread, its removal from the knife also occurs in a separate step.</p>\n<p>Because of that, just before a thread applies the topping to the bread, another thread could change the topping or even remove it. And again, just before removing the topping from the knife, another thread could use that knife to add topping to other bread.</p>\n<p>That is why in the last two test logs we got some bread without topping, and more bread with one of the toppings than the other.</p>\n<h3>Atomicity</h3>\n<p>We wrote those naive classes just to enlighten the lack of atomicity in them, but even single-line codes like <code class=\"language-text\">++i</code> are not atomic, in fact, it comprehends three operations: 1) get the value; 2) add one to it; and 3) update the value back.</p>\n<p>What we should do is enforce the concept of atomicity, which means that each of our tasks should be considered as one. One indivisible task, an atom.</p>\n<p>Java has a built-in mechanism that allows us to achieve atomicity, which is called “synchronized block”.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">synchronized</span><span class=\"token punctuation\">(</span>lock<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\t<span class=\"token comment\">// Code that handles the shared memory</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>We can use any java object to act as a lock, and it will ensure that only one thread that acquires that lock will be able to execute the code within. When the thread finishes its job, it releases that lock so that other threads could do the same thing.</p>\n<p>It is also allowed to create a synchronized method, just by adding the synchronized keyword before the return type of the method. Doing so, the lock will be the object on which the method is being invoked.</p>\n<p>Ok, let's stop talking, and let's get our hands dirty!</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenHungryThenCook10BreadsWithMyWife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">throws</span> <span class=\"token class-name\">InterruptedException</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">var</span> basket <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ConcurrentLinkedQueue</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> knife <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> startGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> endGate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">CountDownLatch</span><span class=\"token punctuation\">(</span><span class=\"token number\">10</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token class-name\">Function</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">,</span> <span class=\"token class-name\">Runnable</span><span class=\"token punctuation\">></span></span> preparation <span class=\"token operator\">=</span> topping <span class=\"token operator\">-></span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">-></span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n           startGate<span class=\"token punctuation\">.</span><span class=\"token function\">await</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">InterruptedException</span> e<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">RuntimeException</span><span class=\"token punctuation\">(</span>e<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n       <span class=\"token keyword\">synchronized</span> <span class=\"token punctuation\">(</span>knife<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token keyword\">var</span> bread <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Bread</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n           knife<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span>topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n           basket<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span>bread<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n           endGate<span class=\"token punctuation\">.</span><span class=\"token function\">countDown</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n   <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token comment\">// (...) omitted for brevity</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Now the fix of our code is just a matter of adding a synchronized block using the knife as the lock. With this, only one thread at a time can take the knife and execute the code inside it.</p>\n<h3>Thread blocking</h3>\n<p>\"Oh! This is the solution for everything, we should synchronize everything!\" Think twice.  Synchronization isn't for free; it creates a performance problem, as now all other threads are blocked waiting for the availability of the lock, which in our case is the knife.</p>\n<p>In our kitchen, we could say that when my wife touches the knife I become blocked, waiting for her. If the phone rings, she should say: \"darling, please answer the phone\". But I will be blocked, I'll not be able to do anything except wait for her to leave the knife.</p>\n<p>A blocked thread goes to the TIMED_WAITING state, and during this time it can not be used. It is really advisable to keep track of how many threads our applications are using because threads are a scarce resource.</p>\n<p>But there is light at the end of the tunnel, at least in this concern you should know that Java 19 is coming up with the concept of <a href=\"https://blogs.oracle.com/javamagazine/post/java-loom-virtual-threads-platform-threads\"><ins>Virtual threads</ins></a>, in its Project Loom. This new feature will cut the one-to-one relationship between Java threads and OS threads, which means that more than one Java virtual thread will be able to use the same OS thread. With that, when some virtual thread gets blocked by an I/O operation, for example, another virtual thread can perform calculations on that same OS thread.</p>\n<p>But, as we said, until there we should use our threads with wisdom.</p>\n<h3>Nonblocking Algorithms</h3>\n<p>\"But, what to do?\", you could ask. Well, if you need better performance you can use Nonblocking Synchronization. Nonblocking algorithms are widely used by JVMs implementations, Operational Systems, and in Java itself to implement locks and other concurrent data structures.</p>\n<p>Those Nonblocking algorithms are way more complicated to design and implement, but they provide better performance by avoiding the thread block itself and give us other benefits like being immune to Deadlock.</p>\n<p>To provide a simple example of Deadlock, imagine that my wife and I are in the living room. The remote controller of the TV and the sofa are Locks. To watch TV, a person needs to sit on the sofa and press the button on the remote controller. A Deadlock would occur if I get the remote controller and my wife sits on the sofa. She will be blocked waiting for the remote controller, and I'll be blocked waiting for the sofa. And we will be like that \"until death does us part.\"</p>\n<p>Let's go back to the Nonblocking algorithm. First of all, we need a way to ensure atomicity to our tasks. And it is possible because modern computer processors have special instructions for managing access to shared data. A common approach is the implementation of the compare-and-swap (CAS) instruction. It guarantees us that the access to the value and its update will occur as a single task.</p>\n<p>Java's Concurrent package provides us with some so-called atomic classes. Let's take AtomicInteger as an example, its documentation states that it is \"An int value that may be updated atomically\".</p>\n<p>The following code shows us the same algorithm, but only the last one achieves thread-safe by delegating its thread-safety to an AtomicInteger:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">class</span> <span class=\"token class-name\">Counter</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">private</span> <span class=\"token class-name\">Integer</span> count <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token keyword\">void</span> <span class=\"token function\">incrementCount</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>count <span class=\"token operator\">=</span> count <span class=\"token operator\">+</span> <span class=\"token number\">1</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token keyword\">int</span> <span class=\"token function\">getCount</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">return</span> count<span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">class</span> <span class=\"token class-name\">ThreadSafeCounter</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">private</span> <span class=\"token class-name\">AtomicInteger</span> count <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AtomicInteger</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token keyword\">void</span> <span class=\"token function\">incrementCount</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>count<span class=\"token punctuation\">.</span><span class=\"token function\">incrementAndGet</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token keyword\">int</span> <span class=\"token function\">getCount</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">return</span> count<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>And how does AtomicInteger ensure atomicity? Using the CAS algorithm! Its incrementAndGet method executes a code that could be simplified like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">private</span> <span class=\"token keyword\">int</span> value<span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">public</span> <span class=\"token keyword\">final</span> <span class=\"token keyword\">int</span> <span class=\"token function\">incrementAndGet</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">int</span> expectedValue<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">int</span> oldValue<span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">do</span> <span class=\"token punctuation\">{</span>\n       oldValue <span class=\"token operator\">=</span> value<span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span> <span class=\"token keyword\">while</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token function\">compareAndSetInt</span><span class=\"token punctuation\">(</span>oldValue<span class=\"token punctuation\">,</span> oldValue <span class=\"token operator\">+</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">return</span> oldValue<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>To start, it gets the current value and stores it in a local variable. Then using the compareAndSetInt method it first checks if, at that precise moment, the current value is the same that was earlier fetched. If it is so, it proceeds with the update and then returns True. If the current value was changed by another thread, the compareAndSetInt method returns False and restarts the process.</p>\n<p>It is worth saying that the compareAndSetInt method is a native method, which uses the most efficient instructions provided by the underlying hardware.</p>\n<p>With this new knowledge, what about trying it on our bread? Let's remove the blocking synchronization and create the faster bread with butter that a computer could have (and some with hazelnut cream too, for the sake of my wife's happiness). We can do this using an AtomicReference.</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">public</span> <span class=\"token keyword\">class</span> <span class=\"token class-name\">Knife</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">private</span> <span class=\"token keyword\">final</span> <span class=\"token class-name\">AtomicReference</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> topping <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AtomicReference</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> topping<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">while</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>topping<span class=\"token punctuation\">.</span><span class=\"token function\">compareAndSet</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">,</span> topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">this</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Bread</span> bread<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token class-name\">String</span> currentTopping<span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>currentTopping <span class=\"token operator\">=</span> topping<span class=\"token punctuation\">.</span><span class=\"token function\">getAndUpdate</span><span class=\"token punctuation\">(</span>s <span class=\"token operator\">-></span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">!=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span>\n           bread<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span>currentTopping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">this</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Of course, we did that after removing the synchronized block from our test. Good, fast, and easy, and without thread blocking! But, please pay close attention to this piece of code. We have some problems there as it is some kind of adaptation of the canonical CAS algorithm.</p>\n<p>The hard part of building nonblocking algorithms is to isolate the shared memory into an atomic single change. But in our baker issue, we have a two-step action: first, we set the topping to the knife, and then we add the topping to the bread. So we have two states to keep track of: the knife and the bread.</p>\n<p>As we said, this code works and does not block the thread, but doesn't give us all the advantages of the CAS algorithm, because we still can have a Livelock issue.</p>\n<p>A Livelock issue can occur even when the thread is not blocked, if it is waiting for an operation that will never succeed. In our code, we used the topping value as a kind of lock. The first thread that moves it from null to another value, it will put all other threads waiting for that value to become null again. It works, but if any thread fails to add the topping to the bread, which moves the topping value back to null, all the other threads will be waiting forever.</p>\n<p>The control mechanism, when more than one thread fights for the knife topping, is done by retrying again immediately, like in the CAS. But the canonical CAS will not fail indefinitely if any other thread fails. It will just finish its job as soon as no other thread touches the shared memory when it is still working.</p>\n<h3>Immutability</h3>\n<p>\"So, what to do!? I'm reading this to find answers, not questions!\" Ok, I'll let you know. The other side of the coin, in the context of thread safety, is Immutability. If we use an immutable object, virtually all problems with atomicity are gone. That's because all problems that we are facing here are based on threads fighting to access the same shared memory. If the memory that they want to access cannot be modified, those risks are gone and thread safety is achieved.</p>\n<p>We can summarise that an Immutable object is one that can't be changed after its creation.</p>\n<p>Java introduced the Record, which is a simple way to create immutable objects. We just need to provide the type and name of the fields. The public constructor, equals, hashCode, and toString methods, along with the private, final fields, are all given for free to us, by the compiler.</p>\n<p>Take a look at the following code:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">public</span> <span class=\"token keyword\">record</span> <span class=\"token class-name\">Knife</span> <span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> topping<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> topping<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span>topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Knife</span> <span class=\"token function\">applyToppingTo</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">Bread</span> bread<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>topping <span class=\"token operator\">!=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span>\n           bread<span class=\"token punctuation\">.</span><span class=\"token function\">setTopping</span><span class=\"token punctuation\">(</span>topping<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Knife</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Some could argue that immutable objects are a waste of resources, but it isn't true in the majority of cases. Dealing with immutable objects offers us performance advantages when it frees us from using synchronization or creating defensive copies, it even reduces the impact on generational garbage collection.</p>\n<p>But talking about defensive copies, is the record really immutable? Look at this test:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenReferenceToRecordThenItShouldBeImmutable</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">record</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> childrenNames <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token class-name\">List</span><span class=\"token punctuation\">.</span><span class=\"token function\">of</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Haru\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> parent <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Bruno\"</span><span class=\"token punctuation\">,</span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">var</span> parentBeforeNewChild <span class=\"token operator\">=</span> parent<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   childrenNames<span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Ayumi\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>parent<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span>parentBeforeNewChild<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>This task will fail with the following log:</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpecting actual&#39;s toString() to return:\n  &lt;&quot;Parent[name=Bruno, childrenNames=[Haru]]&quot;&gt;\nbut was:\n  &lt;Parent[name=Bruno, childrenNames=[Haru, Ayumi]]&gt;</code></pre></div>\n<p>We have to keep in mind that in the way that we created the Parent record we have kept a reference to its internals. A record is still unmodifiable, but to achieve immutability you have to avoid exposing its inner state. In our example, we can avoid that by overriding the constructor and coping the list of children's names:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">record</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name <span class=\"token operator\">=</span> name<span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>childrenNames <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>Now the test is successful, but we are still publishing the internal state of the record. The getter method for the property childrenNames is publishing the reference to the record's inner state, allowing it to be modified:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">givenReferenceToRecordThenItShouldBeImmutable</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">record</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">public</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n           <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name <span class=\"token operator\">=</span> name<span class=\"token punctuation\">;</span>\n           <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>childrenNames <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n       <span class=\"token punctuation\">}</span>\n   <span class=\"token punctuation\">}</span>\n   <span class=\"token keyword\">var</span> childrenNames <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">ArrayList</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span><span class=\"token class-name\">List</span><span class=\"token punctuation\">.</span><span class=\"token function\">of</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Haru\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> parent <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Bruno\"</span><span class=\"token punctuation\">,</span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">var</span> parentBeforeNewChild <span class=\"token operator\">=</span> parent<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   parent<span class=\"token punctuation\">.</span><span class=\"token function\">childrenNames</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">add</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Ayumi\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>parent<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">hasToString</span><span class=\"token punctuation\">(</span>parentBeforeNewChild<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>This code will fail as well:</p>\n<div class=\"gatsby-highlight\" data-language=\"tex\"><pre class=\"language-tex\"><code class=\"language-tex\">java.lang.AssertionError: \nExpecting actual&#39;s toString() to return:\n  &lt;&quot;Parent[name=Bruno, childrenNames=[Haru]]&quot;&gt;\nbut was:\n  &lt;Parent[name=Bruno, childrenNames=[Haru, Ayumi]]&gt;</code></pre></div>\n<p>To avoid that you have at least two options: override the getter and return a copy of our list, or the one that I prefer: save our internal state as an unmodifiable list:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token keyword\">record</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">public</span> <span class=\"token class-name\">Parent</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token class-name\">List</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">String</span><span class=\"token punctuation\">></span></span> childrenNames<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name <span class=\"token operator\">=</span> name<span class=\"token punctuation\">;</span>\n       <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>childrenNames <span class=\"token operator\">=</span> <span class=\"token class-name\">List</span><span class=\"token punctuation\">.</span><span class=\"token function\">copyOf</span><span class=\"token punctuation\">(</span>childrenNames<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Like this, every time someone tries to update our inner state, they will get a UnsupportedOperationException, which I believe is what we should expect from trying to modify something supposed to be immutable.</p>\n<h2>Summary so far</h2>\n<p>What we have seen so far?</p>\n<ul>\n<li>\n<p>We learned more about Race Conditions, in real life and in the software, and the main solution tool from Java: the monitor pattern, using the synchronized keyword;</p>\n</li>\n<li>\n<p>After understanding the downside of locking, we were introduced to the compare-and-swap (CAS) nonblocking algorithm, which despite being hard to develop can lead us to better performance and protect us from Deadlock</p>\n</li>\n<li>\n<p>For the cases when we are unable to isolate our shared memory, or even in other scenarios where we just need more protection, we talked about immutability and how immutable objects can grant us thread safety.</p>\n</li>\n<li>\n<p>We then revisited the java Record, which is a fairly easy way to create an immutable object, but that is not immune to bad programming technic. To really achieve immutability in our objects we saw how we should avoid publishing its inner state.</p>\n</li>\n</ul>\n<h2>Conclusion</h2>\n<p>Oh, it was an amazing journey, we started with a brief introduction about threads, how to properly test them, and we met some new friends from Java's Concurrency package. With new algorithms and tools under our belt, we are ready to travel to the multithreaded world riding our thread-safe software. I'll now eat my bread with butter, see you soon!</p>\n<h2>Appendix</h2>\n<p>Baking delicious cakes with AssertJ's Condition entity:</p>\n<div class=\"gatsby-highlight\" data-language=\"java\"><pre class=\"language-java\"><code class=\"language-java\"><span class=\"token annotation punctuation\">@Test</span>\n<span class=\"token keyword\">void</span> <span class=\"token function\">testTheCake</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n   <span class=\"token keyword\">record</span> <span class=\"token class-name\">Cake</span><span class=\"token punctuation\">(</span><span class=\"token class-name\">String</span> name<span class=\"token punctuation\">,</span> <span class=\"token keyword\">boolean</span> hasFruit<span class=\"token punctuation\">,</span> <span class=\"token keyword\">int</span> weightInKg<span class=\"token punctuation\">)</span><span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">var</span> chocolateCake <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Cake</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Chocolate\"</span><span class=\"token punctuation\">,</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> <span class=\"token number\">5</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> strawberryCake <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Cake</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Strawberry\"</span><span class=\"token punctuation\">,</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> <span class=\"token number\">3</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">var</span> bakery <span class=\"token operator\">=</span> <span class=\"token class-name\">List</span><span class=\"token punctuation\">.</span><span class=\"token function\">of</span><span class=\"token punctuation\">(</span>chocolateCake<span class=\"token punctuation\">,</span> strawberryCake<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token keyword\">var</span> heavyCakes <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Condition</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Cake</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>cake <span class=\"token operator\">-></span> cake<span class=\"token punctuation\">.</span>weightInKg <span class=\"token operator\">>=</span> <span class=\"token number\">3</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"heavy cake\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n   <span class=\"token keyword\">var</span> bigChocolate <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Condition</span><span class=\"token generics\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Cake</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">(</span>cake <span class=\"token operator\">-></span>\n           cake<span class=\"token punctuation\">.</span>name<span class=\"token punctuation\">.</span><span class=\"token function\">contains</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Chocolate\"</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">&amp;&amp;</span>\n           cake<span class=\"token punctuation\">.</span>weightInKg <span class=\"token operator\">>=</span> <span class=\"token number\">5</span>\n           <span class=\"token punctuation\">,</span> <span class=\"token string\">\"big chocolate\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n   <span class=\"token function\">assertThat</span><span class=\"token punctuation\">(</span>bakery<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">haveExactly</span><span class=\"token punctuation\">(</span><span class=\"token number\">2</span><span class=\"token punctuation\">,</span> heavyCakes<span class=\"token punctuation\">)</span>\n           <span class=\"token punctuation\">.</span><span class=\"token function\">haveExactly</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">,</span> bigChocolate<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>","fields":{"slug":"/a-wild-thread-appeared-multithreaded-testing-and-thread-safety/","tags":["Thread-safety","testing","nonblocking_algorithms","immutability"]}}}]}},"pageContext":{"slug":"/rate-limiters/","tags":["auto1","engineering","RateLimiter","Thread","Scheduling"],"category":"Engineering","author":"Bruno Morais","date":"2022-07-18"}}