<?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 Alex Kuk on Medium]]></title>
        <description><![CDATA[Stories by Alex Kuk on Medium]]></description>
        <link>https://medium.com/@lk.snatch?source=rss-6b279bcf490------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*JYZunXU_bBw5vTefTFa3Eg.jpeg</url>
            <title>Stories by Alex Kuk on Medium</title>
            <link>https://medium.com/@lk.snatch?source=rss-6b279bcf490------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:15:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lk.snatch/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[Assert vs Serialize]]></title>
            <link>https://medium.com/@lk.snatch/assert-vs-serialize-c2fbc6b184ea?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2fbc6b184ea</guid>
            <category><![CDATA[asserts]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[deserialization]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 09:00:09 GMT</pubDate>
            <atom:updated>2020-08-10T09:00:09.648Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine, that you have a class only with one private variable and one private method with the assertion inside, like:</p><pre>public class SerializationAssertionCheck implements Serializable {</pre><pre>  private int someNumber = 5;</pre><pre>  private void check() {</pre><pre>    assert someNumber == 5;</pre><pre>  }</pre><pre>}</pre><h4><strong>the Question:</strong></h4><p>Create an object of this class and serialize it to a file. Then comment ‘<em>assert</em>’ command and deserialize the object from the file.</p><p><strong>Will it be serialized or not?</strong></p><p>- yes, it will</p><p>- it will throw some of serialization exception</p><p>- it won’t compile</p><h4><strong>the Answer:</strong></h4><p>It will throw an <em>InvalidClassException</em>:</p><pre>java.io.InvalidClassException: net.snatchTech.assertSerialize.SerializationAssertionCheck;</pre><pre>local class incompatible: stream classdesc serialVersionUID = 7171967375950265774,</pre><pre>local class serialVersionUID = 6475217375515940924</pre><h4><strong>But why? It’s just an assert command in the method!</strong></h4><p>Okay, first of all, what is <em>serialVersionUID</em> from the exception description?</p><p>It’s a long number, which represents the original class version. It is used for comparing classes during deserialization: if you’re trying to deserialize a file to an object with incompatible class (with another <em>serialVersionUID</em> (SUID)), you’ll get an exception like above.</p><h4><strong>But we didn’t define this field!</strong></h4><p>Yes. But in this case it will be computed from the class structure: class name, modifiers, fields &amp; etc. You can see more details <a href="https://docs.oracle.com/javase/8/docs/platform/serialization/spec/class.html#a4100">at the link</a>.</p><p>As you can see there, each class field participates in the SUID computation, except of private static and private transient fields.</p><h4><strong>And what? How is it connected with my assert command?</strong></h4><p>It’s simple. When you have an assertion somewhere in the class, then you have one more hidden computed field.</p><p>Let’s look on the bytecode:</p><pre>// access flags 0x2</pre><pre>private I someNumber</pre><pre>// access flags 0x1018</pre><pre>final static synthetic Z $assertionsDisabled</pre><p>Z $assertionsDisabled — here you are, my <strong>synthetic</strong> (computed) field!</p><p>So, if you have any assertion in the class, then you have one more synthetic field (for further assertion checks). And because it’s a final static, this field participates in the computation of SUID. Therefore, if you remove all assert commands from the class, you’ll get another SUID and you won’t deserialize old version of this class.</p><h4><strong>What can we do??</strong></h4><p>First of all, <em>do not use assert in the code</em>! Bad practice. But it’s arguable of course)</p><p>Secondly, just define SUID explicitly:</p><pre>private static final long serialVersionUID = 7171967375950265774L;</pre><p>It’s interesting that in the <a href="https://jcp.org/aboutJava/communityprocess/jsr/asrt_prop.html">original assert proposal</a> it was a private static field:</p><pre>final private static boolean $assertionsEnabled = ClassLoader.desiredAssertionStatus(className);</pre><p>and it didn’t affect serialization.</p><h3><strong>Conclusion.</strong></h3><p>You should always be careful, even if you ‘<em>just delete some useless code</em>’.</p><p>You can try the code <a href="https://github.com/lkSnatch/tutorials/tree/master/assertSerialize">in my example</a>.</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2fbc6b184ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistent Hashing]]></title>
            <link>https://medium.com/@lk.snatch/consistent-hashing-5ac730dce9c?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac730dce9c</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 18:24:03 GMT</pubDate>
            <atom:updated>2020-04-05T18:33:44.826Z</atom:updated>
            <content:encoded><![CDATA[<p>What do you know about hash? C’mon, I know you’ve heard about hash functions like MD5, SHA-256 &amp; etc.</p><blockquote>“<em>A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes. The values are used to index a fixed-size table called a hash table.</em>” © <a href="https://en.wikipedia.org/wiki/Hash_function">Wikipedia</a></blockquote><p>Okay, thank you Wikipedia, now we also know what is a hash table (or a hash map). But still let me explain how it basically works.</p><p>Imagine that you work as a lawyer and wanna get court decisions under some articles. These articles are very popular and a lot of other lawyers in your company wanna get the same court decisions very often. But obtaining the data from a DB and aggregation of results are expensive operations. Consequently, one of programmers from your company told you that he is going to use a cache in your application to reduce amount of DB calls.</p><p>Also he mentioned something like “<strong><em>blah-blah .. distributed cache .. blah-blah .. consistent hashing ..</em></strong>”</p><p>If you are curious lawyer, you will read some my articles about <a href="https://medium.com/@lk.snatch/system-design-cache-with-java-impl-eba29b5739dc">cache</a> and <a href="https://medium.com/@lk.snatch/system-design-cache-eviction-policies-with-java-impl-37c1228e2b4f">cache eviction policies</a>. But now we’ll look at what lies at the heart of the cache and how it works. I’m talking about HashMap.</p><h3><strong>HashMap</strong></h3><p>When you wanna put something to the hashMap, the hashCode will be calculated first.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8544eda016030f322fc8e0572b341ce2/href">https://medium.com/media/8544eda016030f322fc8e0572b341ce2/href</a></iframe><pre><em>Article 224 of the Law of May 13, 1863 → 1239031166</em></pre><pre><em>Section 202 of the National Securities Act of 1 947 → -2057294793</em></pre><pre><em>Article 2 of the Act of March 10, 1792 → 1507657450</em></pre><pre><em>section 458-B of the Pure Food and Drug Act → 1971618558</em></pre><pre><em>Section 412 of the Patriot Act → 148124959</em></pre><p>And then it’ll be used to determine in which bucket in the array your value should be put. Let’s simplify all of this. Suppose our keys and their hash codes are:</p><pre><em>Article 224 .. → 53</em></pre><pre><em>Section 202 .. → 24</em></pre><pre><em>Article 2 .. → 77</em></pre><pre><em>section 458-B .. → 34</em></pre><pre><em>Section 412 .. → 96</em></pre><p>And we have a hashMap which based on an array of Nodes and this array has length 10. When we put some value with the key “<em>Article 224</em>”, we need to determine a slot in the array. “<em>Article 224</em>” has a hashCode 53, our array has a length 10, so we can just get the remainder of the division 53 by 10:</p><pre><em>53 % 10 = 3</em></pre><p>Thus the “<em>Article 224</em>” will be put into the slot with index ‘3’ in the array of Nodes. In the same way we can put the key “<em>Section 202</em>” with the hashCode ‘24’ into slot with index ‘4’. But the key “<em>section 458-B</em>” has the hashCode ‘34’ and need to be stored to the slot with index ‘4’ too. What to do? Don’t worry, we have an array of Nodes and every Node can be connected with another Node. Thus just create a new Node with the key “<em>section 458-B</em>” and connect it with the Node “<em>Article 224</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*xA-B_nVlo1mTSE5eisT7Aw.jpeg" /></figure><h3><strong>What’s the problem?</strong></h3><p>When the count of elements equals array length (or some else threshold), we’ll need to add more buckets (<em>10, 11, 12</em> in our case). But then array length will be changed, and if we try to get some element by key, we won’t find it! Look at the formula: it was <em>53 % 10 = 3</em>, but has become <em>53 % 13 = 1</em>. Now it should be stored in the slot with index ‘1’ instead of ‘3’. So, we need to calculate new place for every element in the map and move them to their new home. This operation is called <em>Rehash</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*lCs1D_or1_LSz-zYOhh7rQ.jpeg" /></figure><p>Rehash is expensive operation if our map has a lot of elements.</p><p>Okay, now let’s move our attention to a distributed cache. Suppose the cache has 1 billion elements (the government doesn’t sleep and produces laws). It needs to allocate a huge amount of memory. We could distribute cache between several servers. For example, <em>0–3 buckets could be stored on server S0, 4–6 on S1 and 7–9 on S2</em>. If we wanna get decisions by the “<em>Article 224</em>”, we just need to determine a bucket (<em>53 % 10 = 3</em>) and get a server from some storage (we know that 3rd bin is stored on the server S0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*AGlHj2UM0pcj9LvV3-hPzg.jpeg" /></figure><p>Or we could not store the correspondence of buckets and servers, but calculate the server on the fly. Like to determine the number of bin, we should get the remainder of division by server count: 53 % 3 = 2, it’s mean S2 server (yep, not like on the picture’s table).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNDmqRDcL9Nr1uLvTSulBw.jpeg" /></figure><p>What will go wrong when we add new S3 server or server S2 fails? Yes, the same thing like in a simple hashMap. It nothing changes, when the S3 has been added, our map still need a rehash! Because now (when S3 is added) the count of the servers was changed and “<em>Article 224</em>” will be stored at the server S1 instead of S2 (<em>53 % 4 = 1</em>).</p><p>Why do we need a rehash in the cache? Because, as I described above, after add one more server we will get a cache miss for every element. Yes, you can just wait and after some time cache will be filled.. if your servers are always prepared for this load of course..</p><h3><strong>How to avoid full rehash?</strong></h3><h3><strong>Consistent hashing is the answer!</strong></h3><p>A hashCode() method is return a value with the type “<em>integer</em>”. Array in the hashMap has max length equals Integer.MAX_VALUE. Though, we can split this array on some count of buckets. For simplicity suppose that Integer.MAX_VALUE is 100. Then we can use some count of bins (10 for example) to store values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*1cKLWyYtipf_B34iVVcOsQ.jpeg" /></figure><p>“<em>Article 224</em>” has hash code 53 and will be stored to the 6th bucket (50–59), “<em>Section 202</em>” has # 24, so it’ll be stored to the third bin (20–29), and so on. How to determine the number of the bucket in practice? By binary search! Red-black tree in this case will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*qgt_uC6_i3eJghPvEKvdKA.jpeg" /><figcaption>it should be rebalanced at the left side, of course</figcaption></figure><p>We can move backward or forward, it doesn’t matter, but once chosen, we must always move in this direction. “<em>Article 224</em>” -&gt; 53 -&gt; 50; “<em>Section 202</em>” -&gt; 24 -&gt; 20.</p><p>Returning to the servers, we can assign server and hash mappings: hashes 0–39 as server S0; 40–69 as S1; 70–99 as S2. Determining of the server in this case will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*HwArV4JIzGiKS-iCYmUpCw.jpeg" /></figure><p>If we choose backward direction, then 53 will accord to the 40 (S1 server); 24 to 0 (S0 server) and so on.</p><h3><strong>But again, what if S2 goes down?</strong></h3><p>Then all it’s requests will be redirected to the server S1, according to backward direction in the servers tree: 77 -&gt; 40 (S1); 96 -&gt; 40 (S1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*-YyDlRy4qsEYPuuhcnHHNg.jpeg" /></figure><p>I think that the S1 server won’t be happy to work for two. And what to do? <strong>Add more servers of course! But virtual.</strong> We can assign S0 to buckets with the # 0–9, 30–39, 50–59, 80–89; S1 -&gt; 10–19, 40–49, 60–69; S2 -&gt; 20–29, 70–79, 90–99. Also we can give a label for each bucket, like: S0_0 -&gt; 0–9; S0_5 -&gt; 50–59; S0_8 -&gt; 80–89; S1_1 -&gt; 10–19; S1_4 -&gt; 40–49 …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*CKDmjSgABCIS7RIXtJMelQ.jpeg" /></figure><p><strong>Servers should be distributed randomly.</strong> And now, if S2 fails, according to a backward direction in the # tree, two requests will go to S1 (S2_2 -&gt; S1_1, S2_7 -&gt; S1_6) and one request to S0 (S2_9 -&gt; S0_8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*prP0Z8M4vrNIduEVH75kPw.jpeg" /></figure><p>The more randomly labeled buckets — the better distribution, when one of the servers goes down. You don’t need a full rehash, the elements on the servers S0 &amp; S1 will stay at their place. You will get a cache miss only for elements from S2.</p><p><strong>If a new server is added (S3)</strong>, you should allocate its labels somewhere from 0 to 100. For example, S3_75 -&gt; # 75–79, then S2_7 will be limited by hashes 70–74, instead of 70–79. And you will get a cache miss only for requests with the keys with the hashes 75–79:</p><pre>“<em>Section 412</em>” -&gt; # 77 -&gt; S3_75 (S3 server).</pre><p>The old records on the S2 (with # 75–79) will be removed after some time according to its eviction policy.</p><h3><strong>Java implementation</strong></h3><p>Let’s create a simple application which could show the consistent hashing in action. It should contain servers with their labels (virtual servers) and distributed between them cache.</p><p>Create a Server class first, which will store a server name and list of its labels:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47c46e41aa04d612cfa4f1e70a7f6656/href">https://medium.com/media/47c46e41aa04d612cfa4f1e70a7f6656/href</a></iframe><p>ServerLabel class will get range start randomly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a0c4ea1f1945c438bd16cebb6dadd4/href">https://medium.com/media/d8a0c4ea1f1945c438bd16cebb6dadd4/href</a></iframe><p>Also we need a ServerTree (hash ring), which will store the available servers (server labels more precisely):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbdb08cf328f38c0bd46969c086e0518/href">https://medium.com/media/fbdb08cf328f38c0bd46969c086e0518/href</a></iframe><p>Create a cache based on concurrent hash map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4df35e7b57c492f1fc4ece218b8f5a/href">https://medium.com/media/0e4df35e7b57c492f1fc4ece218b8f5a/href</a></iframe><p>And DecisionService which can put and get value from distributed cache:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/309d3819b00f807f04b1d8c5a1013fca/href">https://medium.com/media/309d3819b00f807f04b1d8c5a1013fca/href</a></iframe><p>Okay, now we are prepared to create a main method. Let’s go ahead and simply create a three servers with their own cache:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5427f362c23be02391c9a07ebae2de73/href">https://medium.com/media/5427f362c23be02391c9a07ebae2de73/href</a></iframe><p>After that add nine virtual servers (labels) to the hash ring (server tree):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00b831aa368703830daeeec57bc1c741/href">https://medium.com/media/00b831aa368703830daeeec57bc1c741/href</a></iframe><p>And put the values to the distributed cache:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef942e524fc6da21c20cc4cf01324be4/href">https://medium.com/media/ef942e524fc6da21c20cc4cf01324be4/href</a></iframe><p>Server tree is looked like this now:</p><pre><em>label=’S3_8&#39;, rangeStart=79620631</em></pre><pre><em>label=’S1_2&#39;, rangeStart=457191453</em></pre><pre><em>label=’S2_3&#39;, rangeStart=476515658</em></pre><pre><em>label=’S3_7&#39;, rangeStart=831012325</em></pre><pre><em>label=’S2_4&#39;, rangeStart=1000870721</em></pre><pre><em>label=’S1_0&#39;, rangeStart=1159297670</em></pre><pre><em>label=’S2_5&#39;, rangeStart=1206315082</em></pre><pre><em>label=’S1_1&#39;, rangeStart=1260733873</em></pre><pre><em>label=’S3_6&#39;, rangeStart=1758698458</em></pre><p>Just remind: the key “<em>Section 412 of the Patriot Act” </em>has a hash code<em> </em><em>148124959.</em> Thus, this key should be stored at the server S3 with the label <em>S3_8</em>, because it has a nearest fewer range start number <em>79620631.</em></p><p>Check the caches:</p><pre><em>S1 Cache: Article 2 of the Act of March 10, 1792, not guilty</em></pre><pre><em>S2 Cache: Article 224 of the Law of May 13, 1863, fully justified</em></pre><pre><em>S3 Cache: Section 202 of the National Securities Act of 1 947, partially justified</em></pre><pre><em>section 458-B of the Pure Food and Drug Act, almost guilty</em></pre><pre><em>Section 412 of the Patriot Act, we doubt</em></pre><p>So, “<em>Section 412..”</em> is stored at the server S3, it’s true!</p><p>Let’s try to find it:</p><pre>decisionService.getValue(“Section 412 of the Patriot Act”)</pre><p>Got it:</p><pre><em>we doubt</em></pre><p>Let’s imitate the server S3 fails:</p><pre>s3.getLabels().forEach(serverTree::removeServer);</pre><p>And try to get the value again:</p><pre><em>null</em></pre><p><strong>Expectedly</strong>. If you check the caches, you will see that all values on their places. But anyway we can’t find the value for the key “<em>Section 412..”</em>, because now we’re trying to find it at another server. Put it again:</p><pre>decisionService.putValue(“Section 412 of the Patriot Act”, “we doubt”);</pre><p>And let’s see where it was stored:</p><pre><em>S1 Cache: Article 2 of the Act of March 10, 1792, not guilty</em></pre><pre><em>Section 412 of the Patriot Act, we doubt</em></pre><p><strong>The value went to the server S1</strong>. And try to get the value again:</p><pre><em>we doubt</em></pre><p><em>Expectedly</em>.</p><h3><strong>Conclusion</strong></h3><p>I hope this explanation was clearly. But if not, there is <a href="https://www.toptal.com/big-data/consistent-hashing">another one based on a hash ring</a>.</p><p>You can look at the full code on my <a href="https://github.com/lkSnatch/tutorials/tree/master/consistent-hashing">github project</a>.</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac730dce9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System design: cache eviction policies (with java impl)]]></title>
            <link>https://medium.com/@lk.snatch/system-design-cache-eviction-policies-with-java-impl-37c1228e2b4f?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c1228e2b4f</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[eviction-policy]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 08:57:58 GMT</pubDate>
            <atom:updated>2020-03-26T08:33:12.206Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@lk.snatch/system-design-cache-with-java-impl-eba29b5739dc">previous article</a> we defined what cache is, what we need to know about our data and how to implement different writing policies. Show must go on! And now it’s time to show how records could be forced out of the cache.</p><h3><strong>Why do we need it?</strong></h3><p>As I mentioned earlier, hashtable is the most suitable data structure for building a cache system. Because it has O(1) access for both put and get operations (if you have a good hash function which provide a uniform distribution of hash values). But hashtable has O(n) occupied memory space. Therefore we need to remove some unnecessary entries and keep only those that are in demand.</p><h3><strong>Eviction policies</strong></h3><p>There are a lot of eviction policies:</p><p>- <em>FIFO (First In First Out), LIFO (Last In First Out)</em> — I think it doesn’t need to be explained.</p><p>- <em>LRU (Least Recently Used) </em>— discards items that have not been used for a long time (more than other elements in the cache).</p><p>- <em>TLRU (Time aware Least Recently Used) </em>— LRU with a valid life time for the elements.</p><p>- <em>MRU (Most Recently Used) </em>— discards items that have been used latest.</p><p>- <em>RR (Random Replacement) </em>— randomly selects a candidate for replacement to make space.</p><p>- <em>SLRU (Segmented LRU) </em>— two segments of the cache — probationary and protected segments. Both are constructed on LRU concepts. A new value adds to the probationary segment first. When this value is requested again, it will be moved to the protected segment.</p><p>- <em>LFU (Least Frequently Used) </em>— counts how often an item is needed and discards rare elements.</p><p>- <em>LFRU (Least Frequent Recently Used) </em>— like SLRU, it has two partitions, but one is LFU and the other is LRU (with the most popular content).</p><p>- <em>LIRS (Low Inter-reference Recency Set) </em>— replaces items based on their recency.</p><p>- <em>ARC (Adaptive Replacement Cache) </em>— balances between LRU and LFU. It is based on SLRU, but it can dynamically adjust the size of both segments.</p><h3><strong>Okay, but what about admission policy?</strong></h3><p>Oh, you can just add values and not worry.. But you can also calculate entries uses, compare a new value and an evict candidate, and decide whether to add a new value.</p><p>But now, let’s discuss about replacement policies more precisely: LRU, LFU &amp; SLRU.</p><h3><strong>1.</strong> <strong>Least Recently Used</strong></h3><p>In the cache HashTable we store the keys (by which we’re gonna find) and the values (what we’re gonna find). But we need to know the sequence of using items to evict the oldest one. Linked list could help us! Just use the nodes of linked list as the values in our cache.</p><p>Create nested class Node and override toString() method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ba83e6a52f29829c9fe248e19a1dbb/href">https://medium.com/media/b6ba83e6a52f29829c9fe248e19a1dbb/href</a></iframe><p>Our cache class will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf3a784af0bc001d8a184e96878b8bf/href">https://medium.com/media/ecf3a784af0bc001d8a184e96878b8bf/href</a></iframe><p>Suppose we have a sequence to set/get values to/from a cache “<em>A B C D E B F E</em>” and cache size equals to 4. What will happen?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*TrpnhPyxiikgdEn_Y7nM5A.jpeg" /></figure><p>In 1–4 steps the A,B,C,D will be set.</p><p>5. We need to add E to the cache, but the cache size if four, therefore we must evict something. The most unused item is A, so cut it out.</p><p>6. Get B from the cache (or set, it doesn’t matter). Replace B to the head of our linked list as last used element.</p><p>7. Add F. Now C is the most unused item, cut it and add F to the head.</p><p>8. Get E. Replace E to the head of the list and connect D and B between each other.</p><p>Not so difficult, is it?</p><p>Create get() and set() methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/627762ed76acaf46b9c8da0d830e8b42/href">https://medium.com/media/627762ed76acaf46b9c8da0d830e8b42/href</a></iframe><p>Note that catching of all situations and errors is not our purpose. This code just shows the logic of the cache with LRU eviction policy.</p><p>Create a test method and show the cache content with a head and a tail in each step (every node shows like <em>{previous node item &lt;← current node item →&gt; next node item}</em>):</p><pre><em>0 — — — — — — — </em></pre><pre><em>head=null</em></pre><pre><em>{}</em></pre><pre><em>tail=null</em></pre><pre><em>1 — — — — — — — </em></pre><pre><em>head= null &lt;← A →&gt; null</em></pre><pre><em>{1= null &lt;← A →&gt; null}</em></pre><pre><em>tail= null &lt;← A →&gt; null</em></pre><pre><em>2 — — — — — — — </em></pre><pre><em>head= A &lt;← B →&gt; null</em></pre><pre><em>{1= null &lt;← A →&gt; B, 2= A &lt;← B →&gt; null}</em></pre><pre><em>tail= null &lt;← A →&gt; B</em></pre><pre><em>3 — — — — — — — </em></pre><pre><em>head= B &lt;← C →&gt; null</em></pre><pre><em>{1= null &lt;← A →&gt; B, 2= A &lt;← B →&gt; C, 3= B &lt;← C →&gt; null}</em></pre><pre><em>tail= null &lt;← A →&gt; B</em></pre><pre><em>4 — — — — — — — </em></pre><pre><em>head= C &lt;← D →&gt; null</em></pre><pre><em>{1= null &lt;← A →&gt; B, 2= A &lt;← B →&gt; C, 3= B &lt;← C →&gt; D, 4= C &lt;← D →&gt; null}</em></pre><pre><em>tail= null &lt;← A →&gt; B</em></pre><pre><em>5 — — — — — — — </em></pre><pre><em>head= D &lt;← E →&gt; null</em></pre><pre><em>{2= null &lt;← B →&gt; C, 3= B &lt;← C →&gt; D, 4= C &lt;← D →&gt; E, 5= D &lt;← E →&gt; null}</em></pre><pre><em>tail= null &lt;← B →&gt; C</em></pre><pre><em>6 — — — — — — — </em></pre><pre><em>head= E &lt;← B →&gt; null</em></pre><pre><em>{2= E &lt;← B →&gt; null, 3= null &lt;← C →&gt; D, 4= C &lt;← D →&gt; E, 5= D &lt;← E →&gt; B}</em></pre><pre><em>tail= null &lt;← C →&gt; D</em></pre><pre><em>7 — — — — — — — </em></pre><pre><em>head= B &lt;← F →&gt; null</em></pre><pre><em>{2= E &lt;← B →&gt; F, 4= null &lt;← D →&gt; E, 5= D &lt;← E →&gt; B, 6= B &lt;← F →&gt; null}</em></pre><pre><em>tail= null &lt;← D →&gt; E</em></pre><pre><em>8 — — — — — — — </em></pre><pre><em>head= F &lt;← E →&gt; null</em></pre><pre><em>{2= D &lt;← B →&gt; F, 4= null &lt;← D →&gt; B, 5= F &lt;← E →&gt; null, 6= B &lt;← F →&gt; E}</em></pre><pre><em>tail= null &lt;← D →&gt; B</em></pre><p>As you can see every node and item is in their place.</p><p>Actually, Java has an implementation of this cache variant in <em>LinkedHashMap</em>.</p><h3><strong>What is the problem with LRU?</strong></h3><p>With the addition of many new elements, we can replace some items, which were frequently used.</p><h3><strong>2.</strong> <strong>Least Frequently Used</strong></h3><p><em>Apache</em> did the LFU cache implementation in one of the ways. Let’s consider it!</p><p>They have a node:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3daf7a74cc3ecc25f9f3a84203de2d52/href">https://medium.com/media/3daf7a74cc3ecc25f9f3a84203de2d52/href</a></iframe><p>and a cache with some parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2202ad4a5577edd6fc5218bdbf5c6e31/href">https://medium.com/media/2202ad4a5577edd6fc5218bdbf5c6e31/href</a></iframe><p>The cache is a hashMap with some object as key and Node as value. The Node stores key&amp;value with the uses frequency.</p><p>Frequency list is an array of linked sets of the same Nodes as in the cache.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a78e834f3abebcff36f86f4ff12043d/href">https://medium.com/media/4a78e834f3abebcff36f86f4ff12043d/href</a></iframe><p>How does it work and why do they need <em>lowestFrequency</em> and <em>maxFrequency</em>? Let’s do a test with the sequence of “<em>A B C D E B B B B B F E</em>” and look at the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*k7ykDk0scotlDnkczkai3Q.jpeg" /></figure><p>1–4 steps: put A,B,C,D in the set at 0 position (each was just used once).</p><p>Step 5: put E and evict A (E used once, A is the least recently used item).</p><p>Step 6: B was accessed twice -&gt; move it to the next set with index 1.</p><p>7–10 steps: B was accessed six times and moved to the set at index 5. But cache size is 4, so B was moved to the set at 3 position in the array.</p><p>Step 11: put F.</p><p>Step 12: E was accessed twice -&gt; move it to the next set with index 1.</p><p><strong>The main thing here is:</strong> the index of the <em>frequencyList</em> array is a frequency of the items inside the set in this position.</p><pre><em>0 — — — — — — </em></pre><pre><em>{}</em></pre><pre><em>[[], [], [], []]</em></pre><pre><em>1 — — — — — — </em></pre><pre><em>{1=A=0}</em></pre><pre><em>[[A=0], [], [], []]</em></pre><pre><em>2 — — — — — — </em></pre><pre><em>{1=A=0, 2=B=0}</em></pre><pre><em>[[A=0, B=0], [], [], []]</em></pre><pre><em>3 — — — — — — </em></pre><pre><em>{1=A=0, 2=B=0, 3=C=0}</em></pre><pre><em>[[A=0, B=0, C=0], [], [], []]</em></pre><pre><em>4 — — — — — — </em></pre><pre><em>{1=A=0, 2=B=0, 3=C=0, 4=D=0}</em></pre><pre><em>[[A=0, B=0, C=0, D=0], [], [], []]</em></pre><pre><em>5 — — — — — — </em></pre><pre><em>{2=B=0, 3=C=0, 4=D=0, 5=E=0}</em></pre><pre><em>[[B=0, C=0, D=0, E=0], [], [], []]</em></pre><pre><em>6,7,8,9,10 — — — — — — </em></pre><pre><em>{2=B=3, 3=C=0, 4=D=0, 5=E=0}</em></pre><pre><em>[[C=0, D=0, E=0], [], [], [B=3]]</em></pre><pre><em>11 — — — — — — </em></pre><pre><em>{2=B=3, 4=D=0, 5=E=0, 6=F=0}</em></pre><pre><em>[[D=0, E=0, F=0], [], [], [B=3]]</em></pre><pre><em>12 — — — — — — </em></pre><pre><em>{2=B=3, 4=D=0, 5=E=1, 6=F=0}</em></pre><pre><em>[[D=0, F=0], [E=1], [], [B=3]]</em></pre><p>1. The frequency of any item cannot be more than the cache size.</p><p>2. All elements in the cache are stored in the linked sets by their frequency: if the item is just put, it will be stored at the end of linked set at zero position in the array. If it is accessed once — it’ll be moved to the end of the linked set at position one in the array, and so on. When item is accessed 4 or more times (in our case 4 is a maximum cache size = <em>maxFrequency</em>), it’ll be put to the latest linked set in the array and the count of uses of this item won’t be higher than 3 (positions in the array starts from zero).</p><p>3. When we need to evict some element, we take the linked hash set from the array by index = <em>lowestFrequency</em>, then remove the first (least) item from it (an <em>iterator</em> will help us).</p><p>That’s it. <strong>We have O(1) time complexity</strong> for get and put operations.</p><h3><strong>What’s the problem?</strong></h3><p>We don’t take into account how frequently each item has been accessed during the whole period. Is it possible? Of course, everything is possible, even the flying unicorns!</p><p>Use the separate map to store the frequency and one more for the linked sets (instead of using an array):</p><pre>private final HashMap&lt;K, Long&gt; frequency;</pre><pre>private final HashMap&lt;Long, LinkedHashSet&lt;K&gt;&gt; frequencySets;</pre><p>If we don’t remove evicting items from this frequency map, we will get actual whole period count of using any element. We don’t need a <em>maxFrequency </em>variable in this case, ’cause we have a map of sets instead of an array, and we can store any count. If the frequency of some item reaches a maximum of long-type, we need to do something. For example, divide all the frequencies by two, or just drop this item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*CtMvnzKuDoQKpvQhnOtmyw.jpeg" /></figure><p>7–10 steps: B has been accessed six times and moved to the set at hash of 6. We removed the restriction of the maximum frequency.</p><p>You can look closer at this implementation in the class <em>LFUCacheThreeMaps, </em>the link to the whole code at github will be presented at the end of the article.</p><p>But.. what’s the problem?? Of course in the memory! It’s not rubber! All keys will be stored forever.. And what can we do?</p><h3><strong>3.</strong> <strong>Count Min Sketch</strong></h3><p>Let’s take some sequence again “<em>A B C D E B B B B B F E</em>”. How often is every letter repeated?</p><p>A — 1, B — 6, C — 1, D — 1, E — 2, F — 1. How could we store it without storing the keys? With a hashing.</p><p>Suppose we have a four different hash functions with the same distribution of six samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*pg3UYxzrbM8lipb9UisN9w.jpeg" /></figure><p>A is accessed (put or get — it doesn’t matter).</p><p>Hash function 1 on key A gives the result 5. Take current value on position 5 (in the right table) and increase it by 1.</p><p>Hash function 2 on key A gives the result 3. Take current value on position 3 (in the right table) and increase it by 1.</p><p>Hash 3 gives us 2, and hash 4 returns 1. Increase it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*p6W06wu7TVO7dY8fO8JatQ.jpeg" /></figure><p>B is accessed.</p><p>Hash function 1 on key B gives the result 3. Take current value on position 3 (in the right table) and increase it by 1.</p><p>Do it for each result of hash functions on B.</p><p>Note that hash3 on key B has a result of 2, like on the key A. It means that after increasing the number in the right table, we will get the 2 uses/accesses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*fQ2hitokPPWIqBANIOpCLg.jpeg" /></figure><p>Do it all for the key C. And so on for every next accessed key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR1A_7PVOYCY0fTSC9wRHg.jpeg" /></figure><p>Okay, and how could it help us determine the count of every key use?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gzcSjRYL0QPiBUzSkNF1jA.jpeg" /></figure><p>It’s simple: take all counted values for the key and determine the minimum of them.</p><p>For the key A: hash1 has a result 5. Look at the right table at position hash1–5 and find there the counted value 2. Do it for every hash function. Take the minimum of the results — it’ll be the 1. So, A was accessed once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*0j1O5BsVAz7KDIenC8x5Fw.jpeg" /></figure><p>B has been accessed six times. It’s true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*E0wmO2gEYGljN-qDk9wLrw.jpeg" /></figure><p>C has been allegedly accessed 2 times. But we know that C was accessed just once. It’s not a mistake. With Count Min Sketch you will get the actual number of the item uses or more. But no less.</p><p>If you want to increase the precision, you can add more hash functions.</p><p>What if we reach the maximum of using variable type in the table of uses? Just divide all the frequencies by two, or drop this item.</p><h3><strong>4.</strong> <strong>True cache with blackjack and levels!</strong></h3><p>How could we use all our new knowledge? Let’s build a true cache with blackjack and levels!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*kb51WE6lKqUckCTu18fpmA.jpeg" /></figure><p>What’s going on here? We have two levels of cache. First level — is simple LRU cache, contains all new items. Second level — is SLRU cache with the two LRU segments. But we have an <strong>admission policy</strong> for this level: any <em>new item should have a larger access frequency than the item, which will be evicted</em>.</p><p>1. We want to put a key and a value.</p><p>2. Drive a key through Count Min Sketch table to count the accesses frequency.</p><p>3. Put the item to the head of level 1 cache.</p><p>4. Evict the tail item.</p><p>5. This evicted item could be moved to the level 2 cache:</p><p>5.1 get the evicted (from the level 1 cache) item frequency (look at the Count Min Sketch table)</p><p>5.2 if we add a new element to the level 2 cache, then some element will be evicted from there. So, get the tail (from the probationary segment in the level 2 cache) item frequency.</p><p>5.3 Compare them.</p><p>5.4 If the frequency of the new element is larger than the tail item frequency, replace it. But to the head, of course, it’s still the LRU cache after all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*mCe-dLCDG8-1Y_CbS26MqQ.jpeg" /></figure><p>1. We want to access some key.</p><p>2. Drive it through Count Min Sketch table to count the accesses frequency.</p><p>3. Check it in the level 1 cache and move it to the head if exists.</p><p>3.1 if not — check it in the probationary segment in the level 2 cache.</p><p>3.2 If it exists, move it to the protected segment.</p><p>3.2.1 and move the tail of protected segment back to the head of probationary segment. Just give it one more chance.</p><p>3.3 if not — check it in the protected segment in the level 2 cache and move it to the head if exists.</p><p><strong>Congratulations</strong>! We created the true cache with two levels and with taking into account the access frequencies of the items.</p><h3><strong>Conclusions.</strong></h3><p>Now you know how to implement the different eviction policies of the cache systems, how to make the admission policy and how to take into account the access frequencies of all elements ever requested from the cache.</p><p>You can look at the full code on my <a href="https://github.com/lkSnatch/tutorials/tree/master/cache-eviction">github project</a>.</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c1228e2b4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System design: cache (with java impl)]]></title>
            <link>https://medium.com/@lk.snatch/system-design-cache-with-java-impl-eba29b5739dc?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba29b5739dc</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 20:56:37 GMT</pubDate>
            <atom:updated>2020-03-04T09:02:59.978Z</atom:updated>
            <content:encoded><![CDATA[<p>Is your hardware fluttering in futile attempts to speed up the response with frequently used data from the database to the client? Are you tired of spending money on SSD? It’s time to inject cache into your application!</p><p>Let’s consider how can we design a cache system and implement some options on java.</p><h3><strong>What do you need to know about your data &amp; requests?</strong></h3><p>- <strong><em>validity</em></strong> — how long can you save your data in cache</p><p>- <strong><em>durability</em></strong> — can you lose some data or not</p><p>- <strong><em>size</em></strong></p><p>- <strong><em>read &amp; write frequency</em></strong></p><p>- <strong><em>latency</em></strong></p><p>- <strong><em>availability</em></strong></p><p>- <strong><em>scalability</em></strong></p><p>If you know your data and estimated requests, you can choose best approach for caching and provide <strong><em>high hit rate</em></strong> (when the most required data already in the cache), you know what to do with <strong><em>cache miss</em></strong> (when the data is not found in cache during read or write operation) and can properly set the <strong><em>TTL</em></strong> (<strong><em>time to leave</em></strong> — when the values need to be removed from the cache).</p><h3><strong>Read-Write data policies</strong></h3><p>There are three basic approaches: <strong><em>Write through, Write around </em></strong>and<strong><em> Write back</em></strong>. We will also touch some more options.</p><h3><strong>1.</strong> <strong>Write Through</strong></h3><p>Reading data in all policies happens in the same way:</p><p>1. Send request through the cache to get value.</p><p>2. If we found the value in cache — return it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoH0Em8vhaqfvfb5N7Zllw.jpeg" /></figure><p>3. If not — redirect request to DB.</p><p>4. Obtain actual value from DB.</p><p>5. Write it to the cache.</p><p>6. Return the response with obtained value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*ur2aMrBQSgwMWX5WaKjhjA.jpeg" /></figure><p>The difference in write way.</p><p>When we use write-through variant, we store the data into DB and into cache in parallel (or in order). The significance is that we send response only when the data has been written to both places — DB and cache.</p><p><strong>Pros:</strong> fast read recently written data, data durability.</p><p><strong>Cons:</strong> slow write, cache pollution.</p><p>Write-through cache suitable for most kind of data, which requires data durability and fast read recently used or written data.</p><h3><strong>2.</strong> <strong>Write Around</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*Kdo0p9PZL5Gif92w2hb9yw.jpeg" /></figure><p>Data is written bypassing the cache. It means all requests are sent directly to the DB only and written data does not hit the cache (except of delete/update/invalidate deleting or writing data if you care about cache–DB consistency).</p><p><strong>Pros: </strong>data durability, no cache pollution</p><p><strong>Cons: </strong>slow write (but might be faster than write-through cache), slow read recently written data</p><p>Write-around cache suitable for apps, which don’t need to read recently written data. For example, storing the calls in call-centers: these records are unlikely to be immediately listen.</p><h3><strong>3.</strong> <strong>Write Back</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*I0YUKwl89D9SJ36SNgFacw.jpeg" /></figure><p>Data is written right to the cache and in parallel (or after) it writes into DB. The difference with write-through approach is, in this way, we don’t wait answer from DB. When the data is written into cache, we send the response with record confirmation and recording to DB might continuous in the background.</p><p><strong>Pros: </strong>fast write, fast read recently written data</p><p><strong>Cons:</strong> no data durability, cache pollution</p><p>Use write-back treatment to achieve fast recording. Of course, you should keep in mind that your data might be loss (in situation when something failed and the data was written to the cache but did not have time to write to the database). You can use it for recording some not so important data — metrics, for example.</p><h3><strong>Things to think about</strong></h3><p>There are lot of other approaches and implementations, like:</p><p>- <strong><em>write-invalidate</em></strong> –write-around with invalidating the value in cache, if it present</p><p>- <strong><em>write-update</em></strong> — write-around with updating the value in cache, if it present</p><p>- <strong><em>write-only</em></strong> — like write-back but read operations don’t promote data to cache</p><p>- <strong><em>when to flush dirty pages</em></strong> in write-back — immediately or after checkpoint or only after receiving a new value for recording</p><p>- and so on..</p><h3><strong>Which data structure is most suitable?</strong></h3><p>Any guess? Of course, it’s a <strong><em>hashtable</em></strong>! Because it has O(1) access for both put and get operations (if you have good hash function which provide a uniform distribution of hash values).</p><h3><strong>Eviction policies</strong></h3><p>But hashtable has O(n) space. Therefore we need some eviction policy to remove values from the cache. It could be <em>LRU, MRU, FIFO, LIFO, RR, ARC</em> &amp; etc.</p><p><em>We’ll talk about them </em><a href="https://medium.com/@lk.snatch/system-design-cache-eviction-policies-with-java-impl-37c1228e2b4f"><em>in one of the next articles</em></a><em>.</em></p><h3><strong>How should I handle the requests?</strong></h3><p>It depends on your requirements and requests frequency. The popular approaches are:</p><h3><strong>1.</strong> <strong>Thread per request.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*D_fdy2VTKnJCRYbEnRgvHA.jpeg" /></figure><p>If you haven’t a lot of requests, you can use this variant. It means you create new thread for every new request. It’s easy but <strong>really wasteful</strong> in relation to server resources.</p><h3><strong>2.</strong> <strong>Thread pool.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*cLuUGkK_uEgF52Ob7DhKgA.jpeg" /></figure><p>Like the previous approach you assign thread to every request, but don’t create new one every time, just take existing one from the pool. In this way you save a lot of resources. But <strong>if your system has got a huge amount of requests</strong>, you will be forced to increase the number of threads in pool, and <strong>the</strong> <strong>server will be discouraged</strong>.</p><h3><strong>3.</strong> <strong>Event driven.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGQN3pi891D6remAhZQImw.jpeg" /></figure><p>a. All requests are queued in some event queue</p><p>b. one thread spins forever in event loop</p><p>c. it takes new one request from the queue and pass it to perform by any free thread from the thread pool</p><p>d. then “event loop thread” comes back to the loop for getting new events from the queue</p><p>e. “threads from the thread pool” perform the received task and get the data</p><p>f. put the value to callback function</p><p>g. some thread executes this function and the response is sent back.</p><p>In this option, <strong>you regular the stream of processed data</strong> and will be ready to get the huge amount of requests.</p><h3><strong>How make our system fault-tolerant and persistent?</strong></h3><p>The cache system is stored in RAM for faster IO operations. So, what if the server will be restarted due to a fault? We need to make it persistent and retrieve back all data.</p><h3><strong>1.</strong> <strong>Make snapshots</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*dc4l-Hu0S6f79AIcpGsCEg.jpeg" /></figure><p>You can run asynchronous background service to freeze your data in the cache and make a snapshot using some kind of trigger (regular interval or after a certain number of changes). And then it service will store this snapshot to hard disk as dump file or into DB, for example.</p><p>The <strong>disadvantage</strong> is that you can <strong>restore</strong> your cache to the snapshot version, but <strong>not to the version like right before server restart</strong>.</p><h3><strong>2.</strong> <strong>Log reconstruction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*y6ty6X8FTp2VR6Izfzq-qA.jpeg" /></figure><p>Instead of snapshot, you can log all your operations with the cache (read, write, delete, update). The choice of sync or async logging depends on your system and requirements. You can also apply some kind of queuing here so as not to affect app performance.</p><p>If the server goes down, you will have the log file and all as you should to do — is <strong>reconstruct your last cache version</strong> by executing every instructions in this log file.</p><p>Why do we need to log read operations? It depends on your eviction policy, for example. If you’re caching most readable values, you need counting and logging read operations. Because if you don’t, you will get wrong (not the same) version of cache after reconstruction.</p><h3><strong>3.</strong> <strong>Copy</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*KSWqycei5mVpK-Vv0xWJig.jpeg" /></figure><p>Instead of logging or snapshotting you can try just copy your cache into DB or in some another storage. “Just” — it’s simple to say, but not to do. You can create index by key in the table, but what to do with value? It could be complicated object and it’s hard to organize appropriate table or serialize this value completely.</p><h3><strong>4.</strong> <strong>Combined method (snapshot + log)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhTKUfsapF1lguTj_lPyKA.jpeg" /></figure><p>It is just combine first and second approaches. You are logging all operations and sometimes doing a snapshot. When you did a snapshot, you should clear all instructions in log file until snapshot timestamp. It will <strong>save your space</strong> on the hard drive, <strong>accelerate restore</strong> and <strong>allow get the latest cache version</strong> after failure.</p><h3><strong>And now — what about availability?</strong></h3><p>Let’s suppose we have two nodes with their own hashtable and use consistence hashing in our cache system. What if the server one goes down? Requests will be sent directly to the database. Not cool, is it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*veCR3m62H9kunLlVS3-u0A.jpeg" /></figure><p>We can replicate all data to another one server (mirror). If node one goes down, the client still keeps up the conversation with replica one. This method has better performance for reading data, because the client communicate with both nodes (node and replica) and requests could be distributed between them. But support consistency data between node and its replica is problematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*9YjrMlYNSnz8gd7euI3qYw.jpeg" /></figure><p>In the next approach we can’t send requests to the slave node, the communication occurs between client and master node only. If master falls down, the client will deal with the slave node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*VxaFfnjHQpqXQKc0zAgg0Q.jpeg" /></figure><h3><strong>Let’s implement three basic policies on java</strong></h3><p>Imagine, that we have an application, which stores the cars and the people and connect them together to know car owners. We can just send car number and get info about it and its owner person.</p><p>So, create model classes — the <em>Car</em> (with owner person id):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f94c395d10a5a427ebed0f2e6c0ab7/href">https://medium.com/media/c1f94c395d10a5a427ebed0f2e6c0ab7/href</a></iframe><p>the <em>Person</em> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d71b4214fa1991bed0ab980828c703a0/href">https://medium.com/media/d71b4214fa1991bed0ab980828c703a0/href</a></iframe><p>and the <em>CarOwner</em> (to response with full person info, not just an id from the Car class):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e47cb60749e7f30629f8309ee3d87e/href">https://medium.com/media/70e47cb60749e7f30629f8309ee3d87e/href</a></iframe><p>Create <em>DAO</em> classes for them with “<em>embedded DB</em>” and some methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d429ad1ae76ed31289443bdc696f033/href">https://medium.com/media/2d429ad1ae76ed31289443bdc696f033/href</a></iframe><p>Create <em>services</em> and add the delay to imitate too complicated operation and a worst connection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d6047eac247d14784bac9517f6584d/href">https://medium.com/media/d8d6047eac247d14784bac9517f6584d/href</a></iframe><p>Add delay to the <em>PersonService</em> class in <em>getByName()</em> and <em>getById()</em> methods too.</p><p>Why was the delay inherent only in these methods and not in everyone, which has operation with DB? I’ll explain it further.</p><p>Create <em>controllers</em> for car and person:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2f452a2b0f62e00385483634f701350/href">https://medium.com/media/a2f452a2b0f62e00385483634f701350/href</a></iframe><h3><strong>So, we want to cache two operations:</strong></h3><p>1. get a car and its owner info by car number (read operation)</p><p>2. connect the car and person (write operation)</p><p>Let’s create the <em>CommonController</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a8b4fdaa703e0cd550a4b25413eb424/href">https://medium.com/media/0a8b4fdaa703e0cd550a4b25413eb424/href</a></iframe><p>And <em>CommonService interface</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6bffe8c9d67af2d74652a75c5c5635/href">https://medium.com/media/8b6bffe8c9d67af2d74652a75c5c5635/href</a></iframe><p>then it’s implementation without a cache:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c98ee1ae256fbf14c713dd99e04cad5a/href">https://medium.com/media/c98ee1ae256fbf14c713dd99e04cad5a/href</a></iframe><h4>Get car and its owner info consist of two operations with DB:</h4><p>1. get car by number</p><p>2. get person by id</p><p>Both could be cached if we create a hashMap with key (String carNumber) — value (CarOwner carAndOwnerInfo). That’s why we added the delay to these both operations — to show how cache can improve your application latency. <em>getOwnerByNumber</em> will be completed in four seconds without cache or in zero seconds with it.</p><h4>Set owner to a car consist of three operations with DB:</h4><p>1. get car by number (could be retrieved from the cache)</p><p>2. get person by name (couldn’t)</p><p>3. set owner to a car (could be written to cache firstly with write-around approach)</p><p><em>setOwnerToCar</em> will be completed in six seconds without cache or in four or two seconds with it (depends on write data policy).</p><h3><strong>Finally, let’s create a cache!</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb0f63cdf53b9f1dcd9af08fdba397c/href">https://medium.com/media/ffb0f63cdf53b9f1dcd9af08fdba397c/href</a></iframe><p>Now create every option:</p><h4><strong>1.</strong> <strong>Write-around</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fea5ba3dd401ab3ecdcbea98b835aa34/href">https://medium.com/media/fea5ba3dd401ab3ecdcbea98b835aa34/href</a></iframe><p>To get car &amp; owner we check the value existing in the cache and if it hasn’t we get the value from DB and write it to the cache.</p><p>To set owner we check the car in the cache (for optimization), get person from DB, set owner and then invalidate the cache record.</p><h4><strong>2.</strong> <strong>Write-through</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/098ed83a448fb0bd041b385475493a44/href">https://medium.com/media/098ed83a448fb0bd041b385475493a44/href</a></iframe><p>Get operation is the same.</p><p>Set operation put the new connection between car &amp; person to the DB and then to the cache.</p><h4><strong>3.</strong> <strong>Write-back</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c29582808ae0b7a7741d373323a4d41e/href">https://medium.com/media/c29582808ae0b7a7741d373323a4d41e/href</a></iframe><p>Get operation again the same.</p><p>Set operation uses both optimizations — to get a car from the cache and to set owner firstly in the cache, and only then (after sending a response) write it to DB async.</p><h3><strong>How can we check improvements? Create a test!</strong></h3><p>What we wanna check? Write time.. read time.. and also read after write.. and write after read.. Because each write or read operation may cause cache filling and we can use it for better performance later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/991ef43050d803435fc94db1164c4e51/href">https://medium.com/media/991ef43050d803435fc94db1164c4e51/href</a></iframe><h3><strong>Run the tests. Look at results.</strong></h3><p>Choose the profile in <em>application.properties </em>and run the tests</p><pre><em>mvn test -Dtest=CacheTests</em></pre><p>or in your favorite IDE <strong><em>Idea </em></strong>just click <strong><em>run</em> </strong>inside class <strong><em>CacheTests</em></strong>.</p><p><strong>here is the results:</strong></p><pre>spring.profiles.active=CommonServiceWithoutCache</pre><pre>read time: 24.014894472</pre><pre>write time: 18.0088929550</pre><pre>read after write time: 24.017792753</pre><pre>write after read time: 18.008320701</pre><p><em>Worst execution time, because every operation with DB takes two seconds.</em></p><pre>spring.profiles.active=CacheWriteAroundService</pre><pre>read time: 12.011299223</pre><pre>write time: 18.011621115</pre><pre>read after write time: 12.014920908</pre><pre>write after read time: 12.005370793</pre><p><em>It’s better for read. Write after read operations are faster due to “look up cars in the cache” optimization.</em></p><pre>spring.profiles.active=CacheWriteThroughService</pre><pre>read time: 12.012618517</pre><pre>write time: 18.011820782</pre><pre>read after write time: 0.01078917</pre><pre>write after read time: 12.006140848</pre><p><em>It’s the best execution time for read after write operations, because all recently written data is in the cache (unlike with write-around policy).</em></p><pre>spring.profiles.active=CacheWriteBackService</pre><pre>read time: 12.011902266</pre><pre>write time: 12.011948607</pre><pre>read after write time: 0.01073972</pre><pre>write after read time: 6.005554598</pre><p>This one has the best of the best of the best performance, but you could lost your data, if your server suddenly goes down.</p><h3><strong>Conclusions.</strong></h3><p>Now you know how to implement the cache system, how to do it scalable, fault-tolerance with 100% available, and which write-policy you need to choose for better performance.</p><p>You can look at the full code on my <a href="https://github.com/lkSnatch/tutorials/tree/master/cacheSimple">github project</a>.</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba29b5739dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MSSQL Server Current Queries (Ultimate Script)]]></title>
            <link>https://medium.com/@lk.snatch/mssql-server-current-queries-ultimate-script-f3fd2b08e30b?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3fd2b08e30b</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[mssql-server]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Mon, 27 Jan 2020 12:44:20 GMT</pubDate>
            <atom:updated>2020-02-18T05:10:32.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you wanna know what queries are currently running and firing your CPU or clogging up your memory? Of course, you do!</p><p>Jump for joy! I’ll help you with this <em>Current Queries script (ultimate edition 2.0)</em>. Just run it in your SQL Server Management Studio:</p><pre>WITH XMLNAMESPACES(DEFAULT N’http://schemas.microsoft.com/sqlserver/2004/07/showplan&#39;)</pre><pre>SELECT</pre><pre>  db.name db,</pre><pre>  er.session_id sess_id,</pre><pre>  er.blocking_session_id block_id,</pre><pre>  er.command,</pre><pre>  cast(er.total_elapsed_time / 60000.0 as numeric(15,3)) dur_min,</pre><pre>  er.total_elapsed_time duration,</pre><pre>  DateDiff(MILLISECOND, tat.transaction_begin_time, GETDATE()) tran_duration,</pre><pre>  er.cpu_time cpu,</pre><pre>  ot.context_switches_count cpu_switches,</pre><pre>  er.dop,</pre><pre>  er.parallel_worker_count workers,</pre><pre>  er.reads,</pre><pre>  er.writes,</pre><pre>  er.logical_reads logic,</pre><pre>  er.row_count rows,</pre><pre>  ot.pending_io_count io_count,</pre><pre>  ot.pending_io_byte_count io_byte,</pre><pre>  tdt.log_recs,</pre><pre>  tdt.t_log_recs,</pre><pre>  tdt.log_used,</pre><pre>  tdt.t_log_used,</pre><pre>  tdt.log_reserved,</pre><pre>  tdt.t_log_reserved,</pre><pre>  er.start_time start,</pre><pre>  er.status,</pre><pre>  case er.transaction_isolation_level</pre><pre>    when 1 then ‘ReadUncomitted’</pre><pre>    when 2 then ‘ReadCommitted’</pre><pre>    when 3 then ‘Repeatable’</pre><pre>    when 4 then ‘Serializable’</pre><pre>    when 5 then ‘Snapshot’</pre><pre>    end isolation,</pre><pre>  er.wait_time wait,</pre><pre>  er.wait_type,</pre><pre>  er.last_wait_type,</pre><pre>  er.wait_resource,</pre><pre>  cast(eqmg.query_cost as numeric(20,3)) cost,</pre><pre>  er.granted_query_memory / 128 as granted_memory,</pre><pre>  eqmg.requested_memory_kb / 1024 requested_memory,</pre><pre>  eqmg.used_memory_kb / 1024 cur_used_memory,</pre><pre>  eqmg.max_used_memory_kb / 1024 max_used_memory,</pre><pre>  ISNULL(eqmg.wait_time_ms, CAST(DATEDIFF(MILLISECOND, eqmg.request_time, eqmg.grant_time) AS NUMERIC(15))) wait_memory,</pre><pre>  (tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count) / 128 alloc_tempdb,</pre><pre>  (tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count — tsu.user_objects_dealloc_page_count — tsu.internal_objects_dealloc_page_count) / 128 current_tempdb,</pre><pre>  es.login_name login,</pre><pre>  es.host_name host,</pre><pre>  es.program_name program,</pre><pre>  est.text,</pre><pre>  SUBSTRING(est.text, (statement_start_offset/2)+1,</pre><pre>  ((CASE statement_end_offset</pre><pre>    WHEN -1 THEN DATALENGTH(est.text)</pre><pre>    ELSE statement_end_offset</pre><pre>    END — statement_start_offset)/2) + 1) AS executing_text,</pre><pre>  eqp.query_plan,</pre><pre>  ecp.size_in_bytes / 1024 plan_size_all,</pre><pre>  ecp.usecounts plan_uses,</pre><pre>  ecp.cacheobjtype plan_cachetype,</pre><pre>  ecp.objtype plan_type,</pre><pre>  operators.plan_size as plan_size_kb,</pre><pre>  operators.plan_time as plan_time_ms,</pre><pre>  operators.plan_cpu as plan_cpu_ms,</pre><pre>  operators.plan_memory as plan_memory_kb,</pre><pre>  bes.login_name block_login,</pre><pre>  bes.program_name block_program,</pre><pre>  bes.login_time block_login_time,</pre><pre>  bes.last_request_start_time block_last_request,</pre><pre>  bes.host_name block_host,</pre><pre>  bst.text block_text</pre><pre>FROM sys.dm_exec_requests er</pre><pre>  left join sys.dm_exec_cached_plans ecp</pre><pre>    on er.plan_handle = ecp.plan_handle</pre><pre>  left join (select</pre><pre>    tdt.transaction_id,</pre><pre>    sum(case when tdt.database_id &lt;&gt; 2 then tdt.database_transaction_log_record_count else 0 end) log_recs,</pre><pre>    sum(case when tdt.database_id = 2 then tdt.database_transaction_log_record_count else 0 end) t_log_recs,</pre><pre>    sum(case when tdt.database_id &lt;&gt; 2 then tdt.database_transaction_log_bytes_used / 1024 else 0 end) log_used,</pre><pre>    sum(case when tdt.database_id = 2 then tdt.database_transaction_log_bytes_used / 1024 else 0 end) t_log_used,</pre><pre>    sum(case when tdt.database_id &lt;&gt; 2 then tdt.database_transaction_log_bytes_reserved / 1024 else 0 end) log_reserved,</pre><pre>    sum(case when tdt.database_id = 2 then tdt.database_transaction_log_bytes_reserved / 1024 else 0 end) t_log_reserved</pre><pre>    from sys.dm_tran_database_transactions tdt</pre><pre>    group by transaction_id) tdt</pre><pre>      on er.transaction_id = tdt.transaction_id</pre><pre>  OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) AS est</pre><pre>  OUTER APPLY sys.dm_exec_query_plan(er.plan_handle) AS eqp</pre><pre>  LEFT JOIN sys.databases db</pre><pre>    ON er.database_id = db.database_id</pre><pre>  LEFT JOIN sys.dm_exec_query_memory_grants eqmg</pre><pre>    ON er.session_id = eqmg.session_id</pre><pre>    and er.request_id = eqmg.request_id</pre><pre>    and er.sql_handle = eqmg.sql_handle</pre><pre>  LEFT JOIN sys.dm_db_task_space_usage tsu</pre><pre>    ON er.session_id = tsu.session_id</pre><pre>    and er.request_id = tsu.request_id</pre><pre>    and er.task_address = tsu.task_address</pre><pre>  left join sys.dm_exec_sessions es</pre><pre>    on er.session_id = es.session_id</pre><pre>   -- when DOP != 1 and we wanna see the stat info about whole query instead of separate tasks,</pre><pre>   -- we must do not join by task_address, but group all tasks. Or just kick off this one DMV :)</pre><pre>  left join sys.dm_os_tasks ot</pre><pre>    on er.session_id = ot.session_id</pre><pre>    and er.request_id = ot.request_id</pre><pre>    and er.task_address = ot.task_address</pre><pre>  left join sys.dm_exec_connections bec</pre><pre>  OUTER APPLY sys.dm_exec_sql_text(bec.most_recent_sql_handle) AS bst</pre><pre>    on er.blocking_session_id &gt; 0</pre><pre>    and er.blocking_session_id = bec.most_recent_session_id</pre><pre>  left join sys.dm_exec_sessions bes</pre><pre>    on er.blocking_session_id &gt; 0</pre><pre>    and er.blocking_session_id = bes.session_id</pre><pre>  left JOIN sys.dm_tran_active_transactions AS tat</pre><pre>    on er.transaction_id = tat.transaction_id</pre><pre>  outer APPLY (select</pre><pre>    sum(operators.value(‘@CachedPlanSize’,’numeric(15,0)’)) AS plan_size,</pre><pre>    sum(operators.value(‘@CompileTime’,’numeric(15,0)’)) AS plan_time,</pre><pre>    sum(operators.value(‘@CompileCPU’,’numeric(15,0)’)) AS plan_cpu,</pre><pre>    sum(operators.value(‘@CompileMemory’,’numeric(15,0)’)) AS plan_memory</pre><pre>    from</pre><pre>    eqp.query_plan.nodes(‘//QueryPlan’) rel(operators)) as operators</pre><pre>WHERE not er.status in (‘background’, ‘sleeping’)</pre><pre>  and er.last_wait_type &lt;&gt; ‘SP_SERVER_DIAGNOSTICS_SLEEP’</pre><pre>  --and er.session_id &lt;&gt; @@SPID</pre><pre>ORDER BY</pre><pre>  er.total_elapsed_time DESC</pre><p>Big big query.. Let’s explain some fields:</p><h3><strong>Common:</strong></h3><p>Common info about performing a query — who, when, what, how. It helps you find the guilty user.</p><p><strong><em>db</em></strong> — just a database name</p><p><strong><em>sess_id</em></strong> — ID of the session to which this request is related</p><p><strong><em>command</em></strong> — current type of command, like <em>SELECT, INSERT</em> &amp; etc</p><p><strong><em>start_time</em></strong> — when the query has been started</p><p><strong><em>status</em></strong> — like <em>Sleeping, Running</em> &amp; etc</p><p><strong><em>isolation</em></strong> — transaction isolation level, like <em>ReadCommitted, Serializable</em> &amp; etc</p><p><strong><em>cost</em></strong> — estimated query cost (spherical cat in vacuum, but really hard plans gives high value)</p><p><strong><em>login, host, program</em></strong> — by whom, where and how the request was done</p><h3><strong>Time &amp; CPU:</strong></h3><p>High duration value often indicates a problem. But duration != cpu_time, does not necessarily burn your CPU. For example, your query may be blocked and it doesn’t fire your cores.</p><p><strong><em>duration, dur_min</em></strong> — total time elapsed in milliseconds (or minutes) upon request arrival</p><p><strong><em>tran_duration</em></strong> — duration of active transaction related to this request</p><p><strong><em>cpu</em></strong> — CPU time in milliseconds.</p><p><strong><em>cpu_switches</em></strong> — number of scheduler context switches. If it really high, you should worry</p><p><strong><em>dop</em></strong> — the query degree of parallelism. How many threads may perform this query</p><p><strong><em>workers</em></strong> — the number of reserved parallel workers for this parallel query</p><h3><strong>Input Output:</strong></h3><p>A high reads value may tell us about cache mismatch. High logic value tells us that the query obtains too much data or twists-twirl the same small data chunks in the loops.</p><p><strong><em>reads</em></strong> — number of page reads from disk (you can * 8 and get the size in kilobytes)</p><p><strong><em>writes</em></strong> — number of page writes to disk</p><p><strong><em>logic</em></strong> — number of page reads from cache (this reads perform in the memory)</p><p><strong><em>rows</em></strong> — number of returned rows to the client</p><p><strong><em>io_count</em></strong> — number of physical IO operations for this task</p><p><strong><em>io_byte</em></strong> — total byte count of IO operations (I didn’t see anything other than zero, but I still believe it might be useful someday J )</p><h3><strong>TempDB:</strong></h3><p>How much data your query allocates in tempdb.</p><p><strong><em>alloc_tempdb</em></strong> — size in megabytes reserved or allocated to user and internal objects in tempdb for all the time by this query</p><p><strong><em>current_tempdb</em></strong> — size in megabytes reserved or allocated to user and internal objects in tempdb in this moment by this query</p><h3><strong>Transaction Log:</strong></h3><p>How intensively the query uses the transaction log. High values could cause replica’s delay.</p><p><strong><em>log_recs, t_log_recs</em></strong> — the amount of log records generated in the database (or in the tempdb in particular) for the transaction</p><p><strong><em>log_used, t_log_used</em></strong> — the size in kilobytes used in the transaction log</p><p><strong><em>log_reserved, t_log_reserved</em></strong> — the size in kilobytes reserved in the transaction log</p><h3><strong>Waits:</strong></h3><p>As I have mentioned above, the query may be blocked. This section helps you identify a specific resource and type of waiting.</p><p><strong><em>wait</em></strong> — wait time in milliseconds if the request is currently blocked</p><p><strong><em>wait_type, last_wait_type</em></strong> — type of current or previous wait</p><p><strong><em>wait_resource</em></strong> — which resource this request is waiting</p><h3><strong>Memory:</strong></h3><p>How much each query consumes memory. By default, every query is limited by 25% of total memory. Every high value of granted memory causes cache flushes and forces reading data from disk.</p><p><strong><em>granted_memory</em></strong> — allocated size in the memory (in megabytes)</p><p><strong><em>requested_memory</em></strong> — total requested amount of memory (Mb)</p><p><strong><em>cur_used_memory</em></strong> — physical memory used at this moment (Mb)</p><p><strong><em>max_used_memory</em></strong> — maximum of used memory</p><p><strong><em>wait_memory</em></strong> — how long the request waits for the memory to be granted</p><h3><strong>Query &amp; Plan Text:</strong></h3><p>Some queries may have pretty big plans, they could compile a long time. But it can had a time only at first time (time on time has a time at time.. blaah..), I mean first execution, when the plan is needed to be compiled. And further the same query will perform much faster. Here you can look at plan resources (memory, CPU, compile duration, uses) and spot why the query has ugly execution time.</p><p><strong><em>text, executing_text</em></strong> — query text (full text) and query statement (which piece is currently performing)</p><p><strong><em>query_plan</em></strong> — query plan (thank you, Captain Obvious!)</p><p><strong><em>plan_size_all</em></strong> — number of kilobytes consumed by the cache object (not only plan)</p><p><strong><em>plan_uses</em></strong> — how many times this plan (cache object) has been used (looked up)</p><p><strong><em>plan_cachetype</em></strong> — type of cache object, like <em>Compiled Plan, Extended Proc</em> &amp; etc</p><p><strong><em>plan_type</em></strong> — type of object, like <em>Stored procedure, Prepared statement</em> &amp; etc</p><p><strong><em>plan_size_kb</em></strong> — size of query plan</p><p><strong><em>plan_time_ms</em></strong> — plan compile time</p><p><strong><em>plan_cpu_ms</em></strong> — plan compile CPU time</p><p><strong><em>plan_memory_kb</em></strong> — plan compile memory</p><h3><strong>Blocking query:</strong></h3><p>Information about blocking queries. With info from ‘waits’ section it could help you determine the bad pesky query or session that is being a time hog.</p><p><strong><em>block_id</em></strong> — ID of the guilty session that is blocking this request</p><p><strong><em>block_login, block_host, block_program — </em></strong>by whom, where and how the request is blocked</p><p><strong><em>block_login_time</em></strong> — when the guilty was logged in</p><p><strong><em>block_last_request</em></strong> — timestamp of the last request of the guilty session</p><p><strong><em>block_text</em></strong> — last query text of the guilty connection (be aware — that is not necessarily a guilty query, it’s just the last query of the guilty connection)</p><h3><strong>What about info over the some period?</strong></h3><p>You also can add the fields</p><pre>er.sql_handle,</pre><pre>er.plan_handle,</pre><pre>er.query_hash,</pre><pre>er.query_plan_hash</pre><p>and store your results somewhere (in your favorite database, of course). Then you will be able to group your queries by hashes and see the more resource-intensive ones over the period.</p><h3><strong>Conclusions.</strong></h3><p>Just run the ultimate edition script and feel the power of SQL Server controlling!</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fd2b08e30b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgresql compression]]></title>
            <link>https://medium.com/@lk.snatch/postgresql-compression-854a4647ee43?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/854a4647ee43</guid>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[jsonb]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 06:41:16 GMT</pubDate>
            <atom:updated>2020-01-20T08:20:32.082Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Which options do we have?</strong></p><p>— Auto-<a href="https://www.postgresql.org/docs/current/storage-toast.html">compression TOAST</a>-able data</p><p>— <a href="https://postgrespro.com/docs/enterprise/11/cfs">Postgres Pro compression</a> / encryption</p><p>— <a href="https://github.com/citusdata/cstore_fdw">Cstore_fdw</a> columnar store extension</p><p>— <a href="https://github.com/postgrespro/zson">ZSON</a> extension for jsonb format</p><p>— Compression file systems (like <a href="https://github.com/zfsonlinux/zfs">ZFS</a> or <a href="https://btrfs.wiki.kernel.org/index.php/Compression">Btrfs</a>)</p><p>— <a href="https://docs.timescale.com/latest/using-timescaledb/compression">TimeScaleDB</a> for time-series data</p><p><strong>This article is divided into 4 parts:</strong></p><p>— First (about auto-compression, postgres pro &amp; Cstore_fdw)</p><p>— Second (about ZSON)</p><p>— Third (TimeScaleDB)</p><p>— Fourth (Compression file systems)</p><h3><strong>Postgresql auto-compression</strong></h3><p><strong><em>Briefly</em></strong>: Postgresql hasn’t row- or page-compression, but it can compress values more than 2 kB. The compressor with default strategy works best for attributes of a size between 1K and 1M.</p><p><strong><em>In detail</em></strong>: Postgresql uses <a href="https://www.postgresql.org/docs/current/storage-toast.html">TOAST</a> (The Oversized-Attribute Storage Technique).</p><blockquote>“<em>PostgreSQL uses a fixed page size (commonly 8 kB), and does not allow tuples to span multiple pages. Therefore, it is not possible to store very large field values directly. To overcome this limitation, large field values are compressed and/or broken up into multiple physical rows.</em>” ©</blockquote><p>In simple words, <strong>TOAST is about how your data stores and compresses</strong>.</p><p>The TOAST management code is triggered when a row value is wider than <em>TOAST_TUPLE_THRESHOLD</em> bytes (2 kB by default), and will compress and/or move field values out-of-line until the row value is shorter than <em>TOAST_TUPLE_TARGET</em> bytes (normally 2 kB) or no more gains can be had.</p><p>You can set <em>TOAST_TUPLE_TARGET</em> in storage parameters when creating or altering table:</p><pre><em>ALTER TABLE … SET (toast_tuple_target = N)</em></pre><p>Valid values are between 128 bytes and the (blocksize — header), by default 8160 bytes.</p><p>Also, you can use <em>ALTER COLUMN | TABLE SET STORAGE …</em> to change the strategy or disable toasting on the column entirely. Let’s check the manual for storages description:</p><p>— <strong><em>PLAIN</em></strong> prevents either compression or out-of-line storage; furthermore it disables use of single-byte headers for varlena types. This is the only possible strategy for columns of non-TOAST-able data types.</p><p>— <strong><em>EXTENDED</em></strong> allows both compression and out-of-line storage. This is the default for most TOAST-able data types. Compression will be attempted first, then out-of-line storage if the row is still too big.</p><p>— <strong><em>EXTERNAL</em></strong> allows out-of-line storage but not compression. Use of EXTERNAL will make substring operations on wide text and bytea columns faster (at the penalty of increased storage space) because these operations are optimized to fetch only the required parts of the out-of-line value when it is not compressed.</p><p>— <strong><em>MAIN</em></strong> allows compression but not out-of-line storage. (Actually, out-of-line storage will still be performed for such columns, but only as a last resort when there is no other way to make the row small enough to fit on a page.)</p><p>The compression technique is a fairly simple and very fast member of the LZ family. Let’s see at the ‘<em>pg_lzcompress.c</em>’ source code for more details:</p><pre><em>The compressor with default strategy works best for attributes of a size between 1K and 1M.</em></pre><p>And here is a difference between two included strategies:</p><pre><em>static const PGLZ_Strategy strategy_default_data = {</em></pre><pre><em>   32, /* Data chunks less than 32 bytes are not compressed */</em></pre><pre><em>   INT_MAX, /* No upper limit on what we’ll try to compress */</em></pre><pre><em>   25, /* Require 25% compression rate, or not worth it */</em></pre><pre><em>   1024, /* Give up if no compression in the first 1KB */</em></pre><pre><em>   128, /* Stop history lookup if a match of 128 bytes is found */</em></pre><pre><em>   10 /* Lower good match size by 10% at every loop iteration */</em></pre><pre><em>};</em></pre><pre><em>static const PGLZ_Strategy strategy_always_data = {</em></pre><pre><em>   0, /* Chunks of any size are compressed */</em></pre><pre><em>   INT_MAX,</em></pre><pre><em>   0, /* It’s enough to save one single byte */</em></pre><pre><em>   INT_MAX, /* Never give up early */</em></pre><pre><em>   128, /* Stop history lookup if a match of 128 bytes is found */</em></pre><pre><em>   6 /* Look harder for a good match */</em></pre><pre><em>};</em></pre><h4><strong>What about jsonb?</strong></h4><p>Some time ago jsonb had a problem with the TOAST compression, because the leading portion of the object consisted mostly of a strictly-increasing series of integer offsets. It was fairly incompressible, because the code in pglz_compress() gives up if it’s found nothing compressible in the first first_success_by bytes of a value (this is 1 KB in the default strategy, you can see it above). So, in <a href="https://postgrespro.com/list/thread-id/1849114">this thread</a> guys solved this problem <strong>by changing item offsets to item lengths</strong> and that’s why now the <a href="https://doxygen.postgresql.org/jsonb_8h_source.html#l00119">jsonb header</a> looks like this:</p><pre><em>* JEntry format.</em></pre><pre><em>* The least significant 28 bits store either the data length of the entry, or its end+1 offset from the start of the variable-length portion of the containing object. The next three bits store the type of the entry, and the high-order bit tells whether the least significant bits store a length or an offset.</em></pre><pre><em>* The reason for the offset-or-length complication is to compromise between access speed and data compressibility. In the initial design each JEntry always stored an offset, but this resulted in JEntry arrays with horrible compressibility properties, so that TOAST compression of a JSONB did not work well. Storing only lengths would greatly improve compressibility, but it makes random access into large arrays expensive (O(N) not O(1)).</em></pre><pre><em>* So what we do is store an offset in every JB_OFFSET_STRIDE’th JEntry and a length in the rest. This results in reasonably compressible data (as long as the stride isn’t too small). We may have to examine as many as JB_OFFSET_STRIDE JEntrys in order to find out the offset or length of any given item, but that’s still O(1) no matter how large the container is.</em></pre><h4><strong>Conclusion</strong>:</h4><p>Postgresql has normal balanced default auto-compression, but it’s not always enough.</p><h3><strong>Postgres Pro Compression</strong></h3><p>You can find official info about compression on database level <a href="https://postgrespro.com/docs/enterprise/11/cfs">here</a>.</p><p>Postgres Pro brings the <em>page-compression</em> to postgresql world and uses <em>zstd (from Facebook with love)</em> compression library on Linux and <em>zlib</em> on Windows. Developers claim that their implementation can reduce database size from 2 to 5 times.</p><p>To use compression you need to create a tablespace:</p><pre><em>postgres=# create tablespace compressed_tables location ‘/var/data/cfs’ with (compression=true);</em></pre><p>Compressed once the tablespace can’t be decompressed. And also you can’t compress tablespace which was created earlier.</p><h3><strong>Cstore_fdw compression</strong></h3><p>You also can look at <a href="https://github.com/citusdata/cstore_fdw">cstore_fdw</a> — is an open source columnar store extension for PostgreSQL. it may compress data 6x-10x (according to the <a href="https://www.citusdata.com/">developers</a>).</p><p>But anyway I didn’t try it, because it has some restrictions, like:</p><blockquote><em>“We currently don’t support updating table using DELETE, and UPDATE commands. We also don’t support single row inserts”</em></blockquote><p>So, I leave to try it to you.</p><h3><strong>Common conclusion.</strong></h3><p>As I said above, Postgresql has normal balanced default auto-compression, but it’s not always enough. If you have large tables with many rows and many columns, where each value does not exceed 2 KB, you may face a storage problem, because your data won’t be auto-compressed.</p><p>In the next articles we’ll consider the rest of compression options.</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium</a> or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=854a4647ee43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jar file as Ubuntu service]]></title>
            <link>https://medium.com/@lk.snatch/jar-file-as-ubuntu-service-302ec3e1d656?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/302ec3e1d656</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jar]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 17:28:47 GMT</pubDate>
            <atom:updated>2020-01-20T07:13:00.969Z</atom:updated>
            <content:encoded><![CDATA[<p>To create custom service you need to know a little about <em>systemd</em>.</p><p><strong>systemd</strong> — is a suite of basic utilities for Linux. It provides system and service manager runs with PID 1 and starts the rest part of the OS. Systemd manages services, runs daemons, maintain mounting, rules system configuration, logs, monitors incoming users, launching containers and virtual machines &amp; etc.</p><p>Since the 8th version of Debian <em>systemd</em> is used by default instead of <em>init.d</em>, which uses <em>unit</em>-files from the <em>/etc/systemd/system </em>directory, instead of the scripts from <em>/etc/init.d/</em>, respectively.</p><p><strong>systemctl</strong> — the general command to control and monitor <em>systemd </em>state. It’ll help us to launch custom services.</p><h3><strong>1)</strong> <strong>Systemctl in a nutshell.</strong></h3><p>Only regarding the service launch, because it has much more possibilities.</p><p><strong>Display a list of services</strong> ( — no-legend — without header and descriptions; — all — not only active):</p><pre># systemctl list-units -t service — all</pre><pre>…</pre><pre>nfs-server.service loaded active exited NFS server and services</pre><pre>nfs-utils.service loaded inactive dead NFS server and client serv</pre><pre>nmbd.service loaded active running Samba NMB Daemon</pre><pre>oem-config.service not-found inactive dead oem-config.service</pre><pre>…</pre><p>Units can be both services (.services) and mount points (.mount), devices (.device) or sockets (.socket).</p><p>If you need<strong> only failed services</strong>:</p><pre># systemctl — failed</pre><p><strong>Info about service</strong>:</p><pre># systemctl status smbd</pre><pre>● smbd.service — Samba SMB Daemon</pre><pre>Loaded: loaded (/lib/systemd/system/smbd.service; enabled; vendor preset: enabled)</pre><pre>Active: active (running) since Wed 2019–07–10 12:09:29 MSK; 1 months 2 days ago</pre><pre>Docs: man:smbd(8)</pre><pre>man:samba(7)</pre><pre>man:smb.conf(5)</pre><pre>Main PID: 1427 (smbd)</pre><pre>Status: “smbd: ready to serve connections…”</pre><pre>Tasks: 3 (limit: 11859)</pre><pre>CGroup: /system.slice/smbd.service</pre><pre>├─ 1427 /usr/sbin/smbd — foreground — no-process-group</pre><pre>├─14490 /usr/sbin/smbd — foreground — no-process-group</pre><pre>└─81236 /usr/sbin/smbd — foreground — no-process-group</pre><pre>Aug 09 07:18:55 snatch-ub smbd[81233]: pam_unix(samba:session): session closed for user nobody</pre><pre>Aug 12 14:29:57 snatch-ub smbd[65625]: pam_unix(samba:session): session closed for user nobody</pre><p>If the unit is not specified, then it’s considered .<em>service</em>, in this case — <em>smbd</em>.<em>service</em>; also mount points convert from /<em>home</em> to <em>home</em>.<em>mount</em>, and device names to .device units: <em>/dev/sda2 to dev-sda2.device</em>. When the status is displayed, all launched by the service processes are listed and the last part of the log is displayed.</p><p>View <strong>user services and dependent processes</strong>:</p><pre># systemctl status user@1000 | grep ‘java’</pre><pre>│ ├─102468 java -Xmx400m -jar mssqlCont-1.0-SNAPSHOT.jar mssql_cont server-b1</pre><pre>│ ├─102950 java -Xmx400m -jar mssqlCont-1.0-SNAPSHOT.jar mssql_cont server-b2</pre><pre>│ ├─124706 java -Xmx500m -jar writer-1.0-SNAPSHOT.jar writer postgres</pre><p>If the unit name contain the <em>@ </em>symbol<em>,</em> then it’s an instance of a unit-template. For example, <em>user@1000.service</em> — an instance of <a href="mailto:user@.service"><em>user@.service</em></a><em> </em>template. Instances are distinguish by identifiers after @.</p><p>You may need to <strong>reload <em>systemd </em>settings</strong> after service creating:</p><pre># systemctl daemon-reload</pre><p>Also <strong>add service to system start</strong>:</p><pre># systemctl enable my_amazing</pre><p><strong>Launch the service</strong>:</p><pre># systemctl start my_amazing</pre><p>And <strong>stop it</strong>:</p><pre># systemctl stop my_amazing</pre><h3><strong>2)</strong> <strong>Creating a service.</strong></h3><h4><strong>A) Where?</strong></h4><p>First you need to create a service description file. Where to do it? Let’s see <strong>where the units are loaded from</strong>:</p><pre># systemctl show — property=UnitPath</pre><pre>UnitPath=/etc/systemd/system.control /run/systemd/system.control /run/systemd/transient /etc/systemd/system /run/systemd/system /run/system</pre><p>Put to the priority folder <em>/etc/systemd/system</em>.</p><h4><strong>B) How?</strong></h4><p>You can see existing service example like this:</p><pre># systemctl cat sshd</pre><p>In general, we have<strong> two options</strong> at least:</p><p>- <strong>Launch Java directly</strong> (don’t need any additional scripts)</p><p>- <strong>Launch script</strong>, which launch Java (you can describe additional actions in script)</p><h4><strong>B.0) Create a file</strong></h4><pre># sudo nano /etc/systemd/system/my_amazing.service</pre><h4><strong>B.1) Launch java directly</strong></h4><pre>[Unit]</pre><pre>Description = Java Test Service</pre><pre>Wants=network-online.target</pre><pre>After=network-online.target</pre><pre>[Service]</pre><pre>WorkingDirectory=/home/snatchub/Documents/Share/jar as service test</pre><pre>ExecStart=’/home/snatchub/Documents/Share/jar as service test/javaPlatform/bin/java’ -Xmx100M -jar os-service-1.0-SNAPSHOT.jar ‘amazing’ prod</pre><pre>SuccessExitStatus=143</pre><pre>TimeoutStopSec=10</pre><pre>Restart=always</pre><pre>RestartSec=5</pre><pre>[Install]</pre><pre>WantedBy=multi-user.target</pre><h4><strong>B.2) Launch sh-script</strong></h4><pre>[Unit]</pre><pre>Description = Java Test Service</pre><pre>Wants=network-online.target</pre><pre>After=network-online.target</pre><pre>[Service]</pre><pre>Type=forking</pre><pre>WorkingDirectory=/home/snatchub/Documents/Share/jar as service test</pre><pre>ExecStart=’/home/snatchub/Documents/Share/jar as service test/amazing.sh’</pre><pre>PIDFile=/tmp/my_amazing-pid</pre><pre>SuccessExitStatus=143</pre><pre>TimeoutStopSec=10</pre><pre>Restart=always</pre><pre>RestartSec=5</pre><pre>[Install]</pre><pre>WantedBy=multi-user.target</pre><p><strong>And the script itself:</strong></p><pre>#!/bin/sh</pre><pre># ‘/home/snatchub/Documents/Share/jar as service test/javaPlatform/bin/java’ -Xmx100M -jar os-service-1.0-SNAPSHOT.jar ‘amazing’ prod</pre><pre>SERVICE_NAME=my_amazing</pre><pre>PATH_TO_JAVA=”/home/snatchub/Documents/Share/jar as service test/javaPlatform/bin/java”</pre><pre>JVM_PARAMS=-Xmx100M</pre><pre>PATH_TO_JAR=os-service-1.0-SNAPSHOT.jar</pre><pre>APP_PARAMS=’”amazing” prod’</pre><pre>PID_PATH_NAME=/tmp/my_amazing-pid</pre><pre>echo “Starting $SERVICE_NAME ..”</pre><pre>if [ ! -f $PID_PATH_NAME ]; then</pre><pre>echo “$SERVICE_NAME tryna start..”</pre><pre>nohup “$PATH_TO_JAVA” $JVM_PARAMS -jar $PATH_TO_JAR $APP_PARAMS &gt;&gt; amazing.out 2&gt;&amp;1 &amp;</pre><pre>echo “$SERVICE_NAME started. Writing a PID..”</pre><pre>echo $! &gt; $PID_PATH_NAME</pre><pre>echo “$SERVICE_NAME PID has been written.”</pre><pre>else</pre><pre>echo “$SERVICE_NAME is already running..”</pre><pre>PID=$(cat $PID_PATH_NAME);</pre><pre>echo “$SERVICE_NAME with PID = $PID stopping..”</pre><pre>kill $PID;</pre><pre>echo “$SERVICE_NAME with PID = $PID stopped..”</pre><pre>rm $PID_PATH_NAME;</pre><pre>echo “file $PID_PATH_NAME was deleted”</pre><pre>fi</pre><h4><strong>B.3) What is what?</strong></h4><p>Some of the lines are intuitive, but some are not very. Let’s analyze them (and a little of what else can be specified in the service file):</p><p><strong>Service:</strong></p><p><em>[Unit]</em></p><p># just description</p><p><em>Description = Java Test Service</em></p><p># Service dependence on the network connection (or any other service):</p><p># if dependency is necessary</p><p><em>Requires=network-online.target</em></p><p># if dependency is optional (mutually exclusive with ‘requires’)</p><p><em>Wants=network-online.target</em></p><p># if you need to run service only after connecting to the network. If not specified, the service can be started in parallel with the raising of the network (or any other specified service)</p><p><em>After=network-online.target</em></p><p><em>[Service]</em></p><p># <em>Type</em> — <em>simple</em> by default — start-up cmd and receiving an answer from it about its successful launch.</p><p># <em>exec</em> — start-up cmd and receiving a response about the final application successful launch.</p><p># <em>forking</em> — waits for the specified service to make a fork() from the main process, then waits for main process completion and starts following up units.</p><p><em>(it’ll be extra explained further in the section «nuances»)</em></p><p><em>Type=forking</em></p><p># user under which to run the application</p><p><em>User=snatchub</em></p><p># your application working directory. I.e. the app will start the path to external files from this folder (in some cases).</p><p><em>WorkingDirectory=/home/snatchub/Documents/Share/jar as service test</em></p><p># path to executable file — either java with parameters, or a script that launches your application.</p><p><em>ExecStart=/home/snatchub/Documents/Share/jar as service test/my_amazing.sh</em></p><p># script run by the «Stop» command. If not specified, the SIGTERM will be send.</p><p><em>ExecStop = /home/snatchub/Documents/Share/jar as service test/my_amazing.sh stop</em></p><p># restart script</p><p><em>ExecReload = /home/snatchub/Documents/Share/jar as service test/my_amazing.sh reload</em></p><p># Path to service PID file (the application process ID is written there). Needed to track the main process.</p><p># Service manager doesn’t write to this file, only reads the pid from there, and delete the file after the application is finished.</p><p><em>PIDFile=/tmp/my_amazing-pid</em></p><p># This is an additional «success» application shutdown status.</p><p>(<em>it’ll be extra explained further in the section «nuances»</em>)</p><p><em>SuccessExitStatus=143</em></p><p># If specified, that the service manager waits this time for end of the <em>ExecStop </em>command execution, and then sends <em>SIGTERM</em> signal (if it hasn’t stopped yet). Then waits specified time again for end of app. If our app is very lively and timeout has reached, service manager sends <em>SIGKILL</em>.</p><p><em>TimeoutStopSec=10</em></p><p># <em>on-failure</em> — restart application if it fails (Unclean exit code, Unclean signal, Timeout, Watchdog).</p><p># you can specify <em>always</em>, if the app should always be running. This doesn’t apply to the “<em>systemctl stop</em>” command.</p><p>(<em>it’ll be extra explained further in the section «nuances»</em>)</p><p><em>Restart=always</em></p><p># How long service manager need to wait before restart your app. It has 100ms value by default.</p><p><em>RestartSec=5</em></p><p># the service need to call <em>sd_notify(3)</em> regularly with “<em>WATCHDOG=1</em>” (think about it like “<em>keep-alive ping</em>”).</p><p># if the duration between two calls is larger than the configured time, then the service is considered «failed» and it’ll be terminated with <em>SIGABRT</em> (or the signal specified by «<em>WatchdogSignal</em>»).</p><p><em>WatchdogSec=1</em></p><p># has <em>control-group </em>by default, it means all remaining processes in the control group of this unit will be killed on service stop (after script execution, which specified in «<em>ExecStop» </em>command).</p><p># if set to «<em>process</em>», only main process will be killed.</p><p><em>KillMode=process</em></p><p><em>[Install]</em></p><p># Run level. <em>multi-user.target</em> corresponds to the <em>runlevel3</em> and means, that the service will be started before raising the graphical shell, but when users can already log-in through the terminal.</p><p><em>WantedBy=multi-user.target</em></p><p><strong>Script:</strong></p><p><em>Briefly</em>: if the pid file does not exist, then start java process and write its PID to file, else kill the process by PID from file and delete the file.</p><p><em>In detail</em>:</p><p>if [ ! -f $PID_PATH_NAME ]; then</p><p><em>-f</em> — true, if file exists and is a regular file.</p><p>nohup “$PATH_TO_JAVA” $JVM_PARAMS -jar $PATH_TO_JAR $APP_PARAMS &gt;&gt; amazing.out 2&gt;&amp;1 &amp;</p><p><em>nohup</em> — utility, that runs specified command with ignoring communication loss signals (SIGHUP). I.e. the command will continue to run in the background even after the user logs out.</p><p>The <em>&amp;</em> sign in the end means start java-app as daemon, i.e. the script won’t wait the end of java app and will go further according to its commands.</p><p><em>2&gt;&amp;1</em> means stderr(2) redirect (&gt;) to stdout(&amp;1). The &amp; in this case indicates follows 1 as file descriptor and not a file name.</p><p><em>&gt;&gt; amazing.out</em> — redirect streams to file.</p><p><em>“</em><em>!</em> — Expands to the process ID of the most recently executed background (asynchronous) command.” (с) man bash</p><p>From this never-ornate phrase, we make the thoughtful conclusion that <em>$!</em> contains the process ID.</p><p><em>2&gt;/dev/null</em> — redirect error stream to nowhere. Just suppress warnings.</p><h4><strong>B.4) Nuances.</strong></h4><h4><strong><em>SuccessExitStatus=143</em></strong></h4><p>As I mentioned — this is an additional «success» app shutdown status, which determines whether your application will restart or not in case of an error (if set <em>Restart=on-failure or always</em>).</p><p>When we stop the service by «<em>systemctl stop</em>», a SIGTERM signal is sent with the application exit code 15, which is considered successful by default. But java exits with code 143 instead of 15, therefore we need to tell Ubuntu that our code 143 should also be considered successful.</p><p>if you don’t add this success status, you’ll see “<em>failed</em>” service status instead of “<em>inactive</em>” when try to stop service by «<em>systemctl stop</em>». Like the app terminated by error and will be restarted instead of stopping, if you set <em>Restart</em> parameter.</p><p><strong>Why 143?</strong> Because the Posix specification “The exit status of a command that terminated because it received a signal shall be reported as greater than 128”.</p><p>Java decided to follow specification and therefore 143–128 = 15 — this is a SIGTERM signal.</p><h4><strong><em>Type = forking</em></strong></h4><p>If you start java app directly with type «forking», you’ll see such picture in the service status:</p><pre>Active: activating (start) since Tue 2019–08–27 06:58:04 MSK; 59s ago</pre><p>After 1,5 minutes the service will fall off in a timeout and try to restart application, but again unsuccessfully. Java cannot fork. So, if your service call java directly, set the «<em>Type=simple</em>» explicitly or remove this section.</p><p>If your service launches .sh-script and type sets to <em>forking, </em>you’ll see:</p><pre># systemctl status my_amazing.service</pre><pre>● my_amazing.service — Java Test Service</pre><pre>Loaded: loaded (/etc/systemd/system/my_amazing.service; disabled; vendor preset: enabled)</pre><pre>Active: active (running) since Tue 2019–08–27 07:05:57 MSK; 30s ago</pre><pre>Process: 40703 ExecStart=/home/snatchub/Documents/Share/jar as service test/amazing.sh (code=exited, status=0/SUCCESS)</pre><pre>Main PID: 40710 (java)</pre><pre>Tasks: 19 (limit: 11859)</pre><pre>CGroup: /system.slice/my_amazing.service</pre><pre>└─40710 /home/snatchub/Documents/Share/jar as service test/javaPlatform/bin/java -Xmx100M -jar os-service-1.0-SNAPSHOT.jar “amazing” prod</pre><p>The script has completed successfully but java continues to work and can be stopped by the service manager.</p><p>if <em>Type=simple:</em></p><pre>● my_amazing.service — Java Test Service</pre><pre>Loaded: loaded (/etc/systemd/system/my_amazing.service; disabled; vendor preset: enabled)</pre><pre>Active: inactive (dead)</pre><p>The main process is dead and java don’t work in the background.</p><p><strong><em>Conclusions</em></strong><em>:</em></p><p>If <em>type=simple</em>, then the service must launch java app directly or through .sh-script, which one need to work and wait for java app to finish (i.e. don’t run it as a daemon).</p><p>If <em>type=forking</em>, the service must run .sh-script, which may end right after launching the java app (i.e. java app can be started as a daemon).</p><h4><strong><em>Stop and restart java application by exception.</em></strong></h4><p>Let’s imitate the exception in the user-thread (not daemon) and see if the service restarts (<em>code example on github</em>). If you throw an exception right in the <em>main-thread</em>, then everything works as it should: the app returns error status and restarts. But the <em>main-thread</em> generally ends its life quickly upon exiting the method <em>main(String[] args)</em>, and the application lives further on other user-threads. Let’s create another separate user-thread and throw an exception there. Op-pa, the application ends, but successfully instead of an error! Accordingly, it won’t be restarted with «<em>Restart=on-failure</em>». And we’ll see this exception in the service log, if we don’t have a common «<em>uncaught exception handler</em>»:</p><pre>Aug 19 15:55:16 snatch-ub systemd[1]: Started Java Test Service.</pre><pre>Aug 19 15:55:27 snatch-ub java[103930]: Exception in thread “Thread-0” java.lang.RuntimeException: stop working! need a rest..</pre><pre>Aug 19 15:55:27 snatch-ub java[103930]: at net.snatchTech.osService.App.lambda$main$2(App.java:86)</pre><pre>Aug 19 15:55:27 snatch-ub java[103930]: at java.base/java.lang.Thread.run(Thread.java:834)</pre><p><em>Why is this happening?</em></p><p>Because java returns only main-thread end status and ignores other user-threads end statuses.</p><p><em>What to do?</em></p><p>If your application should always work, then you can set «<em>Restart=always</em>». Otherwise, consider using «<em>Thread.setDefaultUncaughtExceptionHandler()</em>» with error logging and «<em>System.exit(1)</em>» inside this handler.</p><h3><strong>C) Errors.</strong></h3><h4><strong>C.1) How to watch?</strong></h4><p>Don’t forget to check service status after starting, there could be problems:</p><pre># systemctl status my_amazing</pre><pre>● my_amazing.service — Java Test Service</pre><pre>Loaded: loaded (/etc/systemd/system/my_amazing.service; disabled; vendor preset: enabled)</pre><pre>Active: activating (auto-restart) (Result: exit-code) since Mon 2019–08–19 10:06:28 MSK; 1s ago</pre><pre>Process: 64855 ExecStart=/javaPlatform/bin/java -Xmx100M -jar mainTutorial.jar amazing prod (code=exited, status=203/EXEC)</pre><pre>Main PID: 64855 (code=exited, status=203/EXEC)</pre><pre>Aug 19 10:06:28 snatch-ub systemd[1]: my_amazing.service: Main process exited, code=exited, status=203/EXEC</pre><pre>Aug 19 10:06:28 snatch-ub systemd[1]: my_amazing.service: Failed with result ‘exit-code’.</pre><p>In this case, stop the service (so that it doesn’t restart) and look again at the status and the last lines of the service log:</p><pre># systemctl status my_amazing</pre><pre>● my_amazing.service — Java Test Service</pre><pre>Loaded: loaded (/etc/systemd/system/my_amazing.service; disabled; vendor preset: enabled)</pre><pre>Active: inactive (dead)</pre><pre>Aug 19 10:07:17 snatch-ub systemd[1]: Stopped Java Test Service.</pre><pre>Aug 19 10:07:17 snatch-ub systemd[1]: /etc/systemd/system/my_amazing.service:3: Unknown lvalue ‘After network.target’ in sectio</pre><p>A more complete log can be viewed using the command:</p><pre># journalctl -u my_amazing.service</pre><pre> — Logs begin at Thu 2019–04–04 21:49:12 MSK, end at Mon 2019–08–19 13:22:56 MSK. — </pre><pre>Aug 19 10:00:29 snatch-ub systemd[1]: /etc/systemd/system/my_amazing.service:3: Missing ‘=’.</pre><pre>Aug 19 10:04:41 snatch-ub systemd[1]: /etc/systemd/system/my_amazing.service:3: Unknown lvalue ‘After network.target’ in section ‘Unit’</pre><p>We can tail the live log using the -f option:</p><pre># journalctl -f -u my_amazing</pre><h4><strong>C.2) Quotes!</strong></h4><p>It is worth not to forget about the equal sign and not mess with quotes if you have spaces in the paths. Somewhere the quotes are needed (in the <em>exec </em>section), somewhere not (in the <em>working directory</em>). Otherwise, you have a risk to encounter a bunch of errors, like:</p><pre>/etc/systemd/system/my_amazing.service:3: Missing ‘=’.</pre><pre>my_amazing.service: Failed at step EXEC spawning /javaPlatform/bin/java: No such file</pre><pre>Working directory path ‘’/home/snatchub/Documents/Share/jar as service test’’ is not absolute.</pre><pre>Executable path is not absolute: $WorkingDirectory/javaPlatform/bin/java -Xmx100M -jar mainTutorial.jar</pre><pre>Failed at step EXEC spawning /home/snatchub/Documents/Share/jar: No such file or directory”</pre><h4><strong>C.3) Access rights.</strong></h4><p>Don’t forget to add rights to run the script.</p><pre>chmod u+x amazing.sh</pre><p>u means which users’ access to the file will be changed: in this case the user who owns it.</p><p>The operator + causes the selected file mode bits to be added to the existing file mode bits. I.e. it adds the rights instead of re-writes them.</p><p>x — right itself: execute (or search for directories)</p><p>Otherwise, you’ll see:</p><pre>my_amazing.service: Failed at step EXEC spawning /home/snatchub/Documents/Share/jar as service test/amazing.sh: Permission denied</pre><p><em>Wrong user</em>:</p><pre>Aug 22 15:00:50 snatch-ub systemd[61054]: my_amazing.service: Failed to determine user credentials: No such process</pre><pre>Aug 22 15:00:50 snatch-ub systemd[61054]: my_amazing.service: Failed at step USER spawning</pre><p>If we’ve given permissions to script, but haven’t given to directory with logs and resources:</p><pre>Aug 22 15:07:43 snatch-ub amazing.sh[61869]: Can’t load log handler “java.util.logging.FileHandler”</pre><pre>Aug 22 15:07:43 snatch-ub amazing.sh[61869]: java.nio.file.AccessDeniedException: service_0_0.log.lck</pre><p>Check service restart by error:</p><pre>Aug 19 10:06:23 snatch-ub systemd[1]: Started Java Test Service.</pre><pre>Aug 19 10:06:23 snatch-ub systemd[64837]: my_amazing.service: Failed to execute command: No such file or directory</pre><pre>Aug 19 10:06:23 snatch-ub systemd[1]: my_amazing.service: Main process exited, code=exited, status=203/EXEC</pre><pre>Aug 19 10:06:28 snatch-ub systemd[1]: my_amazing.service: Service hold-off time over, scheduling restart.</pre><pre>Aug 19 10:06:28 snatch-ub systemd[1]: my_amazing.service: Scheduled restart job, restart counter is at 1.</pre><p>It can be seen that the service crashed by error and restarted after 5 seconds.</p><h3><strong>Common conclusion.</strong></h3><p>The built-in tools in Ubuntu are enough to run jar as services, use systemctl and enjoy uptime!</p><p>Code examples are on <a href="https://github.com/lkSnatch/tutorials/tree/master/jar-as-os-service">github</a></p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium </a>or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch"><em>Twitter</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=302ec3e1d656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jar file as windows service (+bonus jar to exe)]]></title>
            <link>https://medium.com/@lk.snatch/jar-file-as-windows-service-bonus-jar-to-exe-1b7b179053e4?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b7b179053e4</guid>
            <category><![CDATA[exe]]></category>
            <category><![CDATA[jar]]></category>
            <category><![CDATA[windows-services]]></category>
            <category><![CDATA[nssm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Thu, 22 Aug 2019 10:30:03 GMT</pubDate>
            <atom:updated>2020-07-28T13:04:31.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jar file as Windows service (+bonus jar to exe)</h3><p>So, your project has lived up to production and you’d like to start it with the OS and you don’t manually rise it every time. But how do we do that with a regular jar-file?</p><p><strong>There are a bunch of options:</strong></p><p><strong>I)</strong> <strong>Put the bat-file</strong> with java –jar launch or exe-file <strong>in Windows startup</strong> (after making an exe file from jar).</p><pre>Windows 7 : C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)</pre><pre>Windows 10 : In Run shell:startup</pre><p>This will solve the problem, but your app will start in the best case only with the first login of any user (if you throw bat into startup for all users). But, as you know, a good admin doesn’t walk on the server.</p><p><strong>II)</strong> <strong>Make the Windows task</strong>, starting the bat-file at system startup.</p><p>This option perfectly solves startup problem, but the manipulation with the app ends here, neither start-stop at any time, nor restart due to errors.</p><p><strong>III)</strong> <strong>Run jar as win service with </strong><a href="https://support.microsoft.com/en-us/help/251192/how-to-create-a-windows-service-by-using-sc-exe"><strong>sc.exe</strong></a><strong> </strong>(there is still <em>Srvinstw.exe</em> — GUI version, but we are true-programmers and must use the command-line).</p><p>This is a little program from the Resource Kit for creating services from exe-files.</p><p><em>But we have a jar-file, right?!</em> No problem! There are options to try:</p><p><strong>1)</strong> Run java.exe -jar with parameters directly.</p><p><strong>2)</strong> make exe-file from jar and turn it into a service.</p><p><strong>3)</strong> Use <em>srvany.exe</em></p><p><strong>a)</strong> run java.exe –jar from it</p><p><strong>b)</strong> write bat-file with launch java -jar and run it from <em>srvany</em>.</p><p><strong>IV)</strong> <strong>Use third-party software.</strong></p><p>Let’s rake this pile of options, skipping the first two as the least interesting.</p><h3>0) Application</h3><p>First, we’ll write a small application with blackjack and resources, depending on passed parameters, in order to feel maximum pain in the agony of trying to make it work as a service.</p><p>The app will:</p><p>- swear that there are no parameters</p><p>- read certain setting files depending on the passed parameters</p><p>- parse these settings by an external library</p><p>- pour the same settings in the log every 5 seconds</p><p>An app example can be found here:</p><p><a href="https://github.com/lkSnatch/tutorials/tree/master/jar-as-os-service">https://github.com/lkSnatch/tutorials/tree/master/jar-as-os-service</a></p><p>My result will be the <strong>executable jar-file</strong>, with dependent libraries and resources outside in the separate folder. You can do whatever you want, experiment.</p><h3>1) Start the service with sc.exe</h3><p>Well, to read sc help, just enter:</p><pre>sc –bla_bla</pre><p>The result will be «Error. Unidentified command» and further help on possible commands.</p><h4>A) Create the service with java.exe –jar</h4><pre>sc create TestServ4 binPath= “E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe -Xmx400m -jar E:\Java\JavaPrograms\test\withoutSpaces\mainTutorial-1.0-SNAPSHOT.jar amazing prod” type= own start= auto error= normal DisplayName= TestService4</pre><p>I have a jdk dragging around the app, not to depend on versions in the servers and to give my program solidity of a large size. The full path to java.exe is not necessary if it’s in the environment variables. It’s worth noting one annoying and unobtrusive peculiarity: «binPath= » — after any parameter (here is a binPath) immediately comes the <em>equal sign</em>, and then between it and the parameter value a <em>space </em>is required.</p><p>Great, the service is created, run it! Oops..:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*HML7CYdimDVs_HAFvTbReQ.png" /><figcaption>(Windows could not start the TestService6 service on Local Computer. Error 1053: the service did not respond to the start or control request in a timely fashion.)</figcaption></figure><p>(<em>My TestService will have different numbers in the examples, because the service wasn’t always deleted immediately, sometimes it was just marked for deletion</em>)</p><p>Just in case, let’s look if the app log has appeared. But it has! Only a tiny one, containing info from the moment of trying to start the service up until the moment of issuing the error. What happened? Here’s what:</p><p>- service started launching java.exe with the required parameters</p><p>- our app started its work</p><p>- Windows service manager waited some time for a response from java.exe about it successful (or not) launch</p><p>- but java.exe returned nothing, because it owes nothing to anyone</p><p>- service manager counted down the timeout in seconds and shot off java</p><p><strong>Conclusion</strong>: not every exe-file is equally useful to run as a service. <em>One does not simply run any exe-file as a service</em>, it must be specially sharpened for Windows service (at least return some data about it launch).</p><p>Or maybe try <em>javaw</em>? Try it, but <em>double-V</em> in the name doesn’t mean double victory.</p><h4>B) Create the service with cmd /c java.exe -jar</h4><p>What if you run <em>cmd </em>in cmd in cmd and in it run java? Will the whole chain close? Let’s start small — run only java from the cmd, and specify cmd as <em>binpath </em>at service start:</p><pre>sc create TestServ3 binPath= “cmd /c E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe -Xmx400m -jar E:\Java\JavaPrograms\test\withoutSpaces\mainTutorial-1.0-SNAPSHOT.jar amazing prod” type= own start= auto error= normal DisplayName= TestService3</pre><p>Likewise, it falls off after the timeout. But only the cmd process ends its worthless life, and our mega java app continues to breathe and delight.</p><p>It works? Yes! As a full service? No toothing way!</p><p>But put our jar-file in a folder with spaces to (“escape”) enjoy the creation of inclined sticks next to quotes a little more:</p><pre>sc create TestServ6 binPath= “cmd /c E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe -Xmx400m -jar \”E:\Java\JavaPrograms\test\with Spaces\mainTutorial-1.0-SNAPSHOT.jar\” amazing prod” type= own start= auto error= normal DisplayName= TestService6</pre><p>Look at the registry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53RzYP2uS_-UJi2cPuq0_g.png" /><figcaption>(DeleteFlag was set by me, so just assume you haven’t seen it here)</figcaption></figure><p>Doesn’t look bad, just parameters should be crammed in quotation marks for complete happiness.</p><p><strong>Conclusion</strong>: tricks are good, but not always 100% useful.</p><h4>C) Create the service with srvany.exe java.exe –jar</h4><p><a href="https://support.microsoft.com/en-us/help/137890/how-to-create-a-user-defined-service">srvany.exe</a> is also a program tool from the Resource Kit. Its work is simple — run the specified app. I.e. we register srvany.exe as a service with parameters indicating the path to our program. Order: start the service → run srvany → run our app.</p><pre>sc create TestServ6 binPath= “E:\Java\JavaPrograms\test\with Spaces\srvany.exe” type= own start= auto error= normal DisplayName= TestService6</pre><p>Add parameters to launch srvany:</p><pre>reg add “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TestServ6\Parameters” /v “Application” /d “\”E:\Java\JavaPrograms\jdk-11.0.1\bin\javaw.exe\” -Xmx400m -jar \”E:\Java\JavaPrograms\test\with Spaces\mainTutorial-1.0-SNAPSHOT.jar\” \”amazing\” \”prod\””</pre><p>Starting.. watching.. waiting.. watching.. it works!! It’s all? This is the end? Or is something missing? Why invented third-party software (except of self-education and advertising purposes)? You can try to kill the process or invoke the exception in the app. And we will smoothly proceed to the next point.</p><p><strong>Conclusion</strong>: srvany works, but catching errors is lame.</p><h3>2) Start the service with third-party software NSSM.</h3><p>Here is a short list of different software:</p><p>- <a href="http://commons.apache.org/proper/commons-daemon/procrun.html">procrun</a></p><p>- <a href="http://commons.apache.org/proper/commons-daemon/jsvc.html">jsvc </a>(pervert’s version: «<em>It can run on Win32 via the Cygwin emulation layer</em>» (с))</p><p>- <a href="https://github.com/kohsuke/winsw">winsw</a></p><p>- <a href="http://winrun4j.sourceforge.net/">WinRun4J</a></p><p>- <a href="https://wrapper.tanukisoftware.com/doc/english/introduction.html">Java Service Wrapper</a></p><p>- <a href="http://nssm.cc/">NSSM (Non-Sucking Service Manager)</a></p><p>We’ll use the last one. For lazy readers repeat the question: why do we need a third-party software? For them, the answer is right from the nssm site:</p><blockquote>«srvany and other service helper programs suck because they don’t handle failure of the application running as a service. If you use such a program you may see a service listed as started when in fact the application has died. nssm monitors the running service and will restart it if it dies.»</blockquote><p>How does it work? All the same: nssm.exe installing as a service with specified parameters, when the service starts — nssm.exe itself starts, which in turn launches java.exe –jar. Here is a clear run in the task manager for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAReb87RVLbGTXVBO3WhDw.png" /></figure><p>Now in order. Execute «nssm.exe install TestServ» to start the GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*T_Jcq5g9Cqb9npFc0mQmdg.png" /><figcaption>(arguments here: -jar “E:\Java\JavaPrograms\test\with Spaces\mainTutorial-1.0-SNAPSHOT.jar” “amazing” “prod”)</figcaption></figure><p>We can do the same using the command line:</p><pre>nssm install TestServ “E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe” “-Xmx400m -jar \”E:\Java\JavaPrograms\test\with Spaces\mainTutorial-1.0-SNAPSHOT.jar\” \”amazing\” \”prod\””</pre><pre>nssm set TestServ DisplayName “Test Service”</pre><pre>nssm set TestServ AppDirectory “E:\Java\JavaPrograms\test\with Spaces”</pre><pre>nssm set TestServ AppRestartDelay 1000</pre><pre>nssm set TestServ Description “Start java.exe with params -Xmx400m -jar mainTutorial.jar amazing prod”</pre><p>it’s important for us to indicate AppDirectory, because the configs and libs used by us lie there, next to our app in the resources and res subfolders.</p><p>If you are tired of the service or you screwed up when creating it, then run the command:</p><pre>nssm remove TestServ</pre><p>Let’s look back-to-back at the registry entries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*2cwsyV8GFjmb1FUNiBMCag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jYTu2SaQR0kcelTohSzz4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHbSEYwu9TJ2xDpJTWimNg.png" /><figcaption>(yes,yes, my folders «with Spaces» and «withoutSpaces» don’t beat in the commands and on screenshots, just consider that you’ve never seen this, for I am too lazy to redo)</figcaption></figure><p>All parameters and quotation marks are in place. Look at the service info:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*E9PPje4g_scTVLJgXx3WYw.png" /></figure><p>Run service.. Hurray! Everything works, logs are written!</p><pre>jun. 23, 2019 9:33:29 AM net.snatchTech.tutorials.App main</pre><pre>CONFIG: The app has been started with name: amazing_prod</pre><pre>jun. 23, 2019 9:33:30 AM net.snatchTech.tutorials.App lambda$main$3</pre><pre>INFO:</pre><pre>service</pre><pre>name : service</pre><pre>id : prod</pre><pre>name_id : service_prod</pre><pre>options</pre><pre>number : 1</pre><pre>string : smth</pre><pre>jun. 23, 2019 9:33:35 AM net.snatchTech.tutorials.App lambda$main$3</pre><pre>INFO:</pre><pre>service</pre><pre>name : service</pre><pre>id : prod</pre><pre>name_id : service_prod</pre><pre>options</pre><pre>number : 1</pre><pre>string : smth</pre><p>Try to kill java or crash your application from the inside.</p><p><strong>Conclusion</strong>: not written by our magnificent hands, brains and legs third-party software also has the right to life.</p><h3>3) Automate it!</h3><p>It’s worthless to start services on 30 servers by handles, the script is necessary! Omit spreading on machines, at least let’s create a service to correctly run the configuration designated on current server just with one variable name change.</p><p>But the script is easy! Sure? And if you add spaces in the names? The pain is hiding in details of fine-tuning quotation marks and their escaping. Suppose we put <em>AppDir </em>into a variable. How should we write it in the params and as the current directory? Where are the quotation marks necessary and where not?</p><pre>set AppDir=”E:\Java\JavaPrograms\test\with Spaces\” or</pre><pre>set AppDir=”E:\Java\JavaPrograms\test\with Spaces\\” or</pre><pre>set AppDir=”E:\Java\JavaPrograms\test\with Spaces”</pre><p>use in parameters:</p><pre>nssm install %SrvName% %PathToProg% “%ProgParams% -jar %AppDir%%AppName% %AppParams% or</pre><pre>nssm install %SrvName% \”%PathToProg%\” “%ProgParams% -jar \”%AppDir%%AppName%\” %AppParams%” or</pre><pre>nssm install %SrvName% %PathToProg% “%ProgParams% -jar \”%AppDir%\\%AppName%\” %AppParams%”</pre><p>as the current directory:</p><pre>nssm set %SrvName% AppDirectory %AppDir% or</pre><pre>nssm set %SrvName% AppDirectory \”%AppDir%\”</pre><p>If configured incorrectly, you can get such an error when starting the service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*Gb0bQXeGSi2xlAo_zSuSGA.png" /><figcaption>(Windows could not start the TestService on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer the service-specific error code 3.)</figcaption></figure><p>Go to system event log for details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*DFcc_5MQ9OoPAvrli92Q0Q.png" /><figcaption>(Service Control Manager: Error: The service “TestService” stopped due to internal error: System can’t find specified path.)</figcaption></figure><p>See what’s wrong with registry paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaO8KM0hKeGKz34iPmo3lQ.png" /></figure><p>Based on the results we draw conclusions about superfluous/missing quotes or slashes in the right places.</p><p>The result script looks like this:</p><pre>@echo on</pre><pre>set WrapperPath=”E:\Java\JavaPrograms\service\nssm.exe”</pre><pre>set SrvName=”TestServ”</pre><pre>set SrvDispName=”Test Service”</pre><pre>set PathToProg=”E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe”</pre><pre>set ProgParams=”-Xmx400m”</pre><pre>set AppDir=”E:\Java\JavaPrograms\test\with Spaces”</pre><pre>set AppName=”mainTutorial-1.0-SNAPSHOT.jar”</pre><pre>set AppParams=\”amazing\” \”prod\”</pre><pre>%WrapperPath% stop %SrvName%</pre><pre>%WrapperPath% remove %SrvName% confirm</pre><pre>%WrapperPath% install %SrvName% %PathToProg% “%ProgParams% -jar \”%AppDir%\\%AppName%\” %AppParams%”</pre><pre>%WrapperPath% set %SrvName% DisplayName %SrvDispName%</pre><pre>%WrapperPath% set %SrvName% AppDirectory %AppDir%</pre><pre>%WrapperPath% set %SrvName% AppRestartDelay 1000</pre><pre>%WrapperPath% set %SrvName% Description “Start %PathToProg% with params %ProgParams% -jar \”%AppDir%\\%AppName%\” %AppParams%”</pre><p>And in the params in the registry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovzwgOPi-RmTCAnACHnNoQ.png" /></figure><p>Let’s test restarting. Run app with throwing an exception in a parallel thread, that the app terminates itself after two iterations.</p><pre>set AppParams=\”amazing\” \”prod\” 2</pre><p>Watch log files, see their re-creation, which means the service restarts our app upon completion. Great! Even logs are presented in the System Event Journal with a source <em>nssm</em>:</p><pre>Program E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe for service TestServ exited with return code 0.</pre><pre>Killing process tree of process 11196 for service TestServ with exit code 0</pre><pre>Service TestServ action for exit code 0 is Restart. Attempting to restart E:\Java\JavaPrograms\jdk-11.0.1\bin\java.exe.</pre><p>Service TestServ ran for less than 1500 milliseconds. Restart will be delayed by 2000 milliseconds.</p><p><strong>Conclusion</strong>: Automate everything you need, not everything you can, otherwise it may take more time for useless work.</p><h3>4) Bonus: jar to exe</h3><p>Now let’s try to convert/wrap/shove our jar-file into exe-file and run it as a service.</p><p>Here is a couple of variants:</p><p><strong>A)</strong> JDK tools, namely JavaPackager (<a href="https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javapackager.html">JDK8</a>, <a href="https://docs.oracle.com/javase/10/tools/javapackager.htm#JSWOR719">JDK10</a>, <a href="https://medium.com/@adam_carroll/java-packager-with-jdk11-31b3d620f4a8">JDK11</a>).</p><p>I haven’t tried it yet, there are a lot of opportunities there, but it’s a bit confusing for our purposes now.</p><p><strong>B)</strong> compilation from the <a href="https://stackoverflow.com/questions/32539336/how-to-create-exe-from-jar-files-in-java">stackoverflow</a>.</p><p><strong>C)</strong> <a href="http://launch4j.sourceforge.net/">Launch4j </a>— standalone program or as a maven plugin.</p><h4><strong>Use standalone launch4j.</strong></h4><p>Fill the GUI form and specify path to jar and its params, try to embed JDK inside:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*BMWGRkN1N2zyjERsSIOn0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*avHY4tnGElk4FDPJHargBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*3LPQQMArgFt11x9th2Z_6Q.png" /></figure><p>However, it can’t be started, the “start” button is unhighlighted. What’s wrong? Try to save the settings and run it from the cmd:</p><pre>launch4jc.exe “E:\Java\JavaPrograms\test\with Spaces\exe\mainTutL4j.xml”</pre><p>run, get:</p><pre>Error: A JNI error has occurred, please check your installation and try again</pre><pre>Exception in thread “main” java.lang.UnsupportedClassVersionError: net/snatchTech/tutorials/App has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0</pre><p>Oh yea, it’s not visible on the screenshot, but I played around firstly and indicated the jre max version as 9, but it needs to be 11. Erase jre version, run, get:</p><pre>some error: This application was configured to use a bundled Java Runtime Environment but the runtime is missing or corrupted.</pre><p>Erm.. add to the Boundled JRE Path — «\javaw.exe». Doesn’t work. Erase javaw and bin folder. Voila! But wait, now run the exe-file:</p><pre>E:\Java\JavaPrograms\test\with Spaces\exe&gt;mainTut.exe</pre><pre>Error: Unable to initialize main class net.snatchTech.tutorials.App</pre><pre>Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/type/TypeReference</pre><p>Aaarrrgh.. it must be a fat jar.. Okay, move the resources folder. Launch.. Yeah it works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4_2RcWRHG1p_9p6vmvxSw.png" /></figure><p>It can be seen from the running processes that in our case mainTut.exe — is just a wrapper, that launches java-exe –jar with params. Moreover, in the “path to jar” argument is mainTut.exe itself! Let’s try to open our exe-file with the archiver:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sG0lrpQFQhRNJQMu_dovvA.png" /></figure><p>Actually, here lies the same thing as in our jar-file.</p><p>One point — we allegedly have a built-in JRE, although it’s not noticeable by size and the archive inside. Let’s try to rename jdk folder for verification. That is, it doesn’t work. We’ll not be tormented with all the relations, the main thing — here is a working variant and it’s necessary to test it as a service.</p><pre>sc create TestServ4 binPath= “E:\Java\JavaPrograms\test\with Spaces\exe\mainTut.exe” type= own start= auto error= normal DisplayName= TestService4</pre><p>but the result is disappointing, like from the cmd — mainTut.exe closes, but java.exe remains. + somehow it’s necessary to throw different arguments to a jar, cause they are sewn into exe-file.</p><p><strong>Conclusion</strong>: the simple wrapping of your jar-file in exe will not give you any profit to run it as a service. And no profit at all. The wrapping makes sense rather for assembling an installation package.</p><h4>General conclusion.</h4><p>Use NSSM to launch jar-file as a service and enjoy the uptime!</p><p>Feel free to shake hand on <a href="https://medium.com/@lk.snatch">Medium </a>or <a href="https://t.me/javadevel">Telegram</a> or <a href="https://twitter.com/lkSnatch"><em>Twitter</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b7b179053e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL: No space left on device]]></title>
            <link>https://medium.com/@lk.snatch/postgresql-no-space-left-on-device-20248e94d623?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/20248e94d623</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 08:11:37 GMT</pubDate>
            <atom:updated>2020-02-19T05:37:59.738Z</atom:updated>
            <content:encoded><![CDATA[<p>After connecting the next bases to monitoring services, that are actively cluttering up postgres tables with lots of interesting data, during drawing the couple panels grafana choked and said: could not resize shared memory segment “/PostgreSQL.2018052794” to 40935124 bytes: No space left on device.</p><p><em>No space left on device? Really?</em> — I thought, but didn’t argue. Maybe the disks are full? Nope, I just truncated all big tables an hour ago.. Wait a minute, the message tells us about shared memory, and Postgres runs into Docker container.</p><h4>Maybe we’ve reached maximum number of inodes?</h4><p>It’s kind of «file <em>metadata</em>» tables, and it can reach their maximum number, if you generated a crowd of tiny files, by default — less than 2kb. Let’s check:</p><pre>df -ih</pre><pre>Filesystem Inodes IUsed IFree IUse% Mounted on</pre><pre>udev 1.3M 430 1.3M 1% /dev</pre><pre>tmpfs 1.3M 943 1.3M 1% /run</pre><pre>/dev/mapper/dosp — ub — vg-root 16M 273K 16M 2% /</pre><pre>tmpfs 1.3M 1 1.3M 1% /dev/shm</pre><pre>tmpfs 1.3M 5 1.3M 1% /run/lock</pre><pre>tmpfs 1.3M 18 1.3M 1% /sys/fs/cgroup</pre><pre>/dev/loop0 13K 13K 0 100% /snap/core/7270</pre><pre>/dev/loop2 13K 13K 0 100% /snap/core/6964</pre><pre>/dev/loop3 12K 12K 0 100% /snap/intellij-idea-community/158</pre><pre>tmpfs 1.3M 11 1.3M 1% /run/user/999</pre><pre>tmpfs 1.3M 23 1.3M 1% /run/user/125</pre><pre>tmpfs 1.3M 33 1.3M 1% /run/user/1000</pre><pre>/dev/loop4 12K 12K 0 100% /snap/intellij-idea-community/159</pre><pre>overlay 16M 273K 16M 2% /var/lib/docker/overlay2/9e1c6aeeef09986c4343861b0ac3f0f99173ecbef88ed6ec63638d89c732cc8a/merged</pre><pre>shm 1.3M 2 1.3M 1% /var/lib/docker/containers/5ff49a01130ce25e5e4b0649cc8a2efd64e4c67e9a8960c5a717c0c0d5d3cefc/mounts/shm</pre><pre>overlay 16M 273K 16M 2% /var/lib/docker/overlay2/c301ce8eede6b77ab62ecb2f2f5038025375baf9bb8bad7ef957bf3180ab17e8/merged</pre><pre>shm 1.3M 1 1.3M 1% /var/lib/docker/containers/00e0a21d2e010034bc48e8ada44e69335d3ac973a18570bd60cd625b2e532c30/mounts/shm</pre><p>Hmm.. each shm uses only 1% of the maximum inodes count..</p><p>Let’s clean old packages as well:</p><pre>apt-get update &amp;&amp; apt-get autoclean &amp;&amp; apt-get clean &amp;&amp; apt-get autoremove</pre><h4>Maybe docker container has a small limit for shm?</h4><p>Let’s see:</p><pre>df –h</pre><pre>Filesystem Size Used Avail Use% Mounted on</pre><pre>udev 4.9G 0 4.9G 0% /dev</pre><pre>tmpfs 995M 3.8M 992M 1% /run</pre><pre>/dev/mapper/dosp — ub — vg-root 245G 17G 216G 8% /</pre><pre>tmpfs 4.9G 0 4.9G 0% /dev/shm</pre><pre>tmpfs 5.0M 0 5.0M 0% /run/lock</pre><pre>tmpfs 4.9G 0 4.9G 0% /sys/fs/cgroup</pre><pre>/dev/loop0 89M 89M 0 100% /snap/core/7270</pre><pre>/dev/loop2 89M 89M 0 100% /snap/core/6964</pre><pre>/dev/loop3 584M 584M 0 100% /snap/intellij-idea-community/158</pre><pre>tmpfs 995M 0 995M 0% /run/user/999</pre><pre>tmpfs 995M 16K 995M 1% /run/user/125</pre><pre>tmpfs 995M 44K 995M 1% /run/user/1000</pre><pre>/dev/loop4 584M 584M 0 100% /snap/intellij-idea-community/159</pre><pre>overlay 245G 17G 216G 8% /var/lib/docker/overlay2/c301ce8eede6b77ab62ecb2f2f5038025375baf9bb8bad7ef957bf3180ab17e8/merged</pre><pre>shm 64M 0 64M 0% /var/lib/docker/containers/00e0a21d2e010034bc48e8ada44e69335d3ac973a18570bd60cd625b2e532c30/mounts/shm</pre><pre>overlay 245G 17G 216G 8% /var/lib/docker/overlay2/9e1c6aeeef09986c4343861b0ac3f0f99173ecbef88ed6ec63638d89c732cc8a/merged</pre><pre>shm 64M 204K 64M 1% /var/lib/docker/containers/5ff49a01130ce25e5e4b0649cc8a2efd64e4c67e9a8960c5a717c0c0d5d3cefc/mounts/shm</pre><p>or the same inside the container:</p><pre>docker exec -it postgresM df -h /dev/shm</pre><pre>Filesystem Size Used Avail Use% Mounted on</pre><pre>shm 64M 204K 64M 1% /dev/shm</pre><h4>64 mb, Coral!!</h4><p>Someone listened to uncle Gates («<em>640k ought to be enough for anybody</em>») and started containers with default settings. But Postgres and Grafana’s flying queries disagree with you, mr. Gates, and 64 mb is not enough for them.</p><h4>Let’s increase the shm-size</h4><p>to 256 mb first, and then we’ll see. This can be done in different ways:</p><p>1) Adding the argument to your <em>app.yml </em>(if all-in-one) or <em>data.yml</em> (if separate postgres):</p><pre>docker_args: “ — shm-size=256m”</pre><p>2) Recreate container with additional shm-size argument:</p><pre>docker run — shm-size=256m — name postgresM -e POSTGRES_PASSWORD=pass -d postgres</pre><p>3) If you using a docker-compose, you can add shm-size to the <em>docker-compose.yml</em>:</p><pre>version: ‘3.5’</pre><pre>services:</pre><pre>  your_service:</pre><pre>    build:</pre><pre>      context: .</pre><pre>      shm_size: ‘256mb’ ← set the size for building</pre><pre>    shm_size: ‘256mb’ ← for running</pre><p>4) But we don’t want to recreate the container! Then open the editor</p><pre>sudo nano /var/lib/docker/containers/your-container-id/hostconfig.json</pre><p>and search for the string ”ShmSize”:67108864, change it value to 256 mb in bytes, restart the container.</p><p>5) Can it be hotter? Of course! Remount our container’s shm file system:</p><pre>mount -o remount,size=256m -t tmpfs /var/lib/docker/containers/your-container-id/mounts/shm</pre><p>Check:</p><pre>docker exec -it postgresM df -h /dev/shm</pre><pre>Filesystem Size Used Avail Use% Mounted on</pre><pre>shm 256M 8.0K 256M 1% /dev/shm</pre><p>Yeah, that’s what I’m talking about! Now everything will be fine!</p><p>We twist-turn the grafana, and the error no longer climbs out.</p><p><em>Feel free to shake hand on </em><a href="https://medium.com/@lk.snatch"><em>Medium</em></a><em> or </em><a href="https://t.me/javadevel"><em>Telegram</em></a><em> or </em><a href="https://twitter.com/lkSnatch"><em>Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20248e94d623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello Maven.]]></title>
            <link>https://medium.com/@lk.snatch/hello-maven-4ebb68f47430?source=rss-6b279bcf490------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ebb68f47430</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Alex Kuk]]></dc:creator>
            <pubDate>Wed, 17 Jul 2019 12:02:41 GMT</pubDate>
            <atom:updated>2019-09-28T15:23:12.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*FIIfmWaiT82OrFv9pLzcNg.png" /></figure><p>Old-school engineers code in notebooks, compiling files through the terminal. Cool guys write bytecode directly. But lazy progers use project-building systems like Accumulator of knowledge (or for those who don’t know Yiddish — <a href="http://maven.apache.org/what-is-maven.html"><em>Apache Maven</em></a>) integrated into the IDE (or lying somewhere close by to warm the soul by starting the build from the terminal periodically).</p><p><strong>So how can our friend help?</strong></p><p>— downloads the libraries you need automatically, if you, for example, wanna parse json or use jdbc connector, but writing it all is too lazy. There is a huge jar-database in the <a href="https://mvnrepository.com/">central repository</a>.</p><p>— runs processing of your annotations or any other malicious scripts.</p><p>— runs tests, if you are TDD-geek or just take care about their writing.</p><p>— compile jar with all libraries and setting files inside or outside as you wish.</p><p>— a lot of other useful or not things.</p><p><strong>Because </strong>you’ll have to knock a lot on the keyboard and wear out a mouse hole in the table without this framework, let’s consider it closer. We’ll begin with the installation.</p><p>Download the latest version from the <a href="http://maven.apache.org/download.cgi">official website</a>, unpack the archive into a folder (`C:\AmazingMaven\maven-version` in Windows or `/opt/AmazingMaven/maven-version` in Linux) and enjoy. Well, for complete relaxation, you can do a couple more actions:</p><p><strong>*1)</strong> Put in the environment variables `M2_HOME` :</p><p>Windows: <em>control panel — system — additional system settings — environment variables — add</em> `M2_HOME =” C:\AmazingMaven\maven-version” `</p><p>Linux: add a row `export M2_HOME=/opt/AmazingMaven/maven-version` to the file `/etc/profile`</p><p><strong>*2)</strong> Add path to bin-folder in variable `PATH` :</p><p>Windows: `%M2_HOME%\bin`</p><p>Linux: add `export PATH=$PATH:$M2_HOME/bin` to the same file `/etc/profile`</p><p><strong>All this is needed for convenience</strong>: autointegration and launching maven from anywhere. Check the correctness from the console:</p><pre>mvn — version</pre><p>See the info:</p><pre>Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018–10–24T21:41:47+03:00)</pre><pre>Maven home: C:\AmazingMaven\maven-version\bin\..</pre><pre>Java version: 11.0.1, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-11.0.1</pre><pre>Default locale: ru_RU, platform encoding: Cp1251</pre><pre>OS name: “windows 10”, version: “10.0”, arch: “amd64”, family: “windows”</pre><p>Check from a terminal:</p><pre>mvn — version</pre><pre>Command ‘mvn’ not found, but can be installed with:</pre><pre>sudo apt install maven</pre><p>Oops.. hands grow out of the wrong place.. but never mind, smart Torvalds has already sent you on the right path:</p><pre>sudo apt-get install maven</pre><p>Then:</p><pre>mvn — version</pre><pre>Apache Maven 3.6.0</pre><pre>Maven home: /usr/share/maven</pre><pre>Java version: 11.0.3, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-11-openjdk-amd64</pre><pre>Default locale: en_US, platform encoding: UTF-8</pre><pre>OS name: “linux”, version: “4.15.0–54-generic”, arch: “amd64”, family: “unix”</pre><p>But I want a folder <em>AmazingMaven</em>?!! Well, RTFM about Linux first.</p><p>If you hate browsers for being a memory hog, you can use the Maven help directly from the terminal. For example, to view information about cleaning phase, type:</p><pre>mvn help:describe -Dcmd=clean</pre><p>Get:</p><pre>[INFO] ‘clean’ is a phase within the ‘clean’ lifecycle, which has the following phases:</pre><pre>* pre-clean: Not defined</pre><pre>* clean: org.apache.maven.plugins:maven-clean-plugin:2.5:clean</pre><pre>* post-clean: Not defined</pre><p>Our favorite IDEA already has Maven, but you can palm off a more recent version. To do this, go to settings `File → Settings`, type `maven` in the search bar, and you’ll see the option to specify `Maven home directory` in the found window, as well as other settings — which folder will be cluttered up by Maven’s downloaded libraries, where to save its settings, etc.</p><p>In the next articles, step by step, we will get high on the capabilities of this framework and shine with joy, poking the button «<em>Do everything</em>».</p><p><em>Feel free to shake hand on </em><a href="https://medium.com/@lk.snatch"><em>Medium</em></a><em> or </em><a href="https://t.me/javadevel"><em>Telegram</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebb68f47430" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>