<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Milan Mimica on Medium]]></title>
        <description><![CDATA[Stories by Milan Mimica on Medium]]></description>
        <link>https://medium.com/@milan.mimica?source=rss-68da06403fed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yGY4dF0ArWxtk4MqQjhwFw.jpeg</url>
            <title>Stories by Milan Mimica on Medium</title>
            <link>https://medium.com/@milan.mimica?source=rss-68da06403fed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:41:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milan.mimica/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Java CPU usage observer effect]]></title>
            <link>https://medium.com/infobipdev/the-java-cpu-usage-observer-effect-18808b18323f?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/18808b18323f</guid>
            <category><![CDATA[java-14]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mbean]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[cpu-utilization]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:13:41 GMT</pubDate>
            <atom:updated>2021-09-17T09:49:39.791Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A mere observation of a phenomenon inevitably changes that phenomenon.</blockquote><figure><img alt="System CPU Usage graph" src="https://cdn-images-1.medium.com/max/547/1*bzddDEKzdIj_WkUlx7Hz7A.png" /></figure><p>One of the basic metrics of your service goes berserk. System CPU usage graph suddenly becomes all spiky. It’s switching between 0 and 100% most of the time. No business metrics show anomalies so you continue with your daily routine. Ignoring the crazy metric is a proven strategy to get things delivered and not getting stressed out for nothing. It wouldn’t be the first time things somehow solve by themselves. But not this time.</p><h4>Nothing on the surface</h4><p>You dig deeper and find that the metric is produced by <a href="https://docs.oracle.com/en/java/javase/14/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getSystemCpuLoad()">OperatingSystemMXBean::SystemCpuLoad</a>MXBean. The value is exposed to <a href="https://prometheus.io/">prometheus</a> by <a href="https://github.com/prometheus/jmx_exporter">jmx_exporter,</a> together with all other java.lang&lt;type=OperatingSystem&gt;metrics. To your amazement, other metrics look fine. Even ProcessCpuLoad plots a nice-looking line. You ssh to the VM, run htop and CPU usage also looks fine. Development is fast-paced. There have been many recent changes in both the service and the running environment. It’s impossible to track down which change exactly broke the System CPU graph. Besides, it’s Java — you were promised platform independence and backward compatibility!</p><h4>Deep dive into Hotspot JVM</h4><p>System CPU usage is calculated in <a href="https://github.com/openjdk/jdk/blob/master/src/jdk.management/linux/native/libmanagement_ext/UnixOperatingSystem.c#L323">OperatingSystem.c</a> as follows: it reads the first line from /proc/stat, where the system keeps its ticks. A <em>tick</em> is an arbitrary unit for measuring internal system time. There are independent counters of ticks passed doing “idle” time, “user” time, “system” time, and so on. More ticks, more CPU time was spent in the category. Each time you ask Java for an estimation of, as they put it “recent CPU usage”, it reads current tick counters, subtracts the ticks from the last read, and gives you the ratio to total ticks. In pseudo code:</p><pre>ticks = read(&quot;proc/stat&quot;)</pre><pre>user_diff = ticks[&quot;user&quot;] - prev_ticks[&quot;user&quot;]<br>system_diff = ticks[&quot;system&quot;] - prev_ticks[&quot;system&quot;]<br>total_diff = sum(ticks) - sum(prev_ticks)<br>if (total_diff != 0)<br>    cpu_load = (user_diff + system_diff) / total_diff<br>else<br>    cpu_load = 0</pre><pre>prev_ticks = ticks</pre><p>There is an obvious flaw in this implementation: it calculates average CPU usage since the <em>last invocation</em> of the method. If you call it twice in a row, the second invocation is likely to return a value skewed by low-resolution: a zero, a one, or 0.5 if you’re lucky. Exactly what the graph started to plot!</p><h4>Look Once, Look Again</h4><p>The hidden cause of this discrepancy is the rename of the metric in JDK 14 from SystemCpuLoad to CpuLoad. The old metric was not removed, only deprecated in the API. JmxCollector pulls and publishes all available metrics, effectively calculating the same CPU usage twice in a row. The value was corrupted by merely measuring it — twice.</p><p>In MBean API there is no attribute for deprecation, and that’s a real problem. A generic tool has no way of ignoring deprecated metrics. I see no workarounds for this. Even Oracle’s own Mission Control is displaying different values for SystemCpuLoadand CpuLoad. Any generic tool will have the same issue. It’s not safe to assume which metric is going to be right or wrong. It’s random, though seems consistent. Unfortunately, jmx_exporter <a href="https://github.com/prometheus/jmx_exporter/issues/512">does not support</a> the blacklisting of individual MBean values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18808b18323f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infobipdev/the-java-cpu-usage-observer-effect-18808b18323f">The Java CPU usage observer effect</a> was originally published in <a href="https://medium.com/infobipdev">Infobip Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software impedance explained]]></title>
            <link>https://medium.com/free-code-camp/software-impedance-6796cc65758b?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/6796cc65758b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sun, 07 Apr 2019 22:10:27 GMT</pubDate>
            <atom:updated>2019-04-29T19:16:47.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>The impedance mismatch between data processing components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GFgF4KqixGeYwqcExmbjg.png" /></figure><p>It all starts with the simplest signal-processing diagram ever:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*OUE0jW_PgGyX50ppxFsbZA.png" /></figure><p>Component A is passing the signal to component B. Let’s switch to software engineering jargon immediately: A producer is invoking a method of a consumer. Invoking a method takes a finite time. We call this response time or <em>latency</em>. The producer can pass an arbitrary (but limited) amount of data to each method invocation. We call this <em>batch size</em>. Concurrency level is another variable we can play with. The producer can control the number of concurrent invocations by limiting the<em> window size </em>of pending responses. Invoking the method concurrently indeed multiplies the throughput. Throughput (T) is a function of window size (W), batch size (B) and latency (t).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*np0hdGzIO1pb7GnDMSgoiw.png" /></figure><p>We aim for maximum throughput, so increase the concurrency and use higher batch sizes. If only! Response time depends on batch size and window size. To put it more formally, response time if a function of both window size and batch size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*YlQ9_6zllbMMH_X5cVkWmA.png" /></figure><p>To achieve maximum throughput we must find the highest <em>W</em> and <em>B</em> that produce the lowest <em>t</em>. Non-ideal <em>W</em> and <em>B</em> will induce a higher “resistance” in the component, or call it <em>back-pressure</em> if you will.</p><blockquote>Whether it produces the data or just passing it through, a producer must adapt window size and batch size to best suit the consumer. Otherwise we have what I call software impedance mismatch.</blockquote><p>There is no generic expression for f(W, B) as it depends on the component’s implementation. Theory is of no help here. You have to probe the consumer with different batch and window sizes to spot the ideal values that will maximize the throughput.</p><p>Once you find the ideal batch size you must build an “impedance adapter”. Here is a suggested java implementation that accumulates the items and batches them before sending them to the next component (lots of boilerplate code omitted for brevity).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36046006c7636cd0ff2e9e1ac284a996/href">https://medium.com/media/36046006c7636cd0ff2e9e1ac284a996/href</a></iframe><p>Note that invoking the consumer with smaller than maximum (ideal) batch size is still allowed. This assures no additional latency is added. If the selected batch size is optimal, assuming steady item feed, invoking the consumer will take exactly the time it takes to fill <em>maxBatchSize</em> items in the queue.</p><p>Likewise, the number of concurrent method invocations towards some consumer instance can be controlled using a semaphore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f3882266acce68f1df952c1883d3de1/href">https://medium.com/media/4f3882266acce68f1df952c1883d3de1/href</a></iframe><h4>Push vs. Pull mode</h4><p>The above scenario depicts “push” mode, in which the producing component controls the invocation, its timing, and the mentioned key parameters. A more modern approach of dealing with back-pressure is to put the consuming component in charge of the invocation. This puts the system designer in a slightly better position, as engineers of the consuming component don’t need to communicate batch and window size to producers. Nevertheless, a similar impedance adapter is needed.</p><h4>Conclusion</h4><p>Impedance adapters are stateful components, consisting of queues, threads, callback maps, etc., which adds complexity, but matching impedance is essential in inter-component communication.</p><p>I argue that each component should specify its impedance parameters: optimal batch size and concurrency level. That way producer components can adapt to minimize the back-pressure.</p><p>Unlike the electrical impedance, the impedance in software is not limited to two dimensions. Here I show only two parameters, but often the response time depends on other variables too.</p><p>Impedance is a very dynamic property. It may depend on the data being sent, overall workload, sometimes even on variables not controlled by the caller. If needed, the consumer’s API should be designed in a way that allows the component to publish its latest impedance parameters via API. That way the producers could dynamically adapt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6796cc65758b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/software-impedance-6796cc65758b">Software impedance explained</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Redis antipattern]]></title>
            <link>https://medium.com/@milan.mimica/one-redis-antipattern-27275b9e33a8?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/27275b9e33a8</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[architectural-patterns]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sun, 18 Mar 2018 14:07:37 GMT</pubDate>
            <atom:updated>2018-03-19T14:53:46.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*GZHfWXJn1wv5Bmp9EZadoA.png" /></figure><p>A general scenario: you are designing a service for high-throughput and high-availability, and you’ve come to the point to where you need to decide how to share data between instances. There are several technologies you can use, but <a href="https://redis.io/">Redis</a> sure does look nice and simple, versatile, and can be used in so many wrong ways. Lets see how it all breaks down when the state you are working with is short-lived and you <strong>cannot afford to lose it</strong>, and you decide to put it in Redis.</p><p>You setup and master-slave, on say 5 instances, on different physical machines and you can be confident your state is there, safe and available to be handled through the master instances. With libraries like <a href="https://github.com/redisson/redisson">Redisson</a> the Java integration is seamless. If only…</p><p>The first question that pops up is how much memory I need. Remember that Redis is in-memory storage, swapping is performance killer, so you need enough memory to fit all the data, even when there is a spike. You ask for estimates, do some testing and figure out you will have at most, say 16GB of data. You provision 20GB VMs to have some spare and everything works fine… until <em>you lose all your data</em>. In master-slave configuration you <a href="https://redis.io/topics/admin#redis-setup-hints">need to enable persistence</a>.</p><p>When you have persistence enabled you need to double your memory. The reason is simple: While the snapshot is being taken, Redis needs to store all the changes aside, not to interfere with snapshotting. It does so very elegantly by empowering mmap’s MAP_SHARED that uses Copy-On-Write mechanism to create copes of modified pages. So if the dumping takes 30 seconds, and much of the state is modified within this period (remember we are dealing with a high-throughput service with short-lived data) chances are most if not all pages will be copied. It does not matter if you choose EOF mechanism: EOF compaction does pretty much the same thing. You need double memory.</p><p>Let it be said that enabling persistence makes no sense: who needs the state that is several minutes old? In a high-throughput service it likely has been overridden several times already and is obsolete. It might even be dangerous to resurrect.</p><p>Even if you choose not to enable persistence you still have the same problem because full synchronization uses a similar mechanism: you need to set <a href="https://redis.io/topics/clients#output-buffers-limits"><em>slaves output buffer</em> limit</a>. It is where operations that are to be replicated to slaves are stored while the full sync operation is in progress. It is a very simple concept: buffer all the ongoing operations and run them on the slave when the slave is ready. The thing is it can take a significant time to transfer 16GB worth of data to a slave and have the slave handle it. I’ve seen a slave taking 30 seconds just to drop the old database. Hint: increase client timeout on server side. During the full sync period changes to the data accumulate in the buffer. The buffer is less likely to reach 16GB, because it doesn’t suffer from fragmentation, but you still need to reserve for worst-case scenario. The good thing is snapshotting and full sync never happen concurrently, so you don’t need to triple your memory, only double it. The bad thing is concurrent full sync can happen, and it’s even encouraged by Redis in disk-less replication mode.</p><p>OK, it should be clear by now that you need a ~36GB VM to handle 16GB worth of data (I arbitrarily put 4GB as spare to that the OS can “breathe”). You can leave with that. So what happens if your data reaches the 16GB watermark? Say, one day you check your Redis dashboard and there is 20GB of data. It all happens to work because there wasn’t a need to trigger a failover. You have to provision more RAM. Except you can’t. To add more RAM you need to restart the VM. Restaring requires full sync (and possibly dumping to disk) which won’t work, because there is no enough RAM. You can ask your devops for hot addition of RAM — good luck with that!</p><p>The conclusion is you need to predict (as impossible as it may be in a disruptive business) how much state there is going to be, double that (because Redis), add more (because OS), and add some more because your prediction was wrong. You cannot change your mind later. After the data size hits the threshold you can only pray it goes does again.</p><h4>For this reason Redis is not a good fit for shared short-lived state on a high-throughput service. The error in initial estimation is fatal, unrecoverable and <a href="https://www.amazon.com/Black-Swan-Improbable-Robustness-Fragility/dp/081297381X">unavoidable</a>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27275b9e33a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take from the system what you need]]></title>
            <link>https://medium.com/@milan.mimica/take-from-the-system-what-you-need-76356c727164?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/76356c727164</guid>
            <category><![CDATA[zlib]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java9]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sun, 06 Aug 2017 11:23:06 GMT</pubDate>
            <atom:updated>2017-08-06T11:30:21.474Z</atom:updated>
            <content:encoded><![CDATA[<p>Just found this little <a href="https://bugs.openjdk.java.net/browse/JDK-8079759">jewel</a> in Java 9: it now uses system’s zlib implementation instead of statically linking to copy of <a href="http://zlib.net/">zlib</a>. This is good because you can now upgrade your OS zlib and Java fill pick it up. If you are a performance freak you can try to sneak into an optimized version, for example the one <a href="https://software.intel.com/en-us/articles/intel-ipp-zlib-coding-functions">provided by Intel</a> which leverages fancy CPU instructions to do the heavy lifting.</p><p>I just did and here is what happened.</p><h3>The benchmark</h3><p>Here is the full <a href="https://gist.github.com/mmimica/9074ab03fa111e1ef3f3cb7e862eff78">benchmark source code</a>, using <a href="http://openjdk.java.net/projects/code-tools/jmh/">JMH</a>. It loads some file (I used 2.7MB zlib-1.2.8.tar which just happened to be there) into memory and zips it, also in-memory. The benchmark is performed with different compression levels: 1, 3, 6 and 9.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4603a2e1fa285ff25ff8f1f56882ac49/href">https://medium.com/media/4603a2e1fa285ff25ff8f1f56882ac49/href</a></iframe><p>The difference is between 1.4 times to 3 times better throughput in favour of IPP. I can imagine this making a significant impact in applications where zip compression makes a large part of the workload. Worth considering it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76356c727164" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slow like a stream, fast like a loop]]></title>
            <link>https://medium.com/infobipdev/slow-like-a-stream-fast-like-a-loop-524f70391182?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/524f70391182</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sat, 05 Aug 2017 08:08:35 GMT</pubDate>
            <atom:updated>2021-09-17T09:50:20.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or why is your Java becoming slower. Or why you should think about the code you type. Or why you shouldn’t let fads affect your coding.</h4><p>Together with lambdas, streams were the one of a few new cool features brought to us by Java 8. The first thing that made stream attractive among the cool kids is its verbosity compared to old-fashioned loop. You could now read the code aloud to your granny. And even more excitingly, you could now pretend you were doing concurrent programming just by choosing parellelStream() instead of stream(). All the loops have to be replaced! Loops are evil! With this hype it was hard to find any resources about stream performance compared to loops. You don&#39;t talk against the only Java 8 cool feature.</p><p>The excitements is now long gone, and everybody is looking at upcoming Java 9, so I feel now is the right time give streams a more sober look. I believe any experienced programmer feels that there is something not quite right with streams. Why hide a complexity of a loop? And at what cost? What is so complex about the loop in the first place, the first control flow statement you learn about, that needs hiding? Since when are one-liners considered more readable? How do you debug streams? What is the processing overhead of invoking a lambda function, implementing control statement with indirect method invocations (via MedthodHandles), drowning deep into the stack; compared to a few byte-codes generated by the loop statement? <em>JIT will take care of it</em> you say? JIT <a href="https://wiki.openjdk.java.net/pages/viewpage.action?pageId=20415918">takes care of loops</a> and does a good job there. It doesn’t do <a href="https://bugs.openjdk.java.net/browse/JDK-6580709">miracles with method invocations</a>. If you just admit that it is possible that streams &amp; lambdas can produce significant computational overhead then you will easy spot them in you profiler output. If you were foolish enough (like me) to use them if your hot code, that is. Because you do profiling, right?</p><h3>The benchmark</h3><p>I wrote a <a href="https://gist.github.com/mmimica/f7f7c8033820dd95dd449cf58e0ad58b">benchmark</a> using <a href="http://openjdk.java.net/projects/code-tools/jmh/">JMH</a>. I’m measuring the performance of a simple operation on an java.lang.ArrayList: sequential search for a specific value which is not present in the list. Using Java 8u131 and Java 9 current mercurial tip. Run on 8 Core Intel i7 CPU @ 2.50GHz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CLJZP7kwMRhTvKIIQtPCA.png" /></figure><p>The graph shows throughput: number of operations per second. More is better.</p><p>I know I could get much better results if I used <em>indexed-based loop</em> instead of <em>enhanced loop</em> (which unfolds into <em>iterator-based loop)</em> but that would be unfair comparison. Streams and <em>enhanced loops</em> work on any kind of collections while <em>index-based loops</em> work only for <em>random access</em> ones<em>.</em></p><p>The only advantage of a stream is in Java 9, when used on a large list, in parallel mode. But event that very is arguable, given it consumes 8 times more power. Also, Java 9 in general shows slightly different behavior: sometimes slower, sometimes faster. That could be because of different GC, but it may be because of something else as well, I wouldn’t speculate.</p><h3>Introspection</h3><p>Now ask yourself:</p><ul><li>Do you care about performance?</li><li>Are you willing to sacrifice some code-coolness because of performance?</li><li>What is the average list size you are performing streaming operation on?</li><li>How likely is for the list to be empty, or with just a few elements?</li><li>Is cached data lookup the backbone of your business logic?</li></ul><p>It turns out I often deal with applications which do nothing but lookups on small or empty in-memory lists. Got nice performance boosts just by rewriting streams (back) to loops.</p><h3>Update May 13th 2019</h3><p>Java 9 looks ancient with rapid Java release cycle. Here is a benchmark with JDK 12. Just to make sure not much has changed. (It was run on a different machine though.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8t1Y9D5UcYqxKk87fM19Yw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524f70391182" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infobipdev/slow-like-a-stream-fast-like-a-loop-524f70391182">Slow like a stream, fast like a loop</a> was originally published in <a href="https://medium.com/infobipdev">Infobip Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned about software development by baking cakes]]></title>
            <link>https://medium.com/infobipdev/what-i-learned-about-software-development-by-baking-cakes-ec507420650?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec507420650</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[baking]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Fri, 21 Apr 2017 11:56:52 GMT</pubDate>
            <atom:updated>2021-07-14T07:02:42.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4RTRQs8kR9t5SP11QE2Hg.jpeg" /></figure><p>Some time ago I started baking cakes. Out of nowhere, just like I started programming about 15 years ago. I just wanted to adopt a new skill, learn something new, fun, and interesting. Wait, am I talking about programming or baking?</p><p>I’ve been contemplating a lot lately about programming, software development, cakes, life universe, and everything. Here I’m going to share some of my ideas.</p><h4>Expect failures</h4><p>In baking cakes, just as in software development, some attempts end with a failure, going down the drain/toilet/<a href="https://linux.die.net/man/2/unlink">unlink(2)</a>. At some point, you realize the cake is going to be a certain failure, an unfixable one. The sooner you realize it the better. Real failures are ones from which you don’t become a better pastry chef/programmer/person. Sit back and think where it went wrong, have a glass of wine, and learn something from it.</p><p>Failures don’t cease, ever. Admittedly, the chemical process of cake baking, when developed in a closed system, is determined by a finite set of factors. The result should be predictable. There is no magic. Just as software is executed on deterministic machines. Yet, both fail. It’s a mystery to me.</p><p>I know, there is software that never fails, developed by the process, not by people. There are also cake factories producing rum-tasting cubes wrapped in plastic. Not my cup of tea.</p><h4>You cannot force quality</h4><p>Motivated people deliver quality. If I don’t <strong>feel</strong> like writing software I am <strong>not</strong> going to write software. The same goes for cakes. It’s just that baking cakes doesn’t pay my bills, but honestly, bad quality software doesn’t pay anyone’s bills either. When I don’t feel like coding I can always resort to reviewing someone else’s code, writing cute emails, thinking about architecture, or just socializing with other people who also don’t feel like coding.</p><p>Luckily, there are times when all I wanna do is to bake a cake. Coding, also sometimes.</p><h4>Working software over comprehensive documentation</h4><p>You should already have heard this one. Here is what I think about recipes: you don’t need those. They are incomplete, wrong and you probably don’t know how to use them. A recipe is just a reference. It roughly describes the process. It’s a good starting point to develop something on your own. If it weren’t so, you’d be better of with a cake printer.</p><p>The recipe is like a programming tutorial. You need it just to get started. Soon enough you’ll have to learn about all the hidden processes that make a cake a great success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec507420650" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infobipdev/what-i-learned-about-software-development-by-baking-cakes-ec507420650">What I learned about software development by baking cakes</a> was originally published in <a href="https://medium.com/infobipdev">Infobip Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everybody leaks]]></title>
            <link>https://medium.com/infobipdev/everybody-leaks-f210631f13ef?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/f210631f13ef</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 07:47:08 GMT</pubDate>
            <atom:updated>2021-09-17T09:49:59.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0j_LDAe1APO2krklqvnGyg.jpeg" /></figure><h4>Detecting native memory leaks in Java</h4><h3>Mandatory intro</h3><p>What is a memory leak? It is a type of resource leak that occurs when memory which is no longer needed is not released, according to Wikipedia. The “no longer needed” part is ambiguous here, and left to different interpretations. If you talk to a C programmer, he’ll tell you a block of memory has leaked when there is no reference to it from any of program roots (thread stack pointers and similar). By this definition you cannot (easily) leak memory in Java, since it’s a garbage-collected language, and the garbage collector will take care of reclaiming any unreachable memory blocks. Still, Java folks constantly talk about memory leaks, but on another level. In Java, you leak memory by not using it in your code. For example, you allocate an array, put it in a map, use this map also for something else, and forget about the array. There is no leak detector which will reliably detect such leaks. Technically, it’s not even a leak.</p><h3>When memory is gone</h3><p>When I had a problem with leaking memory resources on one of our <a href="https://www.infobip.com/en/media/news/messaging-technology-at-its-best">Messaging Core</a> services, it did not fall in any of the above categories. The service would exhaust all of 32GB memory over two weeks and eventually get prosecuted by Linux OOM killer. The Java process was given 25G heap. Side note: I like to use fixed heap sizes — same value to -Xmx and -Xms flags, because I see no point of making JVM manage heap size for the service running on a virtual machine which has been designed for peak memory usage. The JVM just must have enough memory, any time it needs it, so let it reserve it. It also makes things more simple. Because I knew heap size was fixed I knew without any doubt that I head a problem with native (off-heap) memory management. Hotspot JVM uses native memory for various things, like metaspace, housekeeping metadata, thread stack, GC metadata… All sorts of internal things which are needed for the JVM to work. Or, in JVM user’s point of view: wasted memory. Without much thinking, one would say that 25:7 heap to waste radio would be big enough, but apparently it wasn’t.</p><p>I couldn’t nail down the root cause of native memory leak just by searching the Internet. I could easily exclude the top 4 causes of native memory leaks I found people complaining about the most:</p><ol><li><strong>Not closing the </strong><strong>java.util.zip.DeflaterInput/OutputStream</strong> – These streams internally use java.util.zip.Deflater which uses JNI and allocates some native memory in the process. If you don&#39;t close it you have a <em>temporary</em> leak. Deflater itself implements java.lang.Object.finalize() where the memory is reclaimed. My leak was of permanent nature and not even Full GC did make any difference.</li><li><strong>sun.misc.util.Unsafe.allocateMemory et. al.</strong> – Hotspot JVM exposes this functionality to manage native memory. It&#39;s easy to misuse and create C-style memory leaks. I have scanned the classpath, and the only use of this feature was by <a href="https://netty.io/">netty 4</a>. After having throughfully examined netty&#39;s buffer management code I had to admit I can&#39;t blame netty. There is also a static variable AtomicLong io.netty.util.internal.PlatformDependent.DIRECT_MEMORY_COUNTER which keeps track of the amount of allocated memory.</li><li><strong>direct </strong><strong>java.nio.ByteBuffer</strong> – this is actually not much more than a wrapper around Unsafe.allocateMemory. It&#39;s used by netty 3, which I also happen to have in classpath. It&#39;s easy to check how much memory is allocated by this with JMX Mbean value java.nio.BufferPool.direct. It also showed that there is no leak. There is also this buffer caching feature which is <a href="http://www.evanjones.ca/java-bytebuffer-leak.html">known to produce memory leaks</a>, but setting jdk.nio.maxCachedBufferSize didn&#39;t change anything.</li><li><strong>The class loader</strong>: if you keep creating new class definitions on the fly you are bound to leak memory. Just don’t. I didn’t.</li></ol><h3>Native memory profiling</h3><p>So it looked like I was not facing a well-known problem, and if I wanted to find the cause of this memory leak I had to do it myself. Hotspot does offer some <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr007.html">native memory tracking facilities</a>. When enabled, it keeps track of native memory allocations, divided in several categories. Also, you can create a baseline for later comparison. Here is the profile after the service has been running for 5 days, against a 10 hours old baseline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f605eefa18a76e65d47403ef50f2a94d/href">https://medium.com/media/f605eefa18a76e65d47403ef50f2a94d/href</a></iframe><p>It allocated almost 600MB of memory in last 10 hours only! And that is after 5 days of high load, which one would expect to be enough time for the system to stabilize. Unfortunately, it wasn’t and the “Internal” category just kept on growing until it crashed. For reference, here are all native memory categories (the ones with zero delta against baseline were omitted in previous output):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/338c551009d8e95552756a28c59803e5/href">https://medium.com/media/338c551009d8e95552756a28c59803e5/href</a></iframe><p>Unfortunately, mtInternal doesn&#39;t narrow down to anything. It&#39;s basically “uncategorized”. At least I could be sure now that memory wasn&#39;t taken by Java heap, or thread stack spaces, or Classloader, or JIT, or GC… or could I? What else is there?</p><p>This guy successfully <a href="http://www.evanjones.ca/java-native-leak-bug.html">used jemalloc to detect his cause of a Java native memory leak</a> and I gave it a try. (Lession leared: don’t just clone master branch from github and assume it’s production ready. <a href="https://github.com/jemalloc/jemalloc/issues/499">It is not.</a>) The <a href="http://jemalloc.net/">jemalloc</a> library has a tool to track sources of allocations of live (not free()-ed) memory blocks at some given moment. It periodically dumps profiles between which you can create delta profiles. It literally points on a picture where recent memory consumption comes from. It does so by sampling calls to malloc(3) et. al. It also demangles C++ symbols. What a nice time to live in!</p><p>This is what I got for last 10 hours on a service with 5 days uptime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*ykgAN6DsRxHe3JFVOF5brQ.png" /><figcaption>jemalloc profiling output</figcaption></figure><p>In that period 755MB worth memory blocks were allocated (via malloc(3)) and not released. About 711MB came from G1RemSet and HeapRegion classes. The values are sampled but represent the correct ratio. The leak is coming from G1 GC code! It just keeps allocating more memory. This is actually G1 keeping track of heap areas (<em>cards</em>) between <em>heap regions</em> which are being changed between <em>generations</em>. Sorry, but there is no more simple way to put it. Here is a <a href="https://blogs.oracle.com/g1gc/entry/g1_gc_glossary_of_terms">glossary</a>. What I found strange is that this allocation is classified as mtInternal by the VM, and not as mtGC. There is a <a href="https://bugs.openjdk.java.net/browse/JDK-8176571">ticket</a> filled for this now.</p><h3>Meanwhile in Internal G1 department</h3><p>The most effective way to reduce the resource waste of change tracking between heap regions is to reduce the count of heap regions. You do that by increasing heap region size. By default, G1 tries to divide the entire heap into 2048 regions of equal size, but so that region size is between 1M and 32M, and a power of 2. For 25G heap it calculated 3150 regions of 8M. By setting -XX:G1HeapRegionSize=16M region count halved, reducing housekeeping overhead, thus stabilizing native memory usage. It also has other, potentially negative side-effects like increase of heap fragmentation and increase of homogeneous object threshold, but you should know this already. But the good thing is, native memory starvation problem was gone. Category mtInternal didn&#39;t go above 2G. I still had the 25:7 heap/native memory ratio which bugged me.</p><p>Turns out the trick is in OtherRegionsTable::add_reference method. When storing remembered sets it tries to use a sparse representation (very fine grained, memory efficient, linear complexity), then when it overflows it falls back to a more coarse grained representation using bitmaps (which use far more memory). This branching is also visible in allocation graph as BitMap::resize and HeapObj::new flows. We want to use the HeapObj::new more, and the parameter is -XX:G1RSetSparseRegionEntries. Here is a possibly <a href="http://mail.openjdk.java.net/pipermail/hotspot-gc-use/2017-February/002622.html">better explanation</a>, but it&#39;s hard to explain code. [Edit: and <a href="https://www.infoq.com/articles/tuning-tips-G1-GC">another one</a>]</p><p>In my case, default value for G1RSetSparseRegionEntries was 20. I increased it to 64 and mtInternal category halved, with no measurable performance impact. Finally.</p><h3>Real man use default settings</h3><p>… as <a href="http://java-is-the-new-c.blogspot.hr/2013/07/tuning-and-benchmarking-java-7s-garbage.html">this guy put it</a>.</p><p>This was a long journey. I still don’t know what is it in my service that makes JVM behave that way. Or if this could be qualified as a leak at all. Maybe it just needed more off-heap memory and it would stabilize eventually. There must be some easier, less time-consuming, business-friendly, pragmatic thinker’s solution. And I agree. Let’s imagine a patient with explaining the symptoms to a pragmatic doctor:</p><p>Patient: “After my service has been running two weeks…”<br>Doctor: “Wait, you run the same version for two weeks? You’re not deploying fast enough. Fix your agile process.”<br>Patient: “I set a heap size of 25G and …”<br>Doctor: “Wait, that’s way too much! Here, have a prescription for micro-services.”</p><p>Or as one my colleague says: If you have to set anything more than -Xmx and -Xms you must be doing something wrong.</p><h4>Update June 3rd 2019</h4><p>The default value of G1RSetSparseRegionEntries is going to change in JDK13, to scale exponentially with heap size: <a href="https://bugs.openjdk.java.net/browse/JDK-8223162">JDK-8223162</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f210631f13ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/infobipdev/everybody-leaks-f210631f13ef">Everybody leaks</a> was originally published in <a href="https://medium.com/infobipdev">Infobip Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Waiting for Spring]]></title>
            <link>https://medium.com/@milan.mimica/waiting-for-spring-10328152293d?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/10328152293d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Fri, 07 Apr 2017 18:54:48 GMT</pubDate>
            <atom:updated>2017-04-07T19:34:27.470Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some more ranting on Java’s synchronized</h4><p>There is this problem that has been bugging me for ages, or more precisely since we’ve started to use <a href="https://medium.com/@milan.mimica/making-spring-data-jpa-run-747044c513b7">cached Spring Data</a> in our projects. There is this private inner static class org.springframework.orm.jpa.SharedEntityManagerCreator.DeferredQueryInvocationHandler which overrides java.lang.Object.finalize(). I&#39;m sure you know how you are not supposed to do this. Yet, Spring devs decided to do it. This causes serious performance degradation. While there are hundreds of articles explaining why overriding finalize() is bad practice, and how all the assumptions you make about it are wrong, none of the articles tell you that Object&#39;s constructor enters a <strong>synchronized</strong> block if the class overrides finalize(). Yes, java.lang.Object actually has a constructor body, hidden inside JVM, and at one point it looks up if the class overrides finalize(), and if it does, registers itself to static void java.lang.ref.Finalizer::register(Object finalizee) which unconditionally enters a <strong>synchronized block on a static field</strong>. Neat, JDK developers, real neat! If I had someone in my team do that we&#39;d have a serious talk. The functionality could be implemented using some concurrent structure, but JDK developers are just not motivated to improve this because finalize() is getting <a href="https://bugs.openjdk.java.net/browse/JDK-8165641">deprecated</a> in Java 9 and probably removed in Java 10.</p><p>They say good managers make others to their job, so I made Juergen Hoeller fix this one. I just had to <a href="https://jira.spring.io/browse/SPR-15363">kindly ask</a>. Now waiting for Spring version 4.3.8 which is due in a few days. I’ve never been waiting for Spring so eagerly.</p><p>Here, have a poem while you wait</p><blockquote><strong>First Days Of Spring — Noah and the Whale</strong></blockquote><blockquote><em>It’s the first day of spring<br>And my life is starting over again<br>Well the trees grow, the river flows<br>And its water will wash away my sin<br>For I do believe that everyone<br>has one chance to fuck up their lives<br>Like a cut down tree, I will rise again</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10328152293d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Spring Data JPA run]]></title>
            <link>https://medium.com/@milan.mimica/making-spring-data-jpa-run-747044c513b7?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/747044c513b7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-data]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Sat, 01 Apr 2017 11:06:34 GMT</pubDate>
            <atom:updated>2017-04-02T06:13:11.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*adBEcFyPITbF5m3NGXuSPQ.jpeg" /></figure><h3>Slow &amp; special</h3><p><a href="http://projects.spring.io/spring-data-jpa/">Spring Data JPA</a> (or SPRDAJ for close friends) is cool. Really neat and cool. It’s just that one thing… it’s slow. How slow? Well, probably not slow enough for most usages. It’s probably fast enough for you. I guess it was written under assumption that relational databases are generally slow, so no one will notice how crappy SPRDAJ really is. But in <a href="http://www.infobip.com/">Infobip</a> we are using it in a very special way. I have managed to redirect all JPA queries which would normally go to the database, to my custom on-heap cache. This cache is independently kept in sync with the database(s). All of the choke-points listed here are noticed when using SPRDAJ with this library, where queries are executed against cached data. There is no overhead which is normally present, caused by Hibernate, JDBC, network and the database, which make SPRDAJ look lightening fast. So, we’re special, and SPRDAJ is slow. Slow and special. Like Forrest Gump. Except it’s not running.</p><p>Without <em>any</em> of these optimizations SPRDAJ renders the service so slow it makes it useless. It doesn’t work at all! Proven on several core platform services. If you’re unlucky enough to have to use SPRDAJ in a high throughput service, with many concurrent threads, you’ll find here handful of advices on how you can make it run faster. These choke-points were spotted using Flight recorder and by making thread dumps of real-life applications.</p><h3>Let’s fork</h3><p>The first choke-point I came across was a <strong>synchronized</strong> block in TypedQuery&lt;?&gt; org.springframework.data.jpa.repository.query.PartTreeJpaQuery.QueryPreparer.createQuery(CriteriaQuery&lt;?&gt; criteriaQuery. A private method inside a private inner class. I couldn&#39;t find any other solution than to fork SPRDAJ and recompile it without this synchronized block. The explanation why the synchronized block it was introduced is in <a href="https://jira.spring.io/browse/DATAJPA-396">https://jira.spring.io/browse/DATAJPA-396</a>. With cache enabled there is no need for this. I <a href="https://jira.spring.io/browse/DATAJPA-841">really think</a> this synchronized block should be made optional somehow.</p><p>Another optimization made it into official code base: <a href="https://jira.spring.io/browse/DATAJPA-941">https://jira.spring.io/browse/DATAJPA-941</a>. This is to show that I’m not only bitchin’, but also making change where it’s possible.</p><h3>Easy workarounds</h3><p>For some convolving reasons I don’t want to explain here, it makes things really faster if you just specify EntityManager class when constructing EntityManagerFactoryBean</p><pre>LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();<br>entityManagerFactoryBean.setEntityManagerInterface(javax.persistence.EntityManager.class);</pre><p>It just reduces calls to class loader and cannot do any harm. Nonetheless, SPRDAJ still does a lot of calls to load javax.persistence.TypedQuery class, so it&#39;s a good idea to make sure it doesn&#39;t enter a <strong>synchronized</strong> block a normal class loader has. Just simple cache will do miracles:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1af4b0d969dd8f58e4755384b2c31a9/href">https://medium.com/media/f1af4b0d969dd8f58e4755384b2c31a9/href</a></iframe><h3>Transactions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QjOBkEbAbR7oZAq67i4QcQ.jpeg" /></figure><p>There are many uses of a database that don’t require ACID properties, and I’m really happy when I don’t have to bother with transactions. I also hate it when someone makes it really hard for me to achieve this happiness.</p><p>With default setup, SPRDAJ runs an additional SQL statement to every call you do. It is some “setAuotcomit” thing, and I don’t event want to know what it is about. It practically makes every SPRDAJ call two times slower. One unnecessary round-trip to the RDBMS at least. It completely defies the purpose of caching, if you use one. A team of experts I’m glad I’m working with has found a way to disable transactions. You have to redefine methods provided by org.springframework.data.repository.CrudRepository with an additional annotation: @Transactional(propagation = Propagation.NOT_SUPPORTED). While this works, I still suspect there must be a simpler way to do this.</p><h3>Rewire like McGuywer</h3><p>If you’re running SPRDAJ in a highly concurrent environment, chances are you’ll notice that your service is still spending much time in classes whose name suggests they have something to do with transactions. What I first noticed was that String org.springframework.transaction.interceptor.TransactionAspectSupport.methodIdentification(Method method, Class&lt;?&gt; targetClass) was making <strong>80% of total memory allocations</strong>. That&#39;s a lot of GC pressure, for a debug information which is never even used. How do you fix it? Redefine a transaction interceptor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5752efa9cd3971736547d49fc4bef18e/href">https://medium.com/media/5752efa9cd3971736547d49fc4bef18e/href</a></iframe><p>and use it instead of the default one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8e2809adf1639fa019b95b78e08904/href">https://medium.com/media/5c8e2809adf1639fa019b95b78e08904/href</a></iframe><p>Or, even better, get rid of the whole damn thing completely:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee42b5d347cc9b4e47d4adc900cf40df/href">https://medium.com/media/ee42b5d347cc9b4e47d4adc900cf40df/href</a></iframe><p>Implementing FalsePointcut is left as an exercise to the reader. When we learn that we can hack proxy objects, it opens the door to many other hacks. And we didn&#39;t even need to use reflection. After all, a repository object <em>is</em> a proxy, and we can statically cast it into an Advised. It took me some time to figure this out.</p><h3>Hack that proxy</h3><p>Another choke-point is<strong> </strong>Object org.springframework.data.repository.core.support.RepositoryFactorySupport.QueryExecutorMethodInterceptor.invoke(MethodInvocation invocation. There is a piece of code that is called unconditionally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab42046dfbf789e853d7b4d263a38d7b/href">https://medium.com/media/ab42046dfbf789e853d7b4d263a38d7b/href</a></iframe><p>This is really lame because</p><ol><li>It could easily be cached. It’s not like method return type is going to change any time soon.</li><li>TypeDescriptor.nested(..) does a complete examination of the method, unconditionally entering a <strong>synchronized</strong> call, and all we needed is a return type.</li><li>The value is only used to support some fancy SPDRAJ features like returning an Optional, or a Feature.</li></ol><p>So you can just redefine QueryExecutorMethodInterceptor like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef64430d4880040b1ec6b7dbf8407055/href">https://medium.com/media/ef64430d4880040b1ec6b7dbf8407055/href</a></iframe><p>And use it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24c0373f6381371fe8d1140c249224ae/href">https://medium.com/media/24c0373f6381371fe8d1140c249224ae/href</a></iframe><h3>What? All optimizations and no benchmarks?</h3><p>Writing good benchmarks is really hard. Some of things don’t pop up unless you run 2000+ threads, and have some specific usage patterns. The only benchmark is my service. It either works or it doesn’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=747044c513b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fjaka]]></title>
            <link>https://medium.com/@milan.mimica/fjaka-da6e14544dfe?source=rss-68da06403fed------2</link>
            <guid isPermaLink="false">https://medium.com/p/da6e14544dfe</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming-tips]]></category>
            <dc:creator><![CDATA[Milan Mimica]]></dc:creator>
            <pubDate>Fri, 31 Mar 2017 20:07:10 GMT</pubDate>
            <atom:updated>2017-03-31T20:07:10.103Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fjaka /fjâka/ — <em>A</em>n expression for the <em>Mediterranean</em> state of body and mind. Can be described as striving towards doing absolutely nothing</h4><p>Our way of thinking inevitably affects our coding style. I have the privilege to work with people of different cultural background, and in order to understand each other better, to enable more effective collaboration, I want to share my core values. Here I present you <em>fjaka</em>.</p><p>As developers, we often use term <em>lazy</em>. Lazy load, Lazy get… We see it as a good thing. One common habit shared by people who are lazy is postponing doing a task or making a decision until really necessary. Procrastination. If you ask them why they do it, they’ll explain that when you delay a task, usually it turns out that it wasn’t needed anyway. It’s similar with decisions. If you choose to decide later, it turns out that because the circumstances have changed in the meantime, either the decision is not needed any more, or you can make a better choice having new facts available.</p><p>I think lazy people have a point. And while being lazy is certainly something your manager will make notice of, developers have found a way to make their code act lazy by using a few code idioms. The most commonly used one is <em>lazy get</em>. It has a couple of variations, but the purpose is the same: delay doing something until necessary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc45ff1feecf5c1b4ececfb5328ad2a5/href">https://medium.com/media/fc45ff1feecf5c1b4ececfb5328ad2a5/href</a></iframe><p>Patterns to delay decisions are a bit more subtle. You have seen them for sure, but maybe you haven’t noticed them. Simple call of an abstract method, for example, is delaying a decision.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed036e1576cb00c0433148a2958dc4f4/href">https://medium.com/media/ed036e1576cb00c0433148a2958dc4f4/href</a></iframe><p>The actual method that is to be called is not known at compile time, and it depends on the concrete types of objects involved in method invocation. This kind of late binding enables for software to do lazy decision-making on which execution path to follow. When the actual method executed depends only on one object (usually the one on which the method is being invoked) it is called <strong>single dispatch</strong>. In this particular case, JVM will execute makeBabies(Animal a) method of the concrete implementation of object foo, whatever it happens to be in runtime. This is what most popular object-oriented programming languages have to offer when it comes to late biding, because it makes language implementation simple enough internally. But it can be a limiting factor when you want to boost your lazy creativity. Imagine you had an animal farm, in Java:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85049f363a698269174c9a1bd14f59f6/href">https://medium.com/media/85049f363a698269174c9a1bd14f59f6/href</a></iframe><p>The straightforward way to make them reproduce would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d76dfbcda79ee6d6250140072e0d6728/href">https://medium.com/media/d76dfbcda79ee6d6250140072e0d6728/href</a></iframe><p>And then you could just write this, and have them breed correctly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15940c28a2c043c5b8bc68f54df23cbf/href">https://medium.com/media/15940c28a2c043c5b8bc68f54df23cbf/href</a></iframe><p>Unfortunately, this will give you compile errors in Java, because the JVM cannot choose a method based on argument type in runtime. While not supported by the language, <strong>multiple dispatch</strong> can be emulated via <a href="https://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25a39487971ebf3ccd3c10494b6711e/href">https://medium.com/media/a25a39487971ebf3ccd3c10494b6711e/href</a></iframe><p>So, next time in peer code review you see something among the lines:void foo(Something s) { s.foo(this); } you should recognize that the developer wrote some code that is trying to make a choice in an extremely lazy fashion, <em>fjaka</em> style.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da6e14544dfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>