<?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 Liviu Adrian Esanu on Medium]]></title>
        <description><![CDATA[Stories by Liviu Adrian Esanu on Medium]]></description>
        <link>https://medium.com/@liviu.esanu?source=rss-ad0571cc9691------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RrRFllB59Cx7pSDGmHb-qA.jpeg</url>
            <title>Stories by Liviu Adrian Esanu on Medium</title>
            <link>https://medium.com/@liviu.esanu?source=rss-ad0571cc9691------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:08:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liviu.esanu/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[Our own Robocode contest]]></title>
            <link>https://medium.com/metrosystemsro/our-own-robocode-contest-ec1db41f8fa9?source=rss-ad0571cc9691------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec1db41f8fa9</guid>
            <category><![CDATA[competition]]></category>
            <category><![CDATA[contests]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Liviu Adrian Esanu]]></dc:creator>
            <pubDate>Mon, 18 Sep 2017 06:16:18 GMT</pubDate>
            <atom:updated>2017-09-18T06:16:18.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Robocode is a game where you write the code for a tank like mini robot. Then your code gets to play against other people. Ten such robots are pitted against each other, and they gain points by shooting or ramming into other robots.</p><p>The Robocode project has an interesting history: it was created in 2000 by Mat Nelson, then IBM took interest in it in 2001. By 2005 the Robocode community was releasing newer versions of the game, and it was used in coding competitions and by students testing out their competitive algorithms.</p><p>The game rules are simple:</p><ul><li>The game map is a rectangle and the robot can move anywhere on it:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Kf9pha_6eNAjMef32EMyag.png" /></figure><ul><li>Game time is referred to as ticks. Each robot will perform one turn each tick.</li><li>A robot is composed of three parts: the vehicle, the gun and the radar. These parts move independent of each other.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*DpGK9o9HGhrRgPp560M89A.png" /></figure><p>All this is done using the API offered by the Robocode platform. Here are some of its most useful methods:</p><ul><li>turnRight(double degree) / turnLeft(double degree) = turns the robot</li><li>ahead(double distance) / back(double distance) = moves the robot</li><li>turnGunRight(double degree) / turnGunLeft(double degree) = turns the gunturnRadarRight(double degree) / turnRadarLeft(double degree) = turns the radar</li><li>getX() / getY() = get the coordinates of the robot</li><li>getHeading() / getGunHeading() / getRadarHeading()= get the angle of the vehicle / gun / radar</li><li>getBattleFieldWidth() / getBattleFieldHeight() = get dimensions of the map</li></ul><p>This set of simple rules and API methods makes creation of a new robot to be easy and fast. Here is the code for a very simple robot (taken from Robocode wiki):</p><pre>package man;<br>import robocode.*;<br> <br>public class MyFirstRobot extends Robot {<br>    public void run() {<br>        while (true) {<br>            ahead(100);<br>            turnGunRight(360);<br>            back(100);<br>            turnGunRight(360);<br>        }<br>    }<br> <br>    public void onScannedRobot(ScannedRobotEvent e) {<br>       fire(1);<br>    }<br>}</pre><p>Every turn, the commands issued by our robot above will be executed. He will move forth and back, and turn his gun and radar to search for enemies. Once an enemy is scanned, it fires a bullet. Since bullet power is between 0.1 and 3 and the speed of each bullet is 20 — (3 * bullet power), our bullet of power 1 is a pretty fast one, moving with a sped 17.</p><p>Our Robocode contest consisted of a 4 hour long marathon, where competitors wrote their robots and 2 rounds of battle: one intermediary round (after 2 hours of coding time) and one final round. The resulting robots had some very interesting and ingenious strategies. I will list below the key features of our most successful three robots.</p><p><strong>RustyTrumpet</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*JsfZaNzmyKnXXrNV6s5OBg.png" /><figcaption>RustyTrumpet</figcaption></figure><p>It is the yellow and orange colored bot, seen in the upper right corner in the above image.</p><p>- It keeps a list of all the other robots, and the distance to each of them</p><p>- Every time it scans a robot, it updates the distance to it, in the list above</p><p>- If the currently scanned enemy happens to be the robot closest to it, RustyTrumpet fires a bullet of maximum power (that is 3) but slow speed.</p><p>- The aiming strategy is highly efficient: it predicts where the target will be by looking at its current position, speed, orientation and distance. Thus, it computes the future position of the enemy, and fires at that location.</p><p>- Its movement pattern is semi random: it choose one direction and performs a large semicircle in that direction. After its completion, another direction is chosen and the next semicircle is performed.</p><p><strong>PizzaPower:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*-wJGzye6h9x3nTvCOQp7ow.png" /><figcaption>PizzaPower</figcaption></figure><p>This bot won the second place, and can be seen in the upper right corner of the image above. Its strategy is the following:</p><p>- Movement pattern is similar to RustyTrumpet, namely it moves in random semicircles, except they are smaller and designed to keep him near on of the corners</p><p>- When there are only 2 opponent left, he suddenly changes his movement pattern: it start to oscillate in large random forward and backward semi circles.</p><p>- Aiming strategy is predictive, though a bit less refined than the previous bot. It computes the distance to the target enemy, then computes the time a bullet would take to get there, then approximates the location of that enemy after the computed time delay.</p><p>- It always fires at the closest enemy, and keeps track of its last scanned location., thus he can predict its movement.</p><p>- Its weakness is that it only stores the last position of the target. His aiming pattern makes computations based on that position and the current position of the target. More elaborate predictions could have been made if PizzaPower were to have stored more detailed information about enemies.</p><p><strong>AdeBot</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*T3K7rex0TeFdVzlAYk2Nyw.png" /><figcaption>AdeBot</figcaption></figure><p>The last, and most complex of the bots presented, is AdeBot, the red on seen in the upper left part of the image above. He won first place, and rightfully so:</p><p>- It keeps detailed data on all the enemies scanned. On each scan event it updated the scanned bot’s position.</p><p>- The movement strategy is highly advanced: it moves in short bursts, each time it computes a series of locations where he can easily get to (based on his current orientation) then choses the one where it is less likely to find another bot nearby (using all the data it stores about enemies). It takes into account the current position of enemy bots, their speed and orientations — so when deciding on a location to move to, it estimates how many opponents will be near that location, by considering their most likely trajectory.</p><p>- Targeting for AdeBot is similarly complex: for each enemy he computes the likely position where he will be. Once all these possible angles are computed, it will fire in the direction that will intersect the most of these enemy trajectories. Furthermore, it this direction should not need for the gun to be turned too much, as this extra time required will interfere with the computations.</p><p>- One extra advantage of AdeBot is its radar movement: while most bots had their radars continuously turning in a circle, some had left right radar sweeping motions, thus increasing their number of enemy scan events. AdeBot went one step further, and only scanned the minimum amount needed to get info about all the enemies, thus when all enemies were scanned the radar turned back in a sweeping motion.</p><p>Overall Robocode is a great example of how a set of simple rules and an easy to use API lead to emerging complexity, and it proved to be a fun and challenging contest. Its beauty lies in the fact that a simple bot can be programmed in minutes, but a good one is much harder to achieve.</p><p>Links and references:</p><p>1. <a href="http://robowiki.net/wiki/Robocode">http://robowiki.net/wiki/Robocode</a></p><p>2. <a href="http://robowiki.net/wiki/Robocode/My_First_Robot">http://robowiki.net/wiki/Robocode/My_First_Robot</a></p><p>3. <a href="http://mark.random-article.com/weber/java/robocode/lesson2.html">http://mark.random-article.com/weber/java/robocode/lesson2.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1db41f8fa9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metrosystemsro/our-own-robocode-contest-ec1db41f8fa9">Our own Robocode contest</a> was originally published in <a href="https://medium.com/metrosystemsro">METRO SYSTEMS Romania</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java memory footprint — part 2]]></title>
            <link>https://medium.com/metrosystemsro/java-memory-footprint-part-2-8791679178e2?source=rss-ad0571cc9691------2</link>
            <guid isPermaLink="false">https://medium.com/p/8791679178e2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Liviu Adrian Esanu]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 15:19:23 GMT</pubDate>
            <atom:updated>2017-07-05T15:19:23.830Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/metrosystemsro/https-medium-com-metrosystemsro-java-memory-footprint-part-1-cf8785d6a47a">part one</a> we saw that Objects in general use much more memory than their primitive counterparts. Namely the overhead is more than 4 times the size of the payload (useful information represented as a primitive data type).</p><p>There are two more memory related issues, namely the footprint of most commonly used collection, and their resize strategy. Both this issues have practical usage and are worthy of attention.</p><p><strong>Memory footprint of most commonly used collections</strong></p><p>Let’s take a look at the java LinekdList class. How much memory does a LinkedList object use ?</p><pre>LinkedList&lt;Integer&gt; l = new LinkedList&lt;Integer&gt;();</pre><p>Without getting into details as much as we did in the first part, the LinkedList object will look similar to the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*9L_ykgKcGeLFUYb383Bs8g.png" /></figure><p>From the memory footprint point of view, each LinkedList object will need memory to store the fields inherited from Object class, just like all other objects. Furthermore memory will also be allocated for an int field that stores the size of the list, and a reference to the first and last elements.</p><p>Also, for each value contained in the LinkedList, please note that there is the need of an internal object (namely a node) that contains the useful payload information, and the references to the prev and next list entries.</p><p>Here is the code for the Node class:</p><pre>private static class Node&lt;E&gt; {<br>        E item;<br>        Node&lt;E&gt; next;<br>        Node&lt;E&gt; prev;<br><br>        Node(Node&lt;E&gt; prev, E element, Node&lt;E&gt; next) {<br>            this.item = element;<br>            this.next = next;<br>            this.prev = prev;<br>        }<br>}</pre><p>To sum it up, in case of a LinkedList, on top of the actually useful memory (that stores the elements in the list), a lot of other objects will be allocated. These internal objects are needed for the LinkedList to function.</p><p>In the image above we see an estimation of the useful memory versus the overhead memory ratio. This ratio is roughly 1 : 1, so the larger the LinkedList the linearly larger the overhead.</p><p>A much simpler class is the ArrayList class:</p><pre>ArrayList&lt;Integer&gt; l = new ArrayList&lt;Integer&gt;(50);</pre><p>If we consider the inner workings of ArrayList, we will need memory to store the fields inherited from object, another 32 bit int to store the ArrayList size, and a reference to an array of Integers. The following image is a simplification of an ArrayList object’s memory footprint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VYrA3GLab-2G102R0vkAA.png" /></figure><p>This class is much more generous with regards to its useful versus overhead memory usage. The memory used by its overhead is constant, while the more elements we add to it, the memory for actual useful data increases.</p><p>A similar case is the StringBuffer class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*7AX3ddHI-eOU4W7m9aHpFw.png" /></figure><p>Here we also have a constant memory for the overhead fields (inherited from Object, a reference to a char[]) while the useful payload memory increases linearly.</p><p>Last but not least let us take a look at the HashMap class.</p><pre>HashMap&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;();</pre><p>The HashMap object will need memory for the fields it inherits form the Object class, another float for the loadFactor, an int for the treshold, an int for the size, etc. On top of that, and array that stores the buckets, and for each bucket a list containing its entries. The approximation of this is in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*7_u-1_q8EsUv8NmoLZiaBQ.png" /></figure><p>While we do not want to get into the details of how a HashMap works, please note that for each key value entry there will be some overhead memory used, namely. Just for trivia, this is the code for the Node class, that implements Map.Entry, used by HashMap:</p><pre>static class Node&lt;K,V&gt; implements Map.Entry&lt;K,V&gt; {<br>        final int hash;<br>        final K key;<br>        V value;<br>        Node&lt;K,V&gt; next;<br><br>        Node(int hash, K key, V value, Node&lt;K,V&gt; next) {<br>            this.hash = hash;<br>            this.key = key;<br>            this.value = value;<br>            this.next = next;<br>        }<br><br>        public final K getKey()        { return key; }<br>        public final V getValue()      { return value; }<br>        public final String toString() { return key + &quot;=&quot; + value; }<br><br>        public final int hashCode() {<br>            return Objects.hashCode(key) ^ Objects.hashCode(value);<br>        }<br><br>        public final V setValue(V newValue) {<br>            V oldValue = value;<br>            value = newValue;<br>            return oldValue;<br>        }<br><br>        public final boolean equals(Object o) {<br>            if (o == this)<br>                return true;<br>            if (o instanceof Map.Entry) {<br>                Map.Entry&lt;?,?&gt; e = (Map.Entry&lt;?,?&gt;)o;<br>                if (Objects.equals(key, e.getKey()) &amp;&amp;<br>                    Objects.equals(value, e.getValue()))<br>                    return true;<br>            }</pre><pre>            return false;<br>        }<br>}</pre><p>To sum up the HashMap memory usage, it is clear that the overhead scales linearly with the payload, namely that that the more entries we have the more overhead memory we use, in a roughly 2:1 ratio.</p><p><strong>Collections resizing problem</strong></p><p>What happens, memory wise, in the following lines of code ?</p><pre><em>StringBuffer s = new StringBuffer();<br>s.append(“MY STRING”);<br>s.append(“ OF TEXT”);</em></pre><p>In the first line, a new StringBuffer object gets instantiated. In the second line, the “MY STRING” string gets appended to it. An approximation of the memory footprint is in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*QFc0ovF-MAj-2GCRolsIrA.png" /></figure><p>The third line is a bit more tricky: as the default capacity of a StringBuffer is 16 characters, our object had enough space to append “MY STRING”, but it clearly has not enough capacity to also append the string “ OF TEXT”.</p><p>What will happen is that the StringBuffer’s object internal char array will get resized, namely its size will double from having space to store 16 chars to having enough space to store 32 chars. Our StringBuffer object, after line three, will look similar to the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*flOmhh8We80vOtDTEH3Uag.png" /></figure><p>The default (initial) capacity of the StringBuffer class is 16. The resizing behavior of StringBuffer class is that it doubles its capacity every time it runs out of space.</p><p>In the table below we see the default capacity and the resizing factor for some of the most commonly used Java classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*XHOB9HkFuMLgQfofrAtWgg.png" /></figure><p>This behavior of certain classes will, if unchecked lead to the following situation: a large collection is almost completely filled and a couple of new elements are added to it. This will cause the collection to double its size, and while the first half of its memory will be filled with useful elements that are stored there, the second part of it will be using space but not storing almost any payload.</p><pre><em>StringBuffer s = new StringBuffer();<br>s.append(“MY STRING”);<br>s.append(“ OF TEXT”);</em></pre><p>For example, after the three lines of code above, the StringBuffer object will use space enough to store 32 characters but in fact will be storing only 17. Thus, space to store 15 characters will be wasted.</p><p>This is called the collection resizing problem, and as a solution, we can do the following: Whenever possible, use the constructor that takes the capacity as a parameter. Thus when we know the final storage capacity instantiate the collection to have that given capacity from the start.</p><p><strong>Conclusions and best practices</strong></p><ul><li>If all other things are the same, use a collection that minimizes the overhead space</li><li>For small sized collections, if functionality is not the issue, use normal arrays instead</li><li>Avoid adding elements to the point your collections resize too many times</li><li>As much as this is possible, estimate the actually needed capacity of a given collection, and instantiate it to that capacity from start</li></ul><p>In case you have not yet done so, please take a look at the first part of this article: <a href="https://medium.com/metrosystemsro/java-memory-footprint-part-1">Java memory footprint — part 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8791679178e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metrosystemsro/java-memory-footprint-part-2-8791679178e2">Java memory footprint — part 2</a> was originally published in <a href="https://medium.com/metrosystemsro">METRO SYSTEMS Romania</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java memory footprint — part 1]]></title>
            <link>https://medium.com/metrosystemsro/https-medium-com-metrosystemsro-java-memory-footprint-part-1-cf8785d6a47a?source=rss-ad0571cc9691------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf8785d6a47a</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-footprint]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Liviu Adrian Esanu]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 15:17:54 GMT</pubDate>
            <atom:updated>2017-07-05T15:19:52.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the way memory works is both useful and practical. To fully grasp the more advanced concepts takes a lot of time and effort. However, understanding the biggest issues and developing a set of best practices requires a much smaller investment.</p><p><strong>Memory footprint of an Integer object</strong></p><p>With that in mind, consider the following lines of code:</p><pre>public static void main(String[] args) {<br>    Integer i = new Integer(10);<br>}</pre><p>When this code is executed, how much memory gets allocated on the second line ?</p><p>In other words, since an int takes 32 (at least on a 32 bits JVM) our question asks how much memory does an Integer object use. It is obvious that the memory used be an Integer object will need to contain the int payload, thus used 32 bits. More than that, it will also use some memory for the fields that the Integer class inherits from Object class.</p><p>Take a look at the image below, and see that Integer class inherits 3 fields from Object class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTtnirNWjbaFOarhNP_42Q.png" /></figure><p>The first field is a reference to a Class object. Indeed every object in Java has a reference to the class that object is an instance of. This reference uses 32 bits.</p><p>The second field is a 32 bits field containing flags and the identity hash code. As a note, the first bit is the shape bit, it marks if the object is a normal object or an array. The identity hash code is usually the initial memory address where the object was first allocated. This value is cached here, and used for other operations, for example the hashCode() method.</p><p>The third field contains locks. It is a well known fact that each Java object must contain a lock that is used by the synchronization mechanism.</p><p>Thus, a simple instantiation of an Integer object will use 4 * 32 = 128 bits of memory, since the Integer object has four 32 bit fields.</p><p><strong>Memory footprint of an int array</strong></p><p>Let us also take a look at the memory footprint of an int[]:</p><pre><em>int[] a = {10};</em></pre><p>As expected, this array object will contain similar fields inherited from the Object class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTtnirNWjbaFOarhNP_42Q.png" /></figure><p>We see the class, pointer, the flags, the locks and an extra 32 bits field, the size field. The value of this field is the number of values contained by the int array, the length of the array. The actual int values follow, in a contiguous fashion, each value using another 32 bits. In total, the array “a” above will use 5 * 32 = 160 bits of memory.</p><p><strong>Memory footprint of a String object</strong></p><p>Now let’s see how much memory is used by a String object:</p><pre><em>String s = new String(“myString”);</em></pre><p>It is clear that a String object will inherit some fields from Object class and also needs to store the actual characters contained by that string. Its memory footprint will look like in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iblGnd_BL-9ODmlB_KV5eg.png" /></figure><p>As we can see, a String object stores the usual class pointer, flags, locks fields and some additional new ones.</p><p>The hash field, is a 32 bit field containing the hash code value of that string. Since strings are immutable this hash code will never change, thus it makes sense to compute it once then store it.</p><p>The count field value is the number of characters in the String object.</p><p>The offset field contains the value of the first index of storage. Namely, since the characters are stored in a char array, the offset tells us the index in that array and the count tells the number of character the string actually has. In case our program uses a large string and a smaller sub string of it, this mechanism ensures that both of them will share the same char array.</p><p>The value field is a 32 bits reference to a char array.</p><p>The char array itself contains the class pointer, flags, locks and size fields, just like the int array above, and in addition to them, the actual chars in our string. These chars are stored on 16 bits, thus we have 2 chars stored in a 32 bit portion of contiguous memory.</p><p>The total memory used by our line of code is 7 * 32 + 8 * 32 = 224 + 256 = 480 bits, grouped in two parts of contiguous memory.</p><p><strong>Memory footprint of String concatenation</strong></p><p>An interesting case is in the code below:</p><pre>String s1 = “string 1”;<br>String s2 = “string 2”;<br>String s3 = s1 + s2;</pre><p>What happens in the third line of code, and what is the memory footprint of the code above ?</p><p>The first thing we must remember is how Java treats string concatenation. Namely, at compile time, the third line above will be replaced by the following:</p><pre><em>s3 = new StringBuilder(String.valueOf(s1)).append(s2).toString();</em></pre><p>Therefore we can see that memory will be allocated for strings s1, s2 and s3 and also for the StringBuilder object. This means that the memory footprint will look something similar to this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*P1r6P5ZjK3eSmsckB70jcA.png" /></figure><p>Thus 4 objects that each contain a reference to a char array will be created (s1, s2 , s3 and a reference of the StringBuilder object) and 4 char arrays.</p><p>This is actually not this simple, due to the Java String literal pool mechanism. In order to conserve memory, all string literal values are stored in a special memory area called the String literal pool.</p><p>One other thing to notice is that the char arrays belonging to s1, s2 and s3 must be immutable, since s1, s2 and s3 are immutable. The underlining char array for the StringBuilder object should be mutable, since StringBuilder is a mutable class. This however is not in the scope of this article.</p><p><strong>Conclusions and best practices</strong></p><ul><li>Integer objects use 4 times as much memory than a 32 bit int. Whenever all other things are equal, use a int[] instead of an Integer[]</li><li>For object arrays there is an overhead (extra fields) to the actual useful information. The overhead is constant though this means that he larger the payload (larger array) the less wasted memory</li><li>String objects share some similarities with char arrays. They are immutable and there exist memory saving mechanisms like the Java String literal pool</li><li>Use StringBuilder instead of string concatenation. The compiler uses them anyway, therefore it is much better to do it in a manner where you have full control and transparency over what happens</li></ul><p>For further conclusions please take a look at the part 2 of this article: <a href="https://medium.com/metrosystemsro/java-memory-footprint-part-2-8791679178e2">Java memory footprint — part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf8785d6a47a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metrosystemsro/https-medium-com-metrosystemsro-java-memory-footprint-part-1-cf8785d6a47a">Java memory footprint — part 1</a> was originally published in <a href="https://medium.com/metrosystemsro">METRO SYSTEMS Romania</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda expressions — a simple way to get acquainted with Java 8]]></title>
            <link>https://medium.com/metrosystemsro/lambda-expressions-a-simple-way-to-get-acquainted-with-java-8-5ea4408e3ec7?source=rss-ad0571cc9691------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea4408e3ec7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[lambda-function]]></category>
            <dc:creator><![CDATA[Liviu Adrian Esanu]]></dc:creator>
            <pubDate>Tue, 13 Jun 2017 09:06:11 GMT</pubDate>
            <atom:updated>2017-06-13T09:06:11.532Z</atom:updated>
            <content:encoded><![CDATA[<p>The beauty of adopting java 8 early on is that it gives an extra option to developers. Namely if a project ports to using java 8 but code is still mostly written in a java 7 fashion, one can incrementally add or use features of java 8, having the option to both increase or decrease the pace of its adoption. Let’s take a look at three examples of how code is written in the old and new fashion, with the concrete benefit of it being more concise using Java 8.</p><p>This is a sample implementation of the <strong>Strategy pattern </strong>in Java 7:</p><pre>public interface Validator {<br>    boolean validate(String s);<br>}<br><br>public class IsLowercase implements Validator {<br>     public boolean validate(String s){<br>        return s.matches(&quot;[a-z]+&quot;);<br>    }<br>}<br><br>public class IsNumeric implements Validator {<br>    public boolean validate(String s){<br>        return s.matches(&quot;\\d+&quot;);<br>    }<br>}<br><br>public class FieldValidator {<br>    private final Validator v;<br><br>    public FieldValidator(Validator v){<br>        this.v = v;<br>    }<br>    public boolean validate(Field field){<br>        return v.validate(field.getInput());<br>    }<br>}<br><br>FieldValidator isNum = new FieldValidator(new IsNumeric());<br>boolean b1 = isNum.validate(new Field(&quot;1234&quot;)); <br>FieldValidator isLower = new FieldValidator(new IsLowercase());<br>boolean b2 = isLower.validate(new Field(&quot;lambda&quot;));</pre><p>It has the following counterpart in Java8, lambda expressions remove the need for two of the classes (IsLowercase and IsNumeric):</p><pre>FieldValidator numericValidator = new FieldValidator((String s) -&gt;    s.matches(&quot;\\d+&quot;));<br>boolean a = numericValidator.validate(new Field(&quot;1234&quot;));</pre><pre>FieldValidator lowerCaseValidator = new FieldValidator((String s) -&gt; s.matches(&quot;[a-z]+&quot;));<br>boolean b = lowerCaseValidator.validate(new Field(&quot;lambda&quot;));</pre><p>The same holds true for the <strong>Observer pattern</strong>:</p><pre>Interface Observer {<br>    void notify(String tweet);<br>}<br><br>class Wine implements Observer {<br>    public void notify(String tweet) {<br>        if(tweet.contains(&quot;wine&quot;)) {<br>            System.out.println(&quot;Breaking news: &quot; + tweet);<br>        }<br>    }<br>}<br><br>class Queen implements Observer {<br>    public void notify(String tweet) {<br>        if(tweet.contains(&quot;queen&quot;)) {<br>            System.out.println(&quot;Exclusive: &quot; + tweet);<br>        }<br>    }<br>}<br><br>interface Subject {<br>    void registerObserver(Observer o);<br>    void notifyObservers(String tweet);<br>}<br><br>class Feed implements Subject {<br>    private final List&lt;Observer&gt; observers = new ArrayList&lt;&gt;();<br>    <br>    public void registerObserver(Observer o) {<br>        this.observers.add(o);<br>    }<br>    <br>    public void notifyObservers(String tweet) {<br>        observers.forEach(o -&gt; o.notify(tweet));<br>    }<br>}</pre><p>And the usage is:</p><pre>Feed f = new Feed();<br>f.registerObserver(new Wine());<br>f.registerObserver(new Queen());</pre><pre>f.notifyObservers(&quot;The queen loves French wine!&quot;);</pre><p>The counterpart in Java 8, using lambdas will also eliminate the need for class Queen and Wine:</p><pre>f.registerObserver(<br>    (String tweet) -&gt; {<br>        if(tweet.contains(&quot;wine&quot;)) {<br>            System.out.println(&quot;Breaking news: &quot; + tweet);<br>        }<br>    });<br><br>f.registerObserver(<br>    (String tweet) -&gt; {<br>        if(tweet.contains(&quot;queen&quot;)) {<br>            System.out.println(&quot;Exclusive: &quot; + tweet);<br>    }<br>});</pre><p>And lastly, below is the Java 7 code for the <strong>Processing pipeline</strong> <strong>pattern</strong>:</p><pre>abstract class ProcessingObject&lt;T&gt; {<br>    protected ProcessingObject&lt;T&gt; successor;<br>    <br>    public void setSuccessor(ProcessingObject&lt;T&gt; successor) {<br>        this.successor = successor;<br>    }<br><br>    public T handle(T input) {<br>        T r = handleWork(input);<br>        if (successor != null) {<br>            return successor.handle(r);<br>        }<br>        <br>        return r;<br>    }<br><br>    abstract protected T handleWork(T input);<br>}<br><br>class Header extends ProcessingObject&lt;String&gt; {<br>    public String handleWork(String text) {<br>        return &quot;You might like: &quot; + text;<br>    }<br>}<br><br>class Spellchecker extends ProcessingObject&lt;String&gt; {<br>    public String handleWork(String text) {<br>        return text.replaceAll(&quot;aquainted&quot;, &quot;acquainted&quot;);<br>    }<br>}</pre><p>The usage will be something like:</p><pre>ProcessingObject&lt;String&gt; p1 = new Header();<br>ProcessingObject&lt;String&gt; p2 = new Spellchecker();<br>p1.setSuccessor(p2);</pre><pre>String result = p1.handle(“A simple way to get acquainted with Java 8”);<br>System.out.println(result);</pre><p>And here is the Java 8 correspondent, again notice that it is less verbose as we no longer need classes Header and Spellchecker:</p><pre><em>UnaryOperator&lt;String&gt; header = (String text) -&gt; &quot;You might like: &quot; + text;</em></pre><pre><em>UnaryOperator&lt;String&gt; spellchecker = (String text) -&gt; text.replaceAll(&quot;</em>aquainted&quot;<em>, </em>&quot;acquainted<em>&quot;);</em></pre><pre><em>Function&lt;String, String&gt; pipeline = header.andThen(spellchecker);</em></pre><pre><em>String result = pipeline.apply(&quot;</em>A simple way to get acquainted with Java 8<em>&quot;);</em></pre><pre><em>System.out.println(result);</em></pre><p>There is no question if current Java applications will have to be migrated eventually to Java 8 in order to take advantage of the servers and new technologies that will be available for it. The effort will have to be done, be it now or later. It seems thus reasonable to consider the benefits of doing it now, and how much effort is needed to see the first results.</p><p>In conclusion, adopting java 8 earlier rather than later is a better approach. It offers more options and it can be done incrementally, without the need of a quick concentrated effort from developers to master the new features.</p><p>As part of the “Java solutions” team at METRO SYSTEMS ROMANIA, I have experienced first hand the adoption of Java 8 by a large company. Every project had to decide for itself whether it switches or not, from java 7 to java 8, and when to do or not do so. This turned out to be of great idea because it made the more passionate and curious programmers, hyped by the java 8 features, interact with the more conservative ones. This made the first group explain, convince, clarify and persuade the later.</p><p>Further reading and bibliography:</p><ol><li><a href="https://en.wikipedia.org/wiki/Strategy_pattern">https://en.wikipedia.org/wiki/Strategy_pattern</a></li><li><a href="https://en.wikipedia.org/wiki/Observer_pattern">https://en.wikipedia.org/wiki/Observer_pattern</a></li><li><a href="https://en.wikipedia.org/wiki/Pipeline_(computing)">https://en.wikipedia.org/wiki/Pipeline_(computing)</a></li><li><a href="https://www.amazon.de/Java-8-Lambdas-Richard-Warburton/dp/1449370772">https://www.amazon.de/Java-8-Lambdas-Richard-Warburton/dp/1449370772</a></li><li><a href="https://github.com/RichardWarburton/java-8-lambdas-exercises">https://github.com/RichardWarburton/java-8-lambdas-exercises</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea4408e3ec7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metrosystemsro/lambda-expressions-a-simple-way-to-get-acquainted-with-java-8-5ea4408e3ec7">Lambda expressions — a simple way to get acquainted with Java 8</a> was originally published in <a href="https://medium.com/metrosystemsro">METRO SYSTEMS Romania</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>