<?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 Daijue on Medium]]></title>
        <description><![CDATA[Stories by Daijue on Medium]]></description>
        <link>https://medium.com/@daijue?source=rss-f0af16954026------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wWGObvKNFCjm42xs</url>
            <title>Stories by Daijue on Medium</title>
            <link>https://medium.com/@daijue?source=rss-f0af16954026------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:25:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daijue/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[C++ Move Semantics]]></title>
            <link>https://medium.com/@daijue/c-move-semantics-30faf1e855cd?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/30faf1e855cd</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 21:22:49 GMT</pubDate>
            <atom:updated>2023-06-26T21:22:49.018Z</atom:updated>
            <content:encoded><![CDATA[<p>Move semantics is one of the most important features introduced in C++11. As a language that gives programmers great power in resource management, C++ empowers more efficient resource management capabilities with move semantics.</p><h4>An Example Class Containing a Big Chunk of Memory</h4><p>Since memory is a very typical example of resources in C++ programs, let me introduce the following class:</p><pre>class BigObj {<br>public:<br>    BigObj(int sz) {<br>        m_arr = new int [sz];<br>        for (int i=0; i &lt; sz; ++i) {<br>            m_arr[i] = i;<br>        }<br>        m_size = sz;<br>    }<br>    BigObj(const BigObj&amp; other) {<br>        cout &lt;&lt; &quot;copy constructor&quot; &lt;&lt; endl;<br>        m_arr = new int[other.m_size];<br>        memcpy(m_arr, other.m_arr, other.m_size*sizeof(int));<br>        m_size = other.m_size;<br>    }<br>    void double_elem() {<br>        for (int i = 0; i &lt; m_size; ++i) {<br>            m_arr[i] *= 2;<br>        }<br>    }<br>    void display() {<br>        for (int i = 0; i &lt; m_size; ++i) {<br>            cout &lt;&lt; m_arr[i] &lt;&lt; &quot; &quot;;<br>        }<br>        cout &lt;&lt; endl;<br>    }<br>private:<br>    int *m_arr;<br>    int m_size;<br>};</pre><p>This class contains an array of integers pointed by m_arr with size m_size. Depending on the size parameter passed to the constructor, the object of the class can potentially be very big.</p><h4>When an Object is Copied</h4><p>Suppose we have the following function that takes an object of BigObj as its parameter:</p><pre>void make_double(BigObj b) {<br>    b.double_elem();<br>    b.display();<br>}</pre><p>Since the parameter is passed by value, without any compiler optimization, the argument object will be copied to the parameter, as shown below:</p><pre>BigObj b(10);<br>make_double(b);</pre><p>It is worth pointing out that copying the BigObj instance can be very expensive. If we take a look at the copy constructor again:</p><pre>BigObj(const BigObj&amp; other) {<br>    cout &lt;&lt; &quot;copy constructor&quot; &lt;&lt; endl;<br>    m_arr = new int[other.m_size];<br>    memcpy(m_arr, other.m_arr, other.m_size*sizeof(int));<br>    m_size = other.m_size;<br>}</pre><p>It involves allocating an new integer array and copy each byte from the array in the passed in object to the new array. When the size m_size is very big, it is surely not efficient. In this case, we do not have much choice if we need to continue use the variable b as is and do not wish to change its values. The make_double function will change its parameter by doubling the array elements.</p><h4>When an Object is Moved</h4><p>Let us look at the following scenario when calling the make_double function:</p><pre>BigObj create_big_obj(int sz)<br>{<br>    BigObj b(sz);<br>    return b;<br>}<br>make_double(create_big_obj(10));</pre><p>In this case, create_big_obj returns an rvalue object, an object that is temporary and there is no way to access it afterwards. Thus, it does not make sense to go through all the expensive copy. It makes sense just to reuse the temporary object memory and move it to the parameter. Here comes the move constructor that does exactly what is needed:</p><pre>BigObj(BigObj&amp;&amp; other) {<br>    cout &lt;&lt; &quot;move constructor&quot; &lt;&lt; endl;<br>    m_arr = other.m_arr;<br>    m_size = other.m_size;<br>    other.m_arr = nullptr;<br>    other.m_size = 0;<br>}</pre><p>Note how in the move constructor, no new memory is allocated. Instead, the memory pointer is assigned. The memory of the integer array is reused. Remember to invalidate the old pointer by nullify it in the move constructor and setting the size to zero.</p><h4>Putting it Together</h4><p>Here is the complete code that demonstrates the difference between the copy (deep copy) and the move (shallow copy).</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>using namespace std;<br><br>class BigObj {<br>public:<br>    BigObj(int sz) {<br>        m_arr = new int [sz];<br>        for (int i=0; i &lt; sz; ++i) {<br>            m_arr[i] = i;<br>        }<br>        m_size = sz;<br>    }<br>    BigObj(const BigObj&amp; other) {<br>        cout &lt;&lt; &quot;copy constructor&quot; &lt;&lt; endl;<br>        m_arr = new int[other.m_size];<br>        memcpy(m_arr, other.m_arr, other.m_size*sizeof(int));<br>        m_size = other.m_size;<br>    }<br>    BigObj(BigObj&amp;&amp; other) {<br>        cout &lt;&lt; &quot;move constructor&quot; &lt;&lt; endl;<br>        m_arr = other.m_arr;<br>        m_size = other.m_size;<br>        other.m_arr = nullptr;<br>        other.m_size = 0;<br>    }<br>    void double_elem() {<br>        for (int i = 0; i &lt; m_size; ++i) {<br>            m_arr[i] *= 2;<br>        }<br>    }<br>    void display() {<br>        for (int i = 0; i &lt; m_size; ++i) {<br>            cout &lt;&lt; m_arr[i] &lt;&lt; &quot; &quot;;<br>        }<br>        cout &lt;&lt; endl;<br>    }<br>private:<br>    int *m_arr;<br>    int m_size;<br><br>};<br><br>BigObj create_big_obj(int sz)<br>{<br>    BigObj b(sz);<br>    return b;<br>}<br><br>void make_double(BigObj b) {<br>    b.double_elem();<br>    b.display();<br>}<br><br>int main() {<br>    BigObj b(10);<br>    make_double(b);<br>    make_double(create_big_obj(10));<br>    return 0;<br>}</pre><p>The output of the above program is:</p><pre>copy constructor<br>0 2 4 6 8 10 12 14 16 18 <br>move constructor<br>0 2 4 6 8 10 12 14 16 18</pre><p>Note to illustrate the effect, we have to turn off the compiler optimization. So the compilation command looks like below:</p><pre>g++ move.cpp -o move -fno-elide-constructors</pre><p>The move assignment operator is very similar. The key is to specify the parameter as rvalue by using the rvalue reference &amp;&amp;.</p><h4>Conclusion</h4><p>Move semantics is very important in modern C++. It allows C++ programmers to write more efficient programs by avoiding unnecessary resource allocation and copying.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30faf1e855cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of Redis Sentinel]]></title>
            <link>https://medium.com/@daijue/basics-of-redis-sentinel-1f04d8c66c9?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f04d8c66c9</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 00:57:49 GMT</pubDate>
            <atom:updated>2023-06-25T01:02:39.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Redis Sentinel is provided by Redis installation for automatic failover since Redis 2.8. A Redis Sentinel architecture consists of a group of Sentinel instances that work together to achieve automatic failover for master and replica Redis instances. In a previous <a href="https://medium.com/@daijue/the-basics-of-replication-in-redis-4b92a3b275bd">article</a>, Redis replication with master and replica instances is discussed. Redis replication, together with automatic failover provided by Redis Sentinel, provide a Redis native high availability solution.</p><h3>Setting up a Group of Sentinels</h3><p>Before setting up the Sentinel group, a group of master and replica Redis instances needs to be set up, as shown in <a href="https://medium.com/@daijue/the-basics-of-replication-in-redis-4b92a3b275bd">here</a>. Again, to make things simple, we use different ports in a single host to simulate different Sentinel hosts that should be used in a production environment. Suppose we use port 7231, 7232 and 7233 for three Sentinel instances. Let us first prepare the configuration file for the Sentinels. Below is the configuration file sentinel.conf for the Sentinel running on port 7231:</p><pre>port 7231<br>sentinel monitor mymaster 127.0.0.1 6231 2<br>sentinel down-after-milliseconds mymaster 5000<br>sentinel failover-timeout mymaster 60000<br>dir &quot;/path/to/working/dir/of/sentinel1&quot;</pre><p>Sentinels running on port 7232 and 7233 have similar configuration files, except that the first line needs to have the changed port number and the last line needs to have the corresponding Sentinel working directory path. Note that the paths to the Sentinel working directories have to be writable since it will be updated by the Redis Sentinel process, e.g. when a replica is promoted to become a master. Even after starting Sentinel, sentinel.conf will be updated as follows:</p><pre>port 7231<br><strong><em>sentinel monitor mymaster 127.0.0.1 6231 2<br></em></strong>sentinel down-after-milliseconds mymaster 5000<br>sentinel failover-timeout mymaster 60000<br>dir &quot;/path/to/working/dir/of/sentinel1&quot;<br><br># Generated by CONFIG REWRITE<br>latency-tracking-info-percentiles 50 99 99.9<br>protected-mode no<br>user default on nopass ~* &amp;* +@all<br>sentinel myid 54320c59ec2407bea83830c695b26e250ad89ae4<br>sentinel config-epoch mymaster 0<br>sentinel leader-epoch mymaster 0<br>sentinel current-epoch 0<br><br><strong><em>sentinel known-replica mymaster 127.0.0.1 6232</em><br></strong><br><strong><em>sentinel known-replica mymaster 127.0.0.1 6233</em></strong></pre><p>Note that by specifying the master IP address and port in the initial configuration file, Redis Sentinel knows the replicas and adds the information to the configuration file.</p><p>After the above configuration file changes, we can start the three Sentinels as follows:</p><pre>cd /path/to/working/dir/of/sentinel1<br>redis-sentinel ./sentinel.conf<br>cd /path/to/working/dir/of/sentinel2<br>redis-sentinel ./sentinel.conf<br>cd /path/to/working/dir/of/sentinel3<br>redis-sentinel ./sentinel.conf</pre><p>Here is the output of the second Sentinel:</p><pre>3231477:X 24 Jun 2023 19:02:44.420 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:02:44.420 # Sentinel ID is 980f8c2f2f6189fd83ec3fa236dc67d9fb2767b5<br>3231477:X 24 Jun 2023 19:02:44.420 # +monitor master mymaster <strong><em>127.0.0.1 6231</em></strong> quorum 2<br>3231477:X 24 Jun 2023 19:02:44.421 * +slave slave <strong><em>127.0.0.1:6232</em></strong> 127.0.0.1 6232 @ mymaster 127.0.0.1 6231<br>3231477:X 24 Jun 2023 19:02:44.442 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:02:44.442 * +slave slave <strong><em>127.0.0.1:6233</em></strong> 127.0.0.1 6233 @ mymaster 127.0.0.1 6231<br>3231477:X 24 Jun 2023 19:02:44.463 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:02:46.278 * <strong><em>+sentinel sentinel c4a3833d9c7f0da9212800e8da8b9c6d0f3467e8 <br>127.0.0.1 7231</em></strong> @ mymaster 127.0.0.1 6231<br>3231477:X 24 Jun 2023 19:02:46.309 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:02:59.757 * <strong><em>+sentinel sentinel 52d58fe85c652eb474ebec5c1e2cc0de22baf25b <br>127.0.0.1 7233</em></strong> @ mymaster 127.0.0.1 6231<br>3231477:X 24 Jun 2023 19:02:59.794 * Sentinel new configuration saved on disk</pre><p>Note how this Sentinel not just got aware of the master and replica Redis instances, but also knew the Sentinel started before it and the Sentinel started after it.</p><h3>Performing a Failover</h3><p>Now let us check out whether the Sentinels we set up above actually work. What will happen if we manually take down the current Redis master instance? As it turns out, an election of the new master took place immediately after the current master is down. Replica1 becomes the new master.</p><pre>3231477:X 24 Jun 2023 19:02:59.794 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:16:31.577 # +sdown master mymaster <strong><em>127.0.0.1 6231</em></strong><br>3231477:X 24 Jun 2023 19:16:31.717 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:16:31.717 # +<strong><em>new-epoch</em></strong> 1<br>3231477:X 24 Jun 2023 19:16:31.750 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:16:31.750 # +vote-for-leader 52d58fe85c652eb474ebec5c1e2cc0de22baf25b 1<br>3231477:X 24 Jun 2023 19:16:32.180 # +config-update-from sentinel 52d58fe85c652eb474ebec5c1e2cc0de22baf25b 127.0.0.1 7233 @ mymaster 127.0.0.1 6231<br>3231477:X 24 Jun 2023 19:16:32.180 # +<strong><em>switch-master mymaster 127.0.0.1 6231 <br>127.0.0.1 6232</em></strong><br>3231477:X 24 Jun 2023 19:16:32.180 * +slave slave <strong><em>127.0.0.1:6233</em></strong> 127.0.0.1 6233 @ mymaster 127.0.0.1 6232<br>3231477:X 24 Jun 2023 19:16:32.180 * +slave slave <strong><em>127.0.0.1:6231</em></strong> 127.0.0.1 6231 @ mymaster 127.0.0.1 6232<br>3231477:X 24 Jun 2023 19:16:32.208 * Sentinel new configuration saved on disk<br>3231477:X 24 Jun 2023 19:16:37.246 # +sdown slave <strong><em>127.0.0.1:6231</em></strong> 127.0.0.1 6231 @ mymaster 127.0.0.1 6232</pre><p>Correspondingly, the configuration file of the Sentinel is updated as follows:</p><pre>port 7232<br>sentinel monitor mymaster 127.0.0.1 6232 2<br>sentinel down-after-milliseconds mymaster 5000<br>sentinel failover-timeout mymaster 60000<br>dir &quot;/path/to/working/dir/of/sentinel2&quot;<br><br># Generated by CONFIG REWRITE<br>protected-mode no<br>latency-tracking-info-percentiles 50 99 99.9<br>user default on nopass ~* &amp;* +@all<br>sentinel myid 980f8c2f2f6189fd83ec3fa236dc67d9fb2767b5<br>sentinel config-epoch mymaster 1<br>sentinel leader-epoch mymaster 1<br>sentinel current-epoch 1<br><br>sentinel known-replica mymaster 127.0.0.1 6231<br><br>sentinel known-replica mymaster 127.0.0.1 6233<br><br>sentinel known-sentinel mymaster 127.0.0.1 7233 52d58fe85c652eb474ebec5c1e2cc0de22baf25b<br><br>sentinel known-sentinel mymaster 127.0.0.1 7231 c4a3833d9c7f0da9212800e8da8b9c6d0f3467e8</pre><p>When we start up the old master again, it becomes a replica of the new master.</p><p>Sentinels go through a sequence of procedures to decide which replica to promote as the new master:</p><ol><li>Is the replica reachable? If not, is the replica’s down time exceeds down-after-milliseconds * 10 (down-after-milliseconds is the parameter we set in sentinel.conf)? If so, then the replica is not considered for election.</li><li>Redis instances have a configuration parameter called replica-priority. If this parameter is 0, the Redis instance never participate in elections. Otherwise, the smaller the parameter, the higher priority it has during election.</li><li>For replicas having the same replica-priority, their offset is compared. Bigger offset means more updated dataset. Thus replicas having bigger offsets should have higher priority in elections.</li><li>Finally as a tie breaker, replicas’ process IDs are compared. A maller process ID gives higher priority during leader elections.</li></ol><h3>Providing Service Discovery for Redis Clients</h3><p>Many Redis client libraries support Redis Sentinel. To configure these Redis clients, we only need the connection information for Sentinel instances. The Sentinels discover which Redis instance is the new master and which Redis instances are replicas. Information of discovered Redis instances will be sent to the client and updated when failover happens and new masters are elected.</p><h3>Conclusion</h3><p>Redis Sentinel is a powerful tool to provide automatic failover for replicated Redis instances. Sentinels monitor the health of Redis instances, perform new leader election in case of master failure, and provide automatic service discovery for Redis clients. Redis Sentinel is essential for the Redis native high availability solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f04d8c66c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Basics of Replication in Redis]]></title>
            <link>https://medium.com/@daijue/the-basics-of-replication-in-redis-4b92a3b275bd?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b92a3b275bd</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 16:39:31 GMT</pubDate>
            <atom:updated>2023-06-24T16:39:31.195Z</atom:updated>
            <content:encoded><![CDATA[<p>Replication plays an important role in helping Redis achieve high availability and scalability. In the simplest scenario, there is a master Redis node and one or more replica Redis nodes. Since it is often the case that there are more read operations than write operations on Redis, letting the master node handle the write requests and letting the replica nodes handle the read operations seem like a reasonable choice. An implication of this choice is that the master node needs to synchronize its data to the replicas.</p><h4>A Simple Master and Replicas Construction</h4><p>In real production environment, the master node and its replicas reside in different hosts. Here for demonstration purpose, we use different ports on a single hosts for master and replica nodes. The first step is to have separate configuration and data directories for the master and the replicas. Assuming the Redis configuration file is installed in /etc/redis/redis.conf, we need to copy this file to each Redis node’s working directory. The following commands are run to create the Redis node’s working directories and copy the configuration file to them:</p><pre>cd redisReplDemoDir<br>mkdir master replica1 replica2<br>cp /etc/redis/redis.conf master<br>cp /etc/redis/redis.conf replica1<br>cp /etc/redis/redis.conf replica2</pre><p>Note that if you are not running these commands as root user, simply prepend sudo to the cp commands and use chown commands to switch the ownership of these files to the current user.</p><p>Next we need to modify the copied configuration files. Suppose the master node runs on port 6231, the replica1 node runs on port 6232 and the replica2 node runs on port 6233. Then the port modification is shown for the master node as below:</p><pre># Accept connections on the specified port, default is 6379 (IANA #815344).<br># If port 0 is specified Redis will not listen on a TCP socket.<br>port 6231</pre><p>The configuration changes for replica1 and replica2 are similar. In addition, we need to change the data directory and the logfile path in the configuration file. This time using replica1 as an example:</p><pre># The working directory.<br>#<br># The DB will be written inside this directory, with the filename specified<br># above using the &#39;dbfilename&#39; configuration directive.<br>#<br># The Append Only File will also be created inside this directory.<br>#<br># Note that you must specify a directory here, not a file name.<br>dir /path_to_redisReplDemoDir/replica1 <br><br># Specify the log file name. Also the empty string can be used to force<br># Redis to log on the standard output. Note that if you use standard<br># output for logging but daemonize, logs will be sent to /dev/null<br>logfile /path_to_redisReplDemoDir/replica1/redis.log</pre><p>The changes for master and replica2 are similar.</p><p>After all the configuration file changes, we are finally ready to start our Redis instances:</p><pre># Start master Redis<br>cd /path_to_redisReplDemoDir/master<br>redis-server ./redis.conf<br># In a separate terminal, start replica1 Redis<br>cd /path_to_redisReplDemoDir/replica1<br>redis-server ./redis.conf<br># In a third terminal, start replica2 Redis<br>cd /path_to_redisReplDemoDir/replica2<br>redis-server ./redis.conf</pre><p>So far, the three Redis servers are independent of each other. To let them work as a master replica structure, we need to use the replicaof command on the replica nodes. The syntax of this command is as follows:</p><pre>replicaof &lt;materip&gt; &lt;masterport&gt;</pre><p>We can either put the command in the replica configuration files or just use redis-cli to connect to the corresponding replica servers and execute the command. In our case, our command looks like below:</p><pre>$ redis-cli -p 6232<br>127.0.0.1:6232&gt; replicaof 127.0.0.1 6231<br>OK</pre><pre>$ redis-cli -p 6233<br>127.0.0.1:6233&gt; replicaof 127.0.0.1 6231<br>OK</pre><p>To show the replicas in master, use the INFO replication command:</p><pre>$ redis-cli -p 6231<br>127.0.0.1:6231&gt; INFO replication<br># Replication<br>role:master<br>connected_slaves:2<br>slave0:ip=127.0.0.1,port=6232,state=online,offset=966,lag=0<br>slave1:ip=127.0.0.1,port=6233,state=online,offset=966,lag=0<br>master_failover_state:no-failover<br>master_replid:b4f438ca13f1ee505f8bf4f03ccab1f648126463<br>master_replid2:0000000000000000000000000000000000000000<br>master_repl_offset:966<br>second_repl_offset:-1<br>repl_backlog_active:1<br>repl_backlog_size:1048576<br>repl_backlog_first_byte_offset:1<br>repl_backlog_histlen:966</pre><p>We can test out that the above construction works by running set num 123 in redis-cli connected to master. Then in either of the redis-cli connected to replica1 or replica2, running get num will return &quot;123&quot;. This demonstrates that the syncing of data from master to replicas is successful. One thing to note is that by default we only write to master and replicas are for read only. If you try to write to a replica, an error will occur:</p><pre>127.0.0.1:6232&gt; set k v<br>(error) READONLY You can&#39;t write against a read only replica.</pre><h4>Behind the Scenes of Replication</h4><p>To understand what happened behind the scenes of the Redis replication procedure, it is important to understand two concepts: replication ID and offset. A replication ID uniquely identifies a story line of a certain dataset. Offset on the other hand defines the position of the story line. When a Redis instance is started as a master or when a replica Redis instance is promoted to master, a new replication ID is generated. When a replica instance is started as a replica of a master, it inherits the master’s replication ID as its own replication ID. When new Redis commands are processed by a Redis instance, its offset is incremented.</p><p>When the replicaof command is executed on a replica instance, a connection is established between the specified master instance and the replica instance. Then the replica uses the <a href="https://redis.io/commands/psync">PSYNC</a> command to send its current replication ID and offset value to the master. This command indicates to the master that the replica wants to replicate the master’s data. The master then checks if the replication ID sent by the replica is the same as its own replication ID. If it is the same, it means that the replica has been connected to the master before and only need to get the data history from the replica’s offset to the master’s offset. In this case, a <strong><em>partial resynchronization</em></strong> occurs. If the replica’s replication ID and the master’s replication ID are different, it means that it is a new replica connection and needs a <strong><em>full synchronization</em></strong>. Full synchronization can also happen when the replication backlog (a memory buffer) used for partial resynchronization is full. Full synchronization can be potentially expensive, especially when an RDB (Retrospect Disk Backup) file is generated on disc. One approach to reduce the expense of full synchronization is to use diskless replication. In this case, instead of generating an RDB file on disk and then sending the same RDB from disk to the replicas, a background child process of the master directly sends the RDB over the network to replicas, eliminating the need of using the disk as an intermediate storage.</p><h4>Summary</h4><p>In this article, a simple setup of a master along with two replica Redis instances are presented to showcase how to achieve data replication in Redis. Understanding Redis replication builds the foundation of understanding how Redis can scale with multiple replicas for read and how Redis achieves high availability with Redis Sentinel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b92a3b275bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms for Finding All Subsets]]></title>
            <link>https://medium.com/@daijue/algorithms-for-finding-all-subsets-22f5d9b817fa?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/22f5d9b817fa</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 01:58:57 GMT</pubDate>
            <atom:updated>2023-06-14T01:58:57.233Z</atom:updated>
            <content:encoded><![CDATA[<h4>Made with Real Code in Java, Python, C++, Go and JavaScript</h4><p>The problem of finding all subsets of a given set is fundamental in algorithms using recursion and backtracking. Since this type of problems usually asks for listing all possible subsets, the recursion based solution is usually by brutal force enumeration. The real challenge lies in how to translate some abstract thinking in your mind to actual running code. This article will present the recursion based solution in different programming languages, to show how the underlying algorithms are essentially the same.</p><h4>All Subsets of a Set with Unique Elements</h4><p>Let’s begin with a simple example. Suppose we have a set {a,b,c}. Then all possible subsets (a.k.a the power set) are:</p><pre>{}  {a} {b} {c} {a,b} {b,c} {a,c} {a,b,c}</pre><p>One may think the above is a natural way for enumerating subsets: first no element, then all subsets with only one element, then all subsets with two elements and finally the subset with all elements. However, this way of thinking doesn’t naturally lead to branching in recursion. Let us look at the following way of enumeration instead.</p><pre>{a,b,c}    has a    has b    has c <br>{a,b}      has a    has b    no c<br>{a,c}      has a    no b     has c<br>{a}        has a    no b     no c<br>{b,c}      no a     has b    has c<br>{b}        no a     has b    no c<br>{c}        no a     no b     has c<br>{}         no a     no b     no c</pre><p>Note how all subsets at first level divide into two groups: the first half with a and the second half without a. For each half with or without a, it further divides into half with b and half without b. Then the same division happens for c. So for each level of recursion, branching is essentially the decision of whether or not to include an element. Once this point is clear, it is easy to understand the code below.</p><p>In Java:</p><pre>void dfs(int[] nums, int i, List&lt;List&lt;Integer&gt;&gt; res, List&lt;Integer&gt; subset) {<br>    if (i == nums.length) {<br>        res.add(new ArrayList&lt;&gt;(subset));<br>        return;<br>    }<br>    subset.add(nums[i]);<br>    dfs(nums, i+1, res, subset);<br>    subset.remove(subset.size()-1);<br>    dfs(nums, i+1, res, subset);<br>}<br><br>public List&lt;List&lt;Integer&gt;&gt; subsets(int[] nums) {<br>    List&lt;List&lt;Integer&gt;&gt; res = new ArrayList&lt;&gt;();<br>    List&lt;Integer&gt; subset = new ArrayList&lt;&gt;();<br>    dfs(nums, 0, res, subset);<br>    return res;    <br>}</pre><p>In Python:</p><pre>def subsets(self, nums: List[int]) -&gt; List[List[int]]:<br>    res = []<br>    subset = []<br>    def dfs(i):<br>        if i == len(nums):<br>            res.append(subset[:])<br>            return<br>        subset.append(nums[i])<br>        dfs(i+1)<br>        subset.pop()<br>        dfs(i+1)<br>    dfs(0)<br>    return res</pre><p>In C++:</p><pre>void dfs(vector&lt;int&gt;&amp; nums, int i, vector&lt;vector&lt;int&gt;&gt;&amp; res, vector&lt;int&gt;&amp; subset) {<br>    if (i == nums.size()) {<br>        res.push_back(subset);<br>        return;<br>    }<br><br>    subset.push_back(nums[i]);<br>    dfs(nums, i+1, res, subset);<br>    subset.pop_back();<br>    dfs(nums, i+1, res, subset);<br>}<br><br>vector&lt;vector&lt;int&gt;&gt; subsets(vector&lt;int&gt;&amp; nums) {<br>    vector&lt;int&gt; subset;<br>    vector&lt;vector&lt;int&gt;&gt; res;<br>    dfs(nums, 0, res, subset);<br>    return res;<br>}</pre><p>In Go:</p><pre>func subsets(nums []int) [][]int {<br>    res := [][]int{}<br>    subset := []int{}<br>    var dfs func(int)<br>    dfs = func(i int) {<br>        if i == len(nums) {<br>            cpy := make([]int, len(subset))<br>            copy(cpy, subset)<br>            res = append(res, cpy)<br>            return<br>        }<br>        subset = append(subset, nums[i])<br>        dfs(i+1)<br>        subset = subset[:len(subset)-1]<br>        dfs(i+1)<br>    }<br>    dfs(0)<br>    return res   <br>}</pre><p>In JavaScript:</p><pre>/**<br> * @param {number[]} nums<br> * @return {number[][]}<br> */<br>var subsets = function(nums) {<br>    let res = []<br>    let subset = []<br>    function dfs(i) {<br>        if (i == nums.length) {<br>            res.push([...subset])<br>            return<br>        }<br>        subset.push(nums[i])<br>        dfs(i+1)<br>        subset.pop()<br>        dfs(i+1)    <br>    }<br>    dfs(0)<br>    return res<br>};</pre><h4>All Subsets of a Set Containing Duplicate Elements</h4><p>Consider the example set: {a,b,b,c}. All subsets of this set are:</p><pre>{a,b,b,c}    has a    has 2b    has c    <br>{a,b,b}      has a    has 2b    no c<br>{a,b,c}      has a    has 1b    has c<br>{a,b}        has a    has 1b    no c<br>{a,c}        has a    no b      has c<br>{a}          has a    no b      no c<br>{b,b,c}      no a     has 2b    has c<br>{b,b}        no a     has 2b    no c<br>{b,c}        no a     has 1b    has c<br>{b}          no a     has 1b    no c<br>{c}          no a     no b      has c<br>{}           no a     no b      no c</pre><p>Suppose we use the previous algorithm in this case. To tell how the previous algorithm works, we label the first b as b1 and the second b as b2. Then all other cases are OK except the case where the subsets having one b:</p><pre>{a,b1,c} {a,b2,c}<br>{a,b1}   {a,b2}<br>{b1,c}   {b2,c}<br>{b1}     {b2}</pre><p>Since b1 and b2 are essentially the same b, we got duplicated subsets using the previous algorithm. To remove such duplication, we make a rule that if only one b is included, then it must be b1 and not b2. In another words, if b1 is not included, neither should b2 be included. Generally, if a certain element has n duplicates and we only want to include k of the n duplicates in certain subsets, then we always include the first k encountered. Translating that concept into something codable: if the i<em>th</em> a is not included, neither should the i+1<em>th</em> a. To prepare implementing this concept, we need to first sort the input set. Once the input set is sorted, in the branch where the current element is not taken, the next recursion will skip all subsequent duplicates and start with a different valued element. See below for how the dfs function changes by including a while loop before the second recursive call.</p><p>In Java:</p><pre>void dfs(int[] nums, int i, List&lt;List&lt;Integer&gt;&gt; res, List&lt;Integer&gt; subset) {<br>    if (i == nums.length) {<br>        res.add(new ArrayList&lt;&gt;(subset));<br>        return;<br>    }<br>    subset.add(nums[i]);<br>    dfs(nums, i+1, res, subset);<br>    subset.remove(subset.size()-1);<br>    // not including nums[i], so skipping all subsequent nums equal to nums[i]<br>    while (i+1 &lt; nums.length &amp;&amp; nums[i+1]==nums[i]) i++;<br>    dfs(nums, i+1, res, subset);        <br>}<br><br>public List&lt;List&lt;Integer&gt;&gt; subsetsWithDup(int[] nums) {<br>    Arrays.sort(nums);<br>    List&lt;List&lt;Integer&gt;&gt; res = new ArrayList&lt;&gt;();<br>    List&lt;Integer&gt; subset = new ArrayList&lt;&gt;();<br>    dfs(nums, 0, res, subset);<br>    return res;        <br>}</pre><p>In Python:</p><pre>def subsetsWithDup(self, nums: List[int]) -&gt; List[List[int]]:<br>    nums.sort()<br>    res = []<br>    subset = []<br>    def dfs(i):<br>        if i == len(nums):<br>            res.append(subset[:])<br>            return<br>        subset.append(nums[i])<br>        dfs(i+1)<br>        subset.pop()<br>        # not including nums[i], <br>        # so skipping all subsequent nums equal to nums[i]<br>        while i+1 &lt; len(nums) and nums[i+1]==nums[i]:<br>            i += 1<br>        dfs(i+1)<br>    dfs(0)<br>    return res</pre><p>In C++:</p><pre>void dfs(vector&lt;int&gt;&amp; nums, int i, vector&lt;vector&lt;int&gt;&gt;&amp; res, vector&lt;int&gt;&amp; subset) {<br>    if (i == nums.size()) {<br>        res.push_back(subset);<br>        return;<br>    }<br><br>    subset.push_back(nums[i]);<br>    dfs(nums, i+1, res, subset);<br>    subset.pop_back();<br>    <br>    // if the ith number is not included, <br>    // any subsequent number having the same value is also not included<br>    while (i+1 &lt; nums.size() &amp;&amp; nums[i+1]==nums[i]) i++;<br>    dfs(nums, i+1, res, subset);<br>} <br><br>vector&lt;vector&lt;int&gt;&gt; subsetsWithDup(vector&lt;int&gt;&amp; nums) {<br>    sort(nums.begin(), nums.end());<br>    vector&lt;vector&lt;int&gt;&gt; res;<br>    vector&lt;int&gt; subset;<br>    dfs(nums, 0, res, subset);<br>    return res;<br>}</pre><p>In Go:</p><pre>func subsetsWithDup(nums []int) [][]int {<br>    sort.Ints(nums)<br>    res := [][]int{}<br>    subset := []int{}<br>    var dfs func(int)<br>    dfs = func(i int) {<br>        if i == len(nums) {<br>            cpy := make([]int, len(subset))<br>            copy(cpy, subset)<br>            res = append(res, cpy)<br>            return<br>        }<br>        subset = append(subset, nums[i])<br>        dfs(i+1)<br>        subset = subset[:len(subset)-1]<br>        for i+1 &lt; len(nums) &amp;&amp; nums[i+1]==nums[i] {<br>            i++;<br>        }<br>        dfs(i+1)<br>    }<br>    dfs(0)<br>    return res<br>}</pre><p>In JavaScript:</p><pre>/**<br> * @param {number[]} nums<br> * @return {number[][]}<br> */<br>var subsetsWithDup = function(nums) {<br>    nums.sort()<br>    let res = []<br>    let subset = []<br>    function dfs(i) {<br>        if (i == nums.length) {<br>            res.push([...subset])<br>            return<br>        }<br>        subset.push(nums[i])<br>        dfs(i+1)<br>        subset.pop()<br>        // not including nums[i], <br>        // so skipping all subsequent nums equal to nums[i]<br>        while (i+1 &lt; nums.length &amp;&amp; nums[i+1]==nums[i]) i++<br>        dfs(i+1)    <br>    }<br>    dfs(0)<br>    return res<br>};</pre><h4>Practice</h4><p>You can practice the above subset problems with your favorite programming language <a href="https://leetcode.com/problems/subsets/">here</a> and <a href="https://leetcode.com/problems/subsets-ii/">here</a>. After that, you will find similar backtrack problems not as daunting as they appear initially.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22f5d9b817fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Permutation Algorithms]]></title>
            <link>https://medium.com/@daijue/permutation-algorithms-39ec31ac1549?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ec31ac1549</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 00:49:15 GMT</pubDate>
            <atom:updated>2023-06-12T00:49:15.172Z</atom:updated>
            <content:encoded><![CDATA[<h4>Made with Real Code in Java, Python, C++, Go and JavaScript</h4><p><a href="https://artofproblemsolving.com/wiki/index.php/Permutation">Permutation</a> is a fundamental concept in mathematics. Translating the math concept into computer programs is hard initially, but once one understand the pattern and the logic, plus a few rounds of practice, coding permutation algorithms becomes second nature.</p><h4>Permutations with Distinct Elements</h4><p>Think about how one would build all permutations of an array [a,b,c,d]. Let each element take turns to be the first element of the permutation. If a is the first element, then the rest of the permutation can be formed by permuting [b,c,d] ; if b is the first element, then the rest of the permutation can be formed by permuting [a,c,d] ; and so on. If we pin down the first two elements, say b and d, then the rest of the permutation can be formed by permuting [a,c]. Since permuting a bigger array can be done by pinning down a prefix subset of elements and then permuting the rest of the array, this sounds in every way like a recursion. In fact, recursion is exactly what we will use.</p><p>Below code in different languages is presented to present a visual effect of how the inner algorithm is the same with different language implementations. In every implementation, here is a list of similarities:</p><ul><li>The collection of the permutations is called res and the current permutation being worked on is called perm.</li><li>The recursive function called dfs is used to compute the permutation of the subarray starting at index i.</li><li>Each recursion starts with checking the termination condition of i==len(nums). If the condition is true, then a permutation perm is obtained and added to the result res. Note that perm needs to be deep copied to res.</li><li>In each recursion, a FOR loop is used to iterate the elements of nums starting at index i. A swap function is used to put the k<em>th </em>element of nums in its i<em>th</em> place and swap them back when that branch of the recursion is done. This is a nice trick for permutation algorithms.</li><li>The permute function initializes perm and res and also calls dfs with i=0 (starting from the first element).</li></ul><p>In Java:</p><pre>void swap(int[] nums, int i, int j) {<br>    int temp = nums[i];<br>    nums[i] = nums[j];<br>    nums[j] = temp;<br>}<br><br>void dfs(int[] nums, int i, List&lt;List&lt;Integer&gt;&gt; res, List&lt;Integer&gt; perm) {<br>    if (i == nums.length) {<br>        res.add(new ArrayList&lt;&gt;(perm));<br>        return;<br>    }<br><br>    for (int k = i; k &lt; nums.length; ++k) {<br>        swap(nums, i, k);<br>        perm.add(nums[i]);<br>        dfs(nums, i+1, res, perm);<br>        perm.remove(perm.size()-1);<br>        swap(nums, i, k);<br>    }<br>}<br><br>public List&lt;List&lt;Integer&gt;&gt; permute(int[] nums) {<br>    List&lt;List&lt;Integer&gt;&gt; res = new ArrayList&lt;&gt;();<br>    List&lt;Integer&gt; perm = new ArrayList&lt;&gt;();<br>    dfs(nums, 0, res, perm);<br>    return res;<br>}</pre><p>In Python:</p><pre>def permute(self, nums: List[int]) -&gt; List[List[int]]:<br>    def swap(i, j):<br>        nums[i], nums[j] = nums[j], nums[i]<br>    def dfs(i, perm):<br>        if i == len(nums):<br>            res.append(perm[:])<br>            return<br>        for k in range(i, len(nums)):<br>            swap(i, k)<br>            perm.append(nums[i])<br>            dfs(i+1, perm)<br>            perm.pop()<br>            swap(i, k)<br>    res = []<br>    dfs(0, [])<br>    return res</pre><p>In C++:</p><pre>void dfs(vector&lt;int&gt;&amp; nums, int i, <br>vector&lt;vector&lt;int&gt;&gt;&amp; res, vector&lt;int&gt; &amp;perm) {<br>    if (i == nums.size()) {<br>        res.push_back(perm);<br>        return;<br>    }<br>    for (int j = i; j &lt; nums.size(); ++j) {<br>        perm.push_back(nums[j]);<br>        swap(nums[i],nums[j]);<br>        dfs(nums, i+1, res, perm);<br>        swap(nums[i],nums[j]);<br>        perm.pop_back();<br>    }<br>}<br><br>vector&lt;vector&lt;int&gt;&gt; permute(vector&lt;int&gt;&amp; nums) {<br>    vector&lt;vector&lt;int&gt;&gt; res;<br>    vector&lt;int&gt; perm;<br>    dfs(nums, 0, res, perm);<br>    return res;<br>}</pre><p>In Go:</p><pre>func permute(nums []int) [][]int {<br>    res := [][]int{}<br>    perm := []int{}<br>    var dfs func(int)<br>    dfs = func(i int) {<br>        swap := func(i int, j int) {<br>            nums[i], nums[j] = nums[j], nums[i]<br>        }    <br>        if i == len(nums) {<br>            cpy := make([]int, len(perm))<br>            copy(cpy, perm)<br>            res = append(res, cpy)<br>            return<br>        }<br>        for k := i; k &lt; len(nums); k++ {<br>            swap(i, k);<br>            perm = append(perm, nums[i])<br>            dfs(i+1)<br>            perm = perm[:len(perm)-1]<br>            swap(i, k);<br>        }<br>    }<br>    dfs(0)<br>    return res<br>}</pre><p>In JavaScript:</p><pre>/**<br> * @param {number[]} nums<br> * @return {number[][]}<br> */<br>var permute = function(nums) {<br>    let res = []<br>    let perm = []<br>    function dfs(i) {<br>        function swap(i, j) {<br>            temp = nums[i]<br>            nums[i] = nums[j]<br>            nums[j] = temp<br>        }<br>        if (i == nums.length) {<br>            res.push([...perm])<br>            return<br>        }<br>        for (let k = i; k &lt; nums.length; ++k) {<br>            swap(i,k)<br>            perm.push(nums[i])<br>            dfs(i+1)<br>            perm.pop()<br>            swap(i,k)<br>        }        <br>    }<br>    dfs(0)<br>    return res<br>};</pre><h4>Unique Permutations with Possibly Duplicate Elements</h4><p>The skeleton of the algorithm in this case is very similar to the case without duplicated elements. The only enhancement needed is when putting the k<em>th</em> element in the i<em>th</em> place. We use a hash set to check if the same value has already been in the i<em>th</em> place in previous FOR loop iterations, only start the recursive downwards when the i<em>th</em> place is a brand new value. In the code below, since only the dfs function is changed from the previous case, the other functions are omitted.</p><p>In Java:</p><pre>void dfs(int[] nums, int i, List&lt;List&lt;Integer&gt;&gt; res, List&lt;Integer&gt; perm) {<br>    if (i == nums.length) {<br>        res.add(new ArrayList&lt;&gt;(perm));<br>        return;<br>    }<br>    HashSet&lt;Integer&gt; seen = new HashSet&lt;&gt;();<br>    for (int k = i; k &lt; nums.length; ++k) {<br>        if (seen.contains(nums[k])) continue;<br>        seen.add(nums[k]);<br>        swap(nums, i, k);<br>        perm.add(nums[i]);<br>        dfs(nums, i+1, res, perm);<br>        perm.remove(perm.size()-1);<br>        swap(nums, i, k);<br>    }<br>}</pre><p>In Python:</p><pre>def dfs(i, perm):<br>    if i == len(nums):<br>        res.append(perm[:])<br>        return<br>    seen = set()<br>    for k in range(i, len(nums)):<br>        if nums[k] in seen:<br>            continue<br>        seen.add(nums[k])<br>        swap(i, k)<br>        perm.append(nums[i])<br>        dfs(i+1, perm)<br>        perm.pop()<br>        swap(i, k)</pre><p>In C++:</p><pre>void dfs(vector&lt;int&gt;&amp; nums, int i, <br>vector&lt;vector&lt;int&gt;&gt;&amp; res, vector&lt;int&gt;&amp; perm) {<br>    if (i == nums.size()) {<br>        res.push_back(perm);<br>        return;<br>    }<br>    unordered_set&lt;int&gt; seen;<br>    for (int k = i; k &lt; nums.size(); ++k) {<br>        // same value in perm[i] cannot happen again<br>        if (seen.find(nums[k]) != seen.end()) continue;<br>        // kth element in nums as ith element in perm<br>        seen.insert(nums[k]);<br>        swap(nums[i], nums[k]);<br>        perm.push_back(nums[i]);<br>        dfs(nums, i+1, res, perm);<br>        perm.pop_back();<br>        swap(nums[i], nums[k]);<br>    }<br>}</pre><p>In Go:</p><pre>dfs = func(i int) {<br>    swap := func(i int, j int) {<br>        nums[i], nums[j] = nums[j], nums[i]<br>    }    <br>    if i == len(nums) {<br>        cpy := make([]int, len(perm))<br>        copy(cpy, perm)<br>        res = append(res, cpy)<br>        return<br>    }<br>    seen := make(map[int]bool)<br>    for k := i; k &lt; len(nums); k++ {<br>        if _, ok := seen[nums[k]]; ok {<br>            continue<br>        }<br>        seen[nums[k]] = true<br>        swap(i, k);<br>        perm = append(perm, nums[i])<br>        dfs(i+1)<br>        perm = perm[:len(perm)-1]<br>        swap(i, k);<br>    }<br>}</pre><p>In JavaScript</p><pre>function dfs(i) {<br>    function swap(i, j) {<br>        temp = nums[i]<br>        nums[i] = nums[j]<br>        nums[j] = temp<br>    }<br>    if (i == nums.length) {<br>        res.push([...perm])<br>        return<br>    }<br>    const seen = new Set()<br>    for (let k = i; k &lt; nums.length; ++k) {<br>        if (seen.has(nums[k])) continue<br>        seen.add(nums[k])<br>        swap(i,k)<br>        perm.push(nums[i])<br>        dfs(i+1)<br>        perm.pop()<br>        swap(i,k)<br>    }        <br>}</pre><h4>Practice</h4><p>Finally, after getting your head around the algorithms, practice with your favorite programming language <a href="https://leetcode.com/problems/permutations/">here</a> and <a href="https://leetcode.com/problems/permutations-ii/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ec31ac1549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tale of Two Pointers]]></title>
            <link>https://medium.com/@daijue/a-tale-of-two-pointers-b78bb384abc0?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/b78bb384abc0</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 16:48:59 GMT</pubDate>
            <atom:updated>2024-10-28T23:50:14.502Z</atom:updated>
            <content:encoded><![CDATA[<h4>Solutions to Algorithm Interview Questions by Two Pointers Going in the Same Directions</h4><p>Two pointer questions are indispensable for any candidate who is preparing algorithm interviews. Generally, two pointer questions can be divided into two categories: two pointers go in the same directions and two pointers go in the opposite directions. This article will focus on the first category: left and right pointers go in the same direction. All the code in this article is written in Java, but the basic algorithm structure is applicable to other programming languages as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0mvZ2z5N7SD6Ht5E" /><figcaption>Photo by <a href="https://unsplash.com/@helloimnik?utm_source=medium&amp;utm_medium=referral">Nik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The Epitome of the Two Pointers Structure</h4><p>Let me start by presenting a very common interview question: <a href="https://leetcode.com/problems/minimum-size-subarray-sum/">LeetCode 209 Minimum Size Subarray Sum</a>. The title of the problem already gives away several hints. In particular, the word <strong><em>Subarray</em></strong> tells you that you will be seeking a portion of the array that is usually defined by a pair of indexes: a left one and a right one. Since indexes are usually represented by integers, the word <strong><em>pointer</em></strong> almost sounds like a misnomer. So in the context of this article, pointers can be viewed as array indexes. Then what are we looking at in this subarray? The answer is right there in the title: <strong><em>Subarray Sum</em></strong>. As programmers who always strive for efficiency, we don’t settle for any subarray, we want one with <strong><em>Minimum Size</em></strong>, another hint by the title of the problem. Isn’t that amazing that by only reading the title of the problem, we already get a sense of its content? Then the rest of the problem description just confirms our assumptions and provides a few more details: we are give an array of positive integers nums and a positive integer target , we want to find a subarray whose sum is greater than or equal to target and that subarray needs to be of minimal length; we return the minimal length as our solution.</p><p>It is not hard to come up with or understand a rough procedure to solve this problem:</p><ol><li>Initialize two pointers l and r to point to the beginning of the array. In code, that means l=0 and r=0 .</li><li>Expand the subarray by moving the right pointer r to the right so that the sum of the subarray delimited by l and r is greater than or equal to target .</li><li>Shrink the subarray (in order to find the mimimal length) by moving the left pointer l to the right as long as the subarray sum is still greater than or equal to target .</li><li>Repeat the above two steps until the end of the array is reached. At this point, a minimal length is available.</li></ol><p>It doesn’t take much programming experience to understand the above procedure, but translating that into a piece of working code is not as trivial. Fortunately, boilerplate code can be applied. Let me present the entire code first, then the next section will tell you the story behind.</p><pre>public int minSubArrayLen(int target, int[] nums) {<br>      int n = nums.length;<br>      int l = 0, sum = 0;<br>      int len = 0, minLen = n+1;<br>      for (int r = 0; r &lt; n; ++r) {<br>          // do something when the right pointer moves one step ahead<br>          // in this case, add the new element to the subarray sum<br>          sum += nums[r];<br>          while (sum &gt;= target) {<br>              // keep moving the left pointer ahead (shrinking the subarray) <br>              // while the subarray sum still meets the target<br>              // update the subarray sum and length along the way<br>              len = r - l + 1;<br>              if (len &lt; minLen) minLen = len;<br>              sum -= nums[l++];<br>          }<br>      }<br>      if (minLen == n+1) return 0;<br>      return minLen;                <br>}</pre><h4>The Choreography of Two Pointers</h4><p>First, I want to highlight the skeleton of the above code, which happens to be applicable to almost the entire category of problems involving two pointers going in the same direction:</p><pre>for (int r = 0; r &lt; n; ++r) {<br>     // do something when the right pointer moves one step ahead<br>     // ...<br>     // ...<br>     // ...<br>     while (sum &gt;= target) {<br>         // keep moving the left pointer ahead (shrinking the subarray) <br>         // while certain conditions of the window are met<br>         // update the current optimal solution along the way<br>         // ...<br>         // ...<br>         // ...<br>         l++;<br>         <br>     }<br>}</pre><p>Think of the right pointer as the pioneer, aggressively trying to explore new territories to reach for the target, one step at a time (this is expressed as the outer for loop, with things happening during each step expressed as the code inside the for loop). The left pointer, on the other hand, is the responsible type. Along every step the right pointer moves forward, the left pointer carefully moves forward for a more optimal solution while making sure the target is still within reach (this is expressed as the while loop inside the for loop). During the iterations that the right pointer is not far enough to reach the target, the left pointer is patiently standing still waiting and not making any move (in this case, the while loop condition is not met and the code inside is not executed). In our exemplary example above, when the right pointer moves one step forward, we add the new element into the sum sum += nums[r] ; when the left pointer moves one step forward, we remove the eliminated element from the sum sum -= nums[l] . We set the initial minLen to one more than the length of the array because we want to check the case that even adding up every element of the array, the total sum is still less than the target . In this case, the function return 0 as required by the problem description.</p><h4>A Pattern to Follow</h4><p>As you solve more and more such two pointers problems, it is easy to spot a pattern of the problems: the setting of the problem always involves an <strong><em>indexable</em></strong> data structure: either a <strong><em>string</em></strong> or an <strong><em>array</em></strong>. In the sea of all possible substrings or subarrays, you are asked to find one substring or one subarray that not only satisfies a given <strong><em>target condition</em></strong>, but also is an <strong><em>optimal</em></strong> one (either the longest or the shortest among those that satisfy the given condition). The solution code also follows a pattern: an outer loop denoting the steps of the right pointer and an inner loop (or if condition) denoting the steps of the left pointer. To demonstrate this, here are a list of similar problems along with their solutions:</p><ul><li><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">LeetCode 3. Longest Substring Without Repeating Characters</a>: whenever the right pointer is moved to expand the substring, a duplicate character can be introduced; this is when the left pointer comes into rescue: it keeps removing characters from the window until the duplicate character, if any, is eliminated.</li></ul><pre>public int lengthOfLongestSubstring(String s) {<br>      int l = 0, r = 0;<br>      int len = 0, maxLen = 0;<br>      for (; r &lt; s.length(); ++r) {<br>          Character cr = s.charAt(r);<br>          // for loop won&#39;t be entered if l==r<br>          for (int i = l; i &lt; r; ++i) {<br>              Character ci = s.charAt(i);<br>              // by introduing character cr to the window,<br>              // need to make sure to skip any previous cr<br>              // from the previous window<br>              if (ci == cr) {<br>                  l = i+1;<br>                  break;<br>              }<br>          }<br>          // now window is valid (contains only unique chars) <br>          len = r - l + 1;<br>          if (len &gt; maxLen) maxLen = len;<br>      }<br>      return maxLen;        <br>}</pre><ul><li><a href="https://leetcode.com/problems/minimum-window-substring/">LeetCode 76. Minimum Window Substring</a>: this is a hard problem, mainly because of the bookkeeping efforts involved. The key is to keep in mind that the condition of a valid window (also the condition of the while loop winCharMatch==numUniqChar) is to have each character count (stored in charCnt and numUniqChar) in the target string t fully represented in the character count in the window (stored in winCharCnt and winCharMatch).</li></ul><pre>public String minWindow(String s, String t) {<br>    if (t.length() == 0) return &quot;&quot;;<br>    // initialize the variables for bookkeeping<br>    HashMap&lt;Character, Integer&gt; charCnt = new HashMap&lt;Character, Integer&gt;();<br>    for (int i = 0; i &lt; t.length(); ++i) {<br>        Character tc = t.charAt(i);<br>        charCnt.put(tc, charCnt.getOrDefault(tc, 0)+1);<br>    }<br>    int numUniqChar = charCnt.size();<br>    int winCharMatch = 0;<br>    int[] window = new int[]{-1,-1};<br>    int winLen = s.length() + 1;<br>    int r = 0, l = 0;<br>    HashMap&lt;Character, Integer&gt; winCharCnt = new HashMap&lt;Character, Integer&gt;();<br>    // FOR loop for expanding the window <br>    // by moving the right pointer<br>    for (; r &lt; s.length(); ++r) {<br>        Character rc = s.charAt(r);<br>        winCharCnt.put(rc, winCharCnt.getOrDefault(rc, 0)+1);<br>        if (winCharCnt.get(rc).equals(charCnt.get(rc))) {<br>            winCharMatch++;<br>        }<br>        // WHILE loop for shrinking the window <br>        // by moving the left pointer <br>        // meanwhile maintaining the validity of the window<br>        while (winCharMatch == numUniqChar) {<br>            int len = r - l + 1;<br>            if (len &lt; winLen) {<br>                winLen = len;<br>                window[0] = l; window[1] = r;<br>            }<br>            Character lc = s.charAt(l);<br>            if (winCharCnt.get(lc).equals(charCnt.get(lc))) {<br>                // previously char cnt for s[l] matched, <br>                // but no longer so because the left pointer<br>                // is about to move<br>                winCharMatch--;<br>            }<br>            winCharCnt.put(lc, winCharCnt.get(lc)-1);<br>            l++;<br>        }<br>    }<br>    if (winLen == s.length()+1) return &quot;&quot;;<br>    return s.substring(window[0], window[1]+1);<br>}</pre><ul><li><a href="https://leetcode.com/problems/longest-repeating-character-replacement/">LeetCode 424. Longest Repeating Character Replacement</a>: I lied before by saying that there is always a WHILE loop inside the FOR loop. The following solution only has an IF to check the validity of the window. In my defense, unlike in other cases where the while loop relentlessly makes sure that the window is valid, in this solution the window is not always valid at the end of each iteration of the for loop (please read on to see why this is OK). When I first saw this solution, I was skeptical about its correctness. As I spent time pondering upon it, I realized the profound meaning of the variables maxFreq and len . maxFreq is the count of the most frequent characters in the window of length len. len never decreases. len increases only when the window is valid. len increases naturally when r increases. But once it is found the window is not valid, len is prevented from increasing naturally by increasing l (shrinking the window). This process ensures that when there is a longer valid window, it is recorded; when the window is not valid, its length never increases. This sliding window is just like those beautiful moments in life that cannot last continuously, but still great to encounter them in the first place and there is always chance that something even more tremendous will come going forward.</li></ul><pre>public int characterReplacement(String s, int k) {<br>    int maxFreq = 0;<br>    // charCnt faithfully records the character counts in the sliding window<br>    HashMap&lt;Character, Integer&gt; charCnt = new HashMap&lt;&gt;();<br>    int l = 0;<br>    int len = 0, maxLen = 0;<br>    for (int r = 0; r &lt; s.length(); ++r) {<br>        int rcCnt = charCnt.getOrDefault(s.charAt(r), 0) + 1;<br>        charCnt.put(s.charAt(r), rcCnt);<br>        if (rcCnt &gt; maxFreq) {<br>            // adding the right pointer character is <br>            // just adding one more most frequent character,<br>            // so it won&#39;t add more entropy to the window<br>            // thus no <br>            maxFreq = rcCnt;<br>        } else {<br>            len = r - l + 1;<br>            // the IF mutation of the WHILE loop<br>            if (len - maxFreq &gt; k) {<br>                // adding the right pointer character <br>                // causes or does not change the fact that <br>                // the current window of length len is invalid<br>                // we cannot make len a new solution.<br>                // has to shrink  <br>                int lcCnt = charCnt.get(s.charAt(l)) - 1;<br>                charCnt.put(s.charAt(l), lcCnt);<br>                l++;<br>            }<br>        }<br>        // len will be non-decreasing over the iterations<br>        // when it increases, the window [l,r] is valid<br>        len = r - l + 1; <br>        if (len &gt; maxLen) maxLen = len;<br>    }<br>    return maxLen;<br>}</pre><h4>Mutations and Variations</h4><p>If it has been an ordeal to read along and understand the above problems and solutions, I hope you could brace yourself for the fact that smart people can always find ways to add more twists and turns to the tale of two pointers. As you dive deeper into the story, you will find the need to use priority queues or monotonic stacks, among other hard-to-maneuver tools. Those problems deserve tales of their own and I will be happy to tell them in the upcoming stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b78bb384abc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Promise — To Resolve or To Reject]]></title>
            <link>https://medium.com/@daijue/the-javascript-promise-to-resolve-or-to-reject-5eff5c7e9139?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eff5c7e9139</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 14:28:32 GMT</pubDate>
            <atom:updated>2022-03-22T14:28:32.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>The JavaScript Promise — To Resolve or To Reject</h3><p>Even before its formal introduction in ECMAScript 2015 (a.k.a. ES6), promises have existed in various JavaScript libraries (e.g. bluebird, WinJS, RSVP.js). ES6 elevated promises to the status of native first level objects in JavaScript, just like objects of String, Date, Array, etc. One of the essential benefits of using the Promise construct is to escape layers upon layers of callback indentations — the callback hell. Not only does Promise makes your JavaScript code aesthetically appealing, it also makes the code logically cleaner — thus easier to read, debug, and maintain.</p><h4>Why a Promise Has to be Made?</h4><p>Before you get to know Promise, it is crucial to understand<a href="https://blog.bitsrc.io/the-good-and-bad-of-javascript-callbacks-dc6dffc21519"> callbacks</a> first. Callbacks are essentially functions passed as arguments to another function that is called a higher-order function. Whether a callback is synchronous or asynchronous is entirely determined by the implementation of the higher-order function. Below is an example of a synchronous callback where the higher-order function hf executes the callback cb right there on its own stack frame:</p><pre>function f1 () { return &quot;123&quot; } <br>function f2 () { return &quot;456&quot; }<br>function hf (<strong>cb</strong>) { console.log(&quot;before&quot;, <strong>cb()</strong>, &quot;after&quot;) }<br>hf(f1) // f1 is the callback, output is: before 123 after<br>hf(f2) // f2 is the callback, output is: before 456 after</pre><p>Unlike the case of synchronous callbacks, there is no way to achieve asynchronous callbacks by using user defined functions exclusively in JavaScript. APIs provided by the JavaScript runtime environment have to be used. These asynchronous APIs are usually implemented in a lower-level language such as C++. Here is an example of the callbacks using the setTimeout asynchronous API:</p><pre>function f1 () { setTimeout(()=&gt;console.log(&quot;123&quot;),2000) }<br>function f2 () { setTimeout(()=&gt;console.log(&quot;456&quot;),1000) } <br>function hf(<strong>cb</strong>) {console.log(&quot;before&quot;); <strong>cb()</strong>;console.log(&quot;after&quot;);}<br>hf(f1)<br>hf(f2)</pre><p>The output of the above code is as follows:</p><pre>before<br>after<br>before<br>after<br>456<br>123</pre><p>Note that the messages in the callback functions are printed after calling the callbacks, indicating that the execution happens after the current call stack.</p><p>Callbacks are great in that not only do they provide the mechanism for algorithmic polymorphism, asynchronous callbacks also help JavaScript achieve the illusion of multi-threaded execution even though the execution engine of JavaScript is single-threaded by nature. The problem, however, lies in the nested use of callbacks — a.k.a the callback hell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2177b45015e6d8efe338b476e5867ae/href">https://medium.com/media/d2177b45015e6d8efe338b476e5867ae/href</a></iframe><p>The output of the above code is f3(f2(f1(f0(10)))), which I am sure is confusing for some people, especially when you look at the last line of the code: line 21 — the manifestation of the callback hell. To help a bit in making the code more comprehensible, here f0, f1, f2, and f3 are functions that take two parameters: the first parameter is the result from its own higher-order function (f0’s result is passed as f1’s first argument, f1’s result is passed as f2’s first argument, and so on); the second parameter is a callback that uses the result value in the calling function as its sole argument. Each callback adds a function name and wraps a pair of parenthesis to the value passed from the outer level function. The deeper the callback, the outer the funcName is located in the output string.</p><p>Promise came into existence to rescue programmers from the above nerve-wracking nested callback hell. Instead of leading people deeper and deeper into the callback rabbit hole, Promise collapses the nesting into a chain of sequences that much resembles how human brains think:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ff969e227f9732b1f72eb3a3c271472/href">https://medium.com/media/8ff969e227f9732b1f72eb3a3c271472/href</a></iframe><p>Notice how elegant line 30–34 are. All because each function now focuses on producing result, and not even needs to be aware of the fact that the result will be used by another function followed by another function.</p><h4>How to Make a Promise</h4><p>If the above code that uses promises looks fine and dandy to you, you might still think it is a bit mysterious. Part of the mysterious feeling may come from the fact that the Promise constructor takes a parameter, and that parameter is a callback! Using Promise does not mean to discard callbacks. In fact, Promise and callbacks work together. Here is how to construct the simplest Promise object:</p><pre>const p = new <strong>Promise</strong>(()=&gt;{})</pre><p>The parameter of the Promise constructor is called an <strong>executor</strong>. The executor is run inside the Promise constructor, and this run is <strong>synchronous</strong>. The following code proves that it is indeed the case:</p><pre>console.log(&quot;before&quot;)<br>const p = new <strong>Promise</strong>(()=&gt;{console.log(&quot;executor is running!&quot;)})<br>console.log(&quot;after&quot;)</pre><p>The output of the above code is:</p><pre>before<br>executor is running!<br>after</pre><p>Note how the message inside the executor is printed out immediately before the message in the next statement is printed out.</p><p>Albeit being simple, an executor with no parameter does not do anything interesting. Usually an executor takes one or two parameters: conventionally called <strong>resolve</strong> for the first parameter and <strong>reject</strong> for the second parameter. (It is absolutely fine if you give other names to the parameters, such as “myResolve” and “myReject”). Note that both <strong>resolve</strong> and <strong>reject</strong> are themselves <strong>callbacks</strong>. You do not need to define resolve and reject, it is defined in the Promise implementation. You only need to call resolve and reject inside the executor.</p><p>Both resolve and reject take practically anything as arguments. The argument to resolve is the result produced by the executor. The argument to reject is the error occurred during the executor run. Here is an illustration of how to use resolve and reject inside the executor:</p><pre>const p = new <strong>Promise</strong>((<strong>resolve</strong>, <strong>reject</strong>)=&gt;{<br>    doSomethingSyncOrAsync(args, (err, data)=&gt;{<br>        if (err) <strong>reject</strong>(new Error(&quot;error code: &quot;+err))<br>        else     <strong>resolve</strong>(data)<br>  })<br>})</pre><h4>Inside a Promise</h4><p>Internally, a Promise object has two important properties: promise <strong>state</strong> and promise <strong>value</strong>. These properties cannot be accessed outside a promise, but can be accessed with methods of the promise. If neither resolve or reject is called during the executor run, a Promise object stays at the <strong>pending</strong> state and its value is <strong>undefined</strong>. Once resolve is called, the promise’s state becomes <strong>fulfilled</strong> and its value is the value of the resolve argument. Once reject is called, the promise’s state becomes <strong>rejected</strong> and its value is the value of the reject argument. When a promise in in <strong>fulfilled</strong> or <strong>rejected</strong> state, the promise is said to be <strong>settled</strong>. Once a promise is settled, its state and value are set in stone. Subsequent calls of resolve and reject have no effect on the state or value of the promise. In another words, only the first call of either resolve or reject will take effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*gRH2tFhU3j9oNrsRXphQcw.png" /><figcaption>State Transition of a Promise Object</figcaption></figure><p>Note that unlike a return statement, reject and resolve do not control the execution flow of the executor run. A resolve call or a reject call only settles the promise — changes the internal state and the internal value of the promise. These changes, however, can work wonders when methods then(), catch(), finally() are called.</p><h4>What Happens then() After a Promise is Settled</h4><p>then(), catch() and finally() are instance methods of a promise, they consumes the result produced by the promise. The parameters for all three methods are callbacks again! (Didn’t I tell you at the beginning that callbacks are important for promises?) Among the three methods, then() is probably the most versatile in that both catch() and finally() are special cases of then(). then() takes two parameters that are usually named onfulfilled and onrejected. If then() is called on a Promise object, once the promise is in the <strong>fulfilled</strong> state, the onfulfilled callback is put on the event queue to be executed. Similarly, once the promise is in the <strong>rejected</strong> state, the onrejected callback is executed. This means that only when a promise is settled, will either onfulfilled or onrejected be executed. The execution of either onfulfilled or onrejected is asynchronous (the settlement of a promise cannot be determined synchronously). The following code proves that the callback parameters for then() are indeed asynchronously executed:</p><pre>const p = new Promise((resolve, reject)=&gt;{<br>    setTimeout(()=&gt;resolve(&quot;mydata&quot;), 2000)<br>})<br>console.log(&quot;before calling then()&quot;)<br>let p0 = p.then((v)=&gt;{console.log(v)}, (e)=&gt;{console.log(e)})<br>console.log(&quot;after calling then()&quot;)</pre><p>The output of the above code is:</p><pre>before calling then()<br>after calling then()<br>mydata</pre><p>Note how then() returns immediately and the message after the then() call is printed first. After two seconds when the promise p is resolved with value mydata, the onfulfilled callback is executed and the string mydata is printed out.</p><p>It is also important to note that then() returns a Promise object! This is exactly the reason that you can chain multiple then() together to perform synchronous or asynchronous tasks in sequence, especially when a later task run depends on the result from a previous task. As for the status and value of the returned promise by then()? Well, it really depends on whether onfulfilled and onrejected have return statement at all and also on what value does onfulffiled or onrejected return. Here is a list of scenarios:</p><ol><li>If neither onfulfilled nor onrejected is executed, then() returns a <strong>pending</strong> promise with value undefined.</li><li>If either onfulfilled or onrejected is executed and does not have a return statement, then() returns a <strong>fulfilled</strong> promise with value undefined.</li><li>If either onfulfilled or onrejected is executed and does have a return statement that returns a <strong>non-promise</strong> value v, then() returns a <strong>fulfilled</strong> promise with value v.</li><li>If either onfulfilled or onrejected is executed and does have a return statement that returns a <strong>promise</strong> value p, then() returns a promise whose status and value are exactly the <strong>same</strong> as p.</li><li>If either onfulfilled or onrejected is executed and throws an <strong>exception </strong>e, then() returns a <strong>rejected</strong> promise with value e.</li></ol><p>Phew, that was a lot of scenarios to list, just for what then() returns! I understand that it can be confusing to read the list, but hope that the following code can eliminate some of the confusion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a948ae5d9dea3b10c9356a5d498d66cf/href">https://medium.com/media/a948ae5d9dea3b10c9356a5d498d66cf/href</a></iframe><p>The output of the above code is as follows:</p><pre>first data<br>second data<br>third data<br>undefined<br>fifth error<br>sixth error</pre><p>Note that for clarity, I explicitly assign each promise to a variable instead of chaining the promises. Each promise uses either the data or the error from the previous promise. Depending on the previous promise status, only one of the onfulfilled and the onrejected callbacks is passed to the then() method of the current promise. Promise.resolve() and Promise.reject() will be discussed in the next section.</p><p>Enough talk about then(), and rest assured that I did not forget catch() and finally(). catch() only handles a rejected promise, thus it only has one callback parameter onrejected. Logically, catch(onrejected) is the same as then(null, onrejected). finally() has one callback parameter that is executed for a settled promise, whether the promise is fulfilled or rejected. Logically, finally(cb) is the same as then(cb, cb). In addition, finally()’s callback parameter does not take any parameter, thus will not process the resolved data or rejected error for the promise. Instead, finally() acts like a relay and passes the resolved data or rejected error on to the next promise.</p><pre>let p = new Promise((resolve)=&gt;{resolve(&quot;first data&quot;)})<br>p.<strong>finally</strong>(()=&gt;{console.log(&quot;executed once settled&quot;)})<br>.<strong>then</strong>(data=&gt;{console.log(&quot;data passed on by finally: &quot;, data)})</pre><h4>Other Flavors of Promise</h4><p>There are several <strong>static</strong> methods of Promise that are used to either construct a settled promise directly or to compose a promise from a collection of promises.</p><p><strong>Promise.resolve(value)</strong> returns a fulfilled promise and the value of the promise is value. <strong>Promise.reject(reason)</strong> returns a rejected promise and the value of the promise is reason. These two static methods are convenient factory methods to construct a settled promise.</p><p><strong>Promise.all(iterable)</strong> takes an iterable collection consisting of promises or non-promise values and returns a Promise object. The returned promise is initially in <strong>pending</strong> state with <strong>undefined</strong> value. Once all promises in the collection are fulfilled, then the returned promise is <strong>fulfilled</strong> and its value is a list of resolved values.</p><pre>let p1 = Promise.resolve(1)<br>let p2 = Promise.resolve(2)<br>console.log(&quot;Before calling Promise.all&quot;, p1, p2)<br>let pa = <strong>Promise.all</strong>([p1, p2, 3, undefined])<br>console.log(&quot;After calling Promise.all&quot;, pa)<br>pa.then(v=&gt;console.log(pa, v))</pre><p>The output of the above code is as follows:</p><pre>Before calling Promise.all Promise { 1 } Promise { 2 }<br>After calling Promise.all Promise { &lt;pending&gt; }<br>Promise { [ 1, 2, 3, undefined ] } [ 1, 2, 3, undefined ]</pre><p>The fact that after calling Promise.all, the returned promise pa is in <strong>pending</strong> state indicates that Promise.all executes <strong>asynchronously</strong>.</p><p>On the other hand, as soon as one of the promises in the Promise.all argument is <strong>rejected</strong>, the returned promise becomes rejected too with the rejected value, even in the case that some of promises is not settled and in pending state.</p><pre>let p0 = new Promise(()=&gt;{})<br>let p1 = Promise.resolve(1)<br>let p2 = Promise.reject(2)<br>console.log(&quot;Before calling Promise.all&quot;, p0, p1, p2)<br>let pa = <strong>Promise.all</strong>([p0, p1, p2, 3, undefined])<br>console.log(&quot;After calling Promise.all&quot;, pa)<br>pa.then(v=&gt;console.log(pa, v), e=&gt;console.log(pa, e))</pre><p>The above code gives the following output:</p><pre>Before calling Promise.all Promise { &lt;pending&gt; } Promise { 1 } Promise { &lt;rejected&gt; 2 }<br>After calling Promise.all Promise { &lt;pending&gt; }<br>Promise { &lt;rejected&gt; 2 } 2</pre><p>Note that pa is in rejected state even though p0 is never settled.</p><p><strong>Promise.allSettled(iterable)</strong> is very similar to Promise.all(iterable) described above. The difference is that the returned promise of Promise.allSettled keeps pending until all of the promises in the list are settled. Once the returned promise of Promise.allSettled is settled, it is always in <strong>fulfilled</strong> state, even in the case that every single promise in the input list is rejected.</p><pre>let p1 = Promise.reject(1)<br>let p2 = Promise.reject(2)<br>console.log(&quot;Before calling Promise.all&quot;, p1, p2)<br>let pa = <strong>Promise.allSettled</strong>([p1, p2])<br>console.log(&quot;After calling Promise.all&quot;, pa)<br>pa.then(v=&gt;console.log(pa))</pre><p>The above code gives the following output:</p><pre>Before calling Promise.allSettled Promise { &lt;rejected&gt; 1 } Promise { &lt;rejected&gt; 2 }<br>After calling Promise.allSettled Promise { &lt;pending&gt; }<br>Promise {<br>  [<br>    { status: &#39;rejected&#39;, reason: 1 },<br>    { status: &#39;rejected&#39;, reason: 2 }<br>  ]<br>}</pre><p>Note that the returned promise pa is in fulfilled state even though both p1 and p2 are rejected. The value of the promise <strong>pa</strong> is a list of objects indicating the status of the input promises and their values (in case of fulfilled promises) or reasons (in case of rejected promises).</p><p><strong>Promise.any(iterable)</strong> returns a single promise that is initially pending. If any promise in the input list is fulfilled, the returned promise is fulfilled and gets the first resolved value.</p><p><strong>Promise.race(iterable)</strong> is similar to Promise.any(iterable). The difference is that once any promise in the input list of Promise.race is settled (fulfilled or rejected), the returned promise is settled with the same state and the same value.</p><h4>Promises are Everywhere</h4><p>Once you understand how Promise works, you would find yourself glide through a lot of modern APIs. For example, the Web API fetch() returns a promise that resolves to the response of a web request. In NodeJS, asynchronous IO operations often return promises. For example, readFile method of a file handle object returns a promise that is fulfilled upon a successful read of the contents of the file. Using promises to wrap asynchronous tasks are very prevalent in many modern JavaScript code base. Promises forever change the structure of JavaScript programs in that code that produces results or exceptions gets decoupled with code that consumes results or handles errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eff5c7e9139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Good and Bad of JavaScript Callbacks]]></title>
            <link>https://medium.com/bitsrc/the-good-and-bad-of-javascript-callbacks-dc6dffc21519?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc6dffc21519</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 02:38:51 GMT</pubDate>
            <atom:updated>2022-03-16T15:32:54.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mvUVN267AIa4yRw.png" /></figure><p>Callbacks are <strong><em>functions</em></strong> that are called back later. If you think I didn’t explain anything in the previous sentence, I did emphasize one important identity of a callback — a function. The callback function — including its references — is passed as an argument to other functions. The functions that receive the callback function as a parameter are the ones responsible to call back the callback function. Callbacks are great because they open up a lot of programming possibilities.</p><h4>Synchronous Callbacks</h4><p>Many people, especially those who are old school, had their first encounter with callbacks when they learned that different comparison functions can be supplied to the same sorting algorithm. For example, when using the Array.prototype.sort() method to sort an array of integers, an optional parameter is the comparison function compareFn.</p><pre><strong>let arr1 = [22, 25, 55, 66, 23, 15, 1, 12]</strong><br><strong>arr1.sort()</strong> // arr1 is sorted in ascending order<br>// arr1 becomes [1, 12, 15, 22, 23, 25, 55, 66]<br><strong>let arr2 = […arr1]</strong> // deep copy arr1 to arr2<br><strong>arr2.sort((e1, e2)=&gt; e2-e1)</strong> // arr2 is sorted in descending order<br>// arr2 becomes [66, 55, 25, 23, 22, 15, 12, 1 ]<br>// (e1, e2)=&gt; e2-e1 is the comparison function</pre><p>This type of callbacks are available in most programming languages, achieving the effect of <strong>polymorphic</strong> algorithms.</p><p>The above illustrates how <strong>synchronous</strong> callbacks work. Synchronous callbacks are executed inside the high-order functions that use them. When the high-order function is done executing, execution of its callback arguments also completes. Since the high-order function has to wait for the completion of synchronous callback execution, synchronous callbacks are also referred to as blocking callbacks — the execution of callbacks block the execution of their caller functions.</p><p>Some additional examples of synchronous callbacks in JavaScript are methods for iterating <strong>arrays</strong>: forEach, map, filter, reduce, some, every , etc.</p><pre>let arr = [1,2,3,4,5]<br>let arrDoubled = arr.map(e=&gt;e+e)<br>console.log(arrDoubled) // output [ 2, 4, 6, 8, 10 ]</pre><h4>Asynchronous Callbacks</h4><p>If synchronous callbacks are ways to achieve greater programming flexibility, then <strong>asynchronous</strong> callbacks are ways to achieve greater performance and user experience. The power of asynchronous callbacks lie in JavaScript’s unique runtime model. JavaScript is a single threaded language, meaning that the execution engine of JavaScript only has one call stack.</p><p>Then how does asynchronous execution achieved?</p><p>The magic is in the API handlers of the JavaScript runtime environment. In the case of web browsers, the APIs are the web APIs; in the case of Node.js, the APIs are the I/O APIs. Tasks of executing asynchronous callbacks are put into the <strong>callback queue</strong>.</p><p>After existing code in the call stack runs to its completion, <strong>event loop</strong> — a process that is part of the JavaScript engine — brings the callbacks in the callback queue to execution.</p><p>Once a callback is run by the execution engine, it is again <strong>run to its completion</strong> (until the call stack is empty) before the next callback starts to run. This <strong>run-to-completion</strong> for code on the call stack continues until all the callbacks in the queue are executed.</p><p>The asynchronous aspect comes from the fact that a callback is not executed immediately in the high order function, but is put in the callback queue to wait for its turn to be run on the call stack.</p><p>The high order function is the one to dispatch the callback task, but not the one to run it.</p><p>The most prevalent example of using an asynchronous callback is using the setTimeOut method.</p><pre>console.log(&quot;before setTimeout&quot;)<br>setTimeout(<br>    ()=&gt;{ console.log(&quot;result is here after 2 seconds&quot;) },<br>    2000<br>)<br>console.log(&quot;after setTimeout&quot;)</pre><p>This method is in the global object window in the case of browsers and global in the case of Node.js.</p><p>The first parameter is the callback function, the second parameter is the time to wait in milliseconds. setTimeout does not need to wait for the callback to complete before it returns.</p><p>Here is how the output looks like:</p><pre>before setTimeout<br>after setTimeout<br>result is here after 2 seconds</pre><p>The benefit of the asynchronous callback mechanism is that all the synchronous code is not blocked by asynchronous events. Asynchronous events (e.g. AJAX requests to remote servers) potentially can take some time to run. Web applications can run more smoothly and responsively with asynchronous callbacks.</p><h4><strong>Callback Hell</strong></h4><p>You must have heard the term “callback hell” before. It sounds scary, but in reality is just aesthetically not that appealing and functionally prone to error and hard to debug and maintain.</p><p>Imagine an e-commerce web application. One of the functions provided by the website is to obtain detailed history of order information for the given customer. There are several steps needed to obtain the required information:</p><ol><li>Get the user information.</li><li>Get the list of order IDs for the user</li><li>Get the list of products for each order</li><li>Compile the information obtained in the previous steps into a report</li></ol><p>Translate into code — callback hell style:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729aae3c4d506061bf6df18f56819328/href">https://medium.com/media/729aae3c4d506061bf6df18f56819328/href</a></iframe><p>Note that setTimeout is used to simulate querying databases to get the corresponding data. The indented callbacks here may not seem to be too bad, but in practice the level of callbacks can reach to a much bigger number. With the presence of other control logic and error handling, the code for sure will go out of the screen.</p><h4>There is Always Promise</h4><p>To address the problem described in the previous section, ES6 introduced Promise as JavaScript’s first level constructor, just like String, Date, Array, etc.</p><p>Here is how to use promises to resolve the callback hell issue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/831c1c52a10cb54b1eeae7e1c6a642a7/href">https://medium.com/media/831c1c52a10cb54b1eeae7e1c6a642a7/href</a></iframe><p>Note how the asynchronous requests to the databases (simulated with setTimeout) are wrapped inside a Promise constructor.</p><p>Also note that for getUserInfo, getOrderInfo, getProductInfo functions, callbacks are no longer needed.</p><p>In the end, each step returns a Promise object and the results are chained through the then methods.</p><p>All the steps become a vertical chain of promises versus a horizontal stretch of callbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*lltbol80lbEN51mr8tygbw.png" /><figcaption>Promise Comes to the Rescue of the Callback Hell</figcaption></figure><p>Stay tuned for my next article explaining the details of Promise and its inner workings.</p><h3>Build composable web applications</h3><p>Don’t build web monoliths. Use <a href="https://bit.dev/">Bit</a> to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.</p><p>Bring your team to <a href="https://bit.cloud/">Bit Cloud</a> to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try <strong>composable frontends</strong> with a <strong>Design System</strong> or <strong>Micro Frontends</strong>, or explore the <strong>composable backend </strong>with<strong> serverside components</strong>. <a href="https://bit.dev/"><strong>Give it a try →</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ctBUj-lpq4PZpMcEF-qB7w.gif" /></figure><h3>Learn More</h3><ul><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://blog.bitsrc.io/the-composable-enterprise-a-guide-609443ae1282">The Composable Enterprise: A Guide</a></li><li><a href="https://blog.bitsrc.io/7-tools-for-faster-frontend-development-in-2022-43b6f663c607">7 Tools for Faster Frontend Development in 2022</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc6dffc21519" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/the-good-and-bad-of-javascript-callbacks-dc6dffc21519">The Good and Bad of JavaScript Callbacks</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never Feel Insecure About Thread Safety Again]]></title>
            <link>https://medium.com/@daijue/never-feel-insecure-about-thread-safety-again-8827d5ee234a?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/8827d5ee234a</guid>
            <category><![CDATA[thread-safe]]></category>
            <category><![CDATA[java-multithreading]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 17:55:27 GMT</pubDate>
            <atom:updated>2022-02-18T17:55:27.551Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to feel very insecure when it comes to the topic of thread safety. Thread, by itself, is already an intimidating concept. (<a href="https://medium.com/@daijue/get-threads-created-and-running-in-java-c6ce4a3e35be">This article</a> hopefully can help make the concept of thread more approachable.) Adding the word “safety” to thread does not help. It sounds an even more daunting topic and leaves one feel a bit — unsafe. As if talking about thread safety is not enough, people begin to throw words like “race condition”, “critical section”, “atomicity”, “immutability”, “mutual exclusion”, “locks”, “lock-free data structures”, and so on, in the context of thread safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*w6deRsqqgPLqycMbh_83Lg.png" /><figcaption>Thread Safety by Daijue Tang</figcaption></figure><p>Anyone in search for an understanding of thread safety deserves better explanations. Thus, I am dedicating this writing to those who strove to understand, yet may still be confused about, a topic that once triggered much anxiety in me — <strong>thread safety</strong>.</p><p>Although the code in this writing is in Java, the concepts are universal in other programming languages and anyone who has some experience in object oriented programming should be able to understand most of it.</p><h4>How Can Threads Be Unsafe?</h4><p>An understanding of thread safety begins with a glimpse of how unsafe threads can be.</p><p>Imagine two threads, both have access to an integer counter. One thread tries to increment the counter in a loop, while the other thread tries to decrement the counter in a loop. Both threads operate on the counter the same number of times. If the counter starts with zero, one would expect that after both threads are done, the counter would remain zero.</p><pre>static int counter = 0; // counter is a class variable <br>                        // shared by threads<br>...</pre><pre>Thread t1 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter++;<br>    }<br>}); // thread t1 increments the counter 5000 times</pre><pre>Thread t2 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter--;<br>    }<br>}); // thread t2 decrements the counter 5000 times</pre><pre>t1.start();           // start running thread t1<br>t2.start();           // start running thread t2<br>t1.join();            // wait for t1 to finish<br>t2.join();            // wait for t2 to finish</pre><pre>System.out.println(counter); // output may not be 0</pre><p>In an unpredictable world of concurrent programming, the last line of the above code segment may or may not output zero. The above code segment is said to be <strong>thread unsafe</strong> exactly because of this nature of not being deterministic. There will be no concern about thread safety if the output is always zero.</p><p>The culprit of making the code not thread safe lies in two lines of seemingly innocent code: counter++ and counter--. Do not be deceived by their simplistic looking. When these two statements are compiled into Java bytecode (or machine code for pure compiled languages such as C++), they each become multiple statements. Here is how counter++ looks like when compiled into Java bytecode:</p><pre>getstatic     #12     // load the value of counter onto the stack<br>                      // counter is identified by index 12<br>iconst_1              // load the int value 1 onto the stack<br>iadd                  // add two ints on the stack and pop them out                   <br>                      // push the result onto the stack<br>putstatic     #12     // pop the result from the stack <br>                      // set it as value for counter (indexed by 12)</pre><p>counter-- looks similar except that iadd is changed to isub. When the Java Virtual Machine (JVM) and the underlying processor execute these instructions, instructions from different threads can be <strong>interleaved</strong>, because the operating system tries to execute instruction sequences for different threads concurrently. Here is a possible interleaving in the case of the counter example:</p><pre><strong>Thread t1 (counter++)             Thread t2 (counter--)</strong></pre><pre>getstatic     #12     <br>iconst_1              <br>iadd<br>                                  getstatic     #12<br>                                  iconst_1<br>                                  isub                 <br>putstatic     #12     <br>                                  putstatic     #12</pre><p>Suppose the value of counter starts with 0. After thread <em>t1</em> load the value of counter and added<em> </em>1 to it, just before thread <em>t1</em> is about to set the value of counter to be 1, thread <em>t2</em> gets its turn to run and load the value of counter (which is still 0 since <em>t1</em> has not changed it yet), calculates counter-1 and pushes the result -1 onto its own stack (note that each thread has its own stack). At exactly this moment, the scheduler decides that it is now thread <em>t1</em>’s turn to run and executes the instruction of putstatic which sets the value of counter to be 1. After that, it is thread <em>t2</em>’s turn and its putstatic instruction sets the value of counter to be -1. This is the defining moment for violating thread safety. After thread <em>t1</em> incremented the counter and thread <em>t2</em> decremented the counter, the counter should be still be 0! In this case, however, the value of counter mysteriously becomes<em> </em>-1!</p><h4>The Root Causes for Violating Thread Safety</h4><p>Whenever there are multiple threads, the exact sequences for thread execution are entirely up to the scheduler and programmers have little control. This means that there is no way to predict how the machine instructions will be interleaved. This condition that the program output or end state is dependent upon its uncontrollable sequences of execution is called a <strong>race condition</strong>.</p><p>The presence of concurrency alone does not necessarily cause race conditions. Independent threads, each minds its own business, having <strong>no shared data</strong> among them, can peacefully coexist without raising concerns about thread safety. Problems start to arise when they start to <strong>share data</strong>. In real life situations, sharing is often associated with positive feelings. Not in the world of concurrent programming! One of the root causes for violating thread safety in the case of the counter example is that both thread <em>t1</em> and thread <em>t2</em> manipulate a <strong>shared variable</strong> counter. In fact, if both threads only try to <strong>read</strong> counter, there will not be any problem at all. But if one or both threads start to <strong>write</strong> to the <strong>shared variable</strong>, <strong>race conditions</strong> start to appear.</p><p>Why <strong>sharing</strong> is bad then, when a thread is only trying to make changes to common resources? Well, the truth is that a thread can make changes (write) to common data, as long as the thread does that in an <strong>atomic</strong> way, isolated from other threads. The section of code that can cause race conditions and must be executed in a <strong>mutual exclusive</strong> way is called <strong>critical section</strong>. In the counter example, counter++ and counter--are both <strong>critical sections</strong> that must be executed <strong>atomically</strong> in order to ensure thread safety.</p><h4><strong>Ways to Achieve Thread Safety</strong></h4><p>Every approach that can achieve thread safety directly or indirectly targets the problem of <strong>sharing</strong> and strives for <strong>atomicity</strong> in critical sections. The solutions for thread safety can be roughly divided into the following four categories.</p><ol><li><strong>No sharing.</strong></li></ol><p>To prevent sharing, each thread can make sure that all the data it makes changes to are local to that thread. Since each thread has its own stack, other threads cannot access its local data. In the spirit of no sharing, here is how to make the two threads in the earlier example do their independent counting and aggregate their results when they are done:</p><pre>FutureTask&lt;Integer&gt; task1 = new FutureTask&lt;&gt;(<br>    () -&gt; {<br>        int counter = 0;<br>        for (int i = 0; i &lt; 5000; i++) {<br>            counter++;<br>        }<br>        return counter;<br>     }<br>);<br>FutureTask&lt;Integer&gt; task2 = new FutureTask&lt;&gt;(<br>    () -&gt; {<br>        int counter = 0;<br>        for (int i = 0; i &lt; 5000; i++) {<br>            counter--;<br>        }<br>        return counter;<br>    }<br>);<br>Thread t1 = new Thread(task1);    <br>Thread t2 = new Thread(task2);<br>t1.start(); // start to run thread t1<br>t2.start(); // start to run thread t2<br>int counter1 = task1.get(); // get the result from thread t1<br>int counter2 = task2.get(); // get the result from thread t2<br>int counter = counter1+counter2; // aggregate the final result<br>System.out.println(counter); // output must be 0</pre><p>If you feel perplexed by the use of FutureTask in the above code, details are provided <a href="https://medium.com/me/stats/post/c6ce4a3e35be">here</a>. In a nutshell, a FutureTask object can be passed as an argument to the Thread constructor so that the result of the thread run can be obtained by calling the get() method of FutureTask. Here both threads operate on their own local counter variable, making their counting operations isolated from each other. Thus, thread safety is achieved through localization and confinement.</p><p><strong>2. Mutual Exclusion</strong></p><p>If sharing is unpreventable, then the shared resources have to be accessed in a mutual exclusive way to ensure thread safety. Mutual exclusion is usually achieved by using some type of lock entities. Before entering the critical section, a lock needs to be acquired (locked). Upon exiting the critical section, the same lock needs to be released (unlocked). At any point in time, only one thread can lock the critical section, accessing the shared data.</p><p>In Java, the most common type of lock is the intrinsic lock on an object, also known as the <strong>monitor lock</strong>. Locking and unlocking are implicitly achieved by wrapping the critical section inside a <strong>synchronized</strong> block. The monitor lock is acquired before entering the synchronized block and released upon exiting the synchronized block. If another thread is trying to enter a synchronized block locked by the same monitor lock, it has to wait until the lock is release and reenter the competition for acquiring the lock. Here is how to use synchronized blocks to ensure thread safety in the earlier example of <em>counter</em>:</p><pre>static int counter = 0;<br>...<br>static Object obj = new Object();</pre><pre>Thread t1 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        <strong>synchronized</strong>(obj) {<br>            counter++; <br>        }<br>    }<br>}); // thread t1 increments the counter 5000 times</pre><pre>Thread t2 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        <strong>synchronized</strong>(obj) {<br>            counter--; <br>        }<br>    }<br>}); // thread t2 decrements the counter 5000 times</pre><pre>t1.start();           // start running thread t1<br>t2.start();           // start running thread t2<br>t1.join();            // wait for t1 to finish<br>t2.join();            // wait for t2 to finish</pre><pre>System.out.println(counter); // output must be 0</pre><p>Note how counter++ and counter--are protected by the same monitor lock associated with the obj object.</p><p><strong>3. Atomic Variables</strong></p><p>Atomic variables are often said to be a lock-free way to achieve thread safety. Operations that access and update atomic variables are guaranteed to be atomic because of the use of special compare-and-set (CAS) machine instructions. Atomic variables are more performant than mutual exclusion locks because they eliminate the need for context switching. When using locks, threads have to be constantly switched between the running state and the blocking state, which involves suspending and saving a thread’s status before resuming another thread. In a nutshell, context switching is expensive! Thus, atomic variables are often harnessed in performance sensitive multi-threaded applications.</p><p>In Java, the java.util.concurrent.atomic package provides a set of different atomic variable types. Other programming languages such as C++ and GoLang also provide similar constructs. Here is how to use AtomicInteger in the earlier example of <em>counter</em>:</p><pre>static AtomicInteger counter = new AtomicInteger(0);<br>...<br>Thread t1 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter.incrementAndGet(); <br>    }<br>}); // thread t1 increments the counter 5000 times<br>Thread t2 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter.decrementAndGet(); <br>    }<br>}); // thread t2 decrements the counter 5000 times<br>t1.start();           // start running thread t1<br>t2.start();           // start running thread t2<br>t1.join();            // wait for t1 to finish<br>t2.join();            // wait for t2 to finish<br>        <br>System.out.println(counter.get()); // output must be 0</pre><p>Note that the variable counter is initialized to 0. The methods incrementAndGet and decrementAndGet are both atomic operations that are executed sequentially in their entirety in one shot.</p><p><strong>4. Immutability</strong></p><p>An object being immutable means that it cannot be changed after it is constructed. Immutable objects are thread safe because no thread can change its internal status after construction. All threads can only do read-only operations on the immutable objects.</p><p>In Java, some library classes such as String and primitive wrapper classes (Integer, Long, Float, Boolean, etc.) are immutable. However, there is one big caveat concerning using objects of these immutable classes as a thread safe guarantee. For example, here is the <strong>wrong</strong> way to achieve thread safety:</p><pre>static <strong>Integer</strong> counter = 0; // counter is a class variable <br>                        // shared by threads<br>...</pre><pre>Thread t1 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter++;<br>    }<br>}); // thread t1 increments the counter 5000 times</pre><pre>Thread t2 = new Thread(()-&gt;{<br>    for (int i = 0; i &lt; 5000; i++) {<br>        counter--;<br>    }<br>}); // thread t2 decrements the counter 5000 times</pre><pre>t1.start();           // start running thread t1<br>t2.start();           // start running thread t2<br>t1.join();            // wait for t1 to finish<br>t2.join();            // wait for t2 to finish</pre><pre>System.out.println(counter); // output may not be 0</pre><p>As you can see, I have changed the first line, making counter a boxed type. Since Integer is an immutable type, it is easy for one to derive that counter is immutable too and thus erroneously think that changing counter from int type to Integer type would make the code thread safe. This incorrect thinking stems from its failure to realize that an Integer object is immutable, but its <strong>reference</strong> is not! counter is a <strong>reference</strong> to an Integer object. To make the <strong>reference</strong> immutable, we have to declare it as final. If counter is final, counter++ and counter--are no longer allowed. So we assign counter to local variables of threads and use FutureTask to obtain the counting result from each thread:</p><pre>static <strong>final Integer</strong> counter = 0; // counter is a class variable <br>                        // shared by threads<br>...<br>FutureTask&lt;Integer&gt; task1 = new FutureTask&lt;&gt;(<br>    () -&gt; {<br>        Integer counter1 = counter;<br>        for (int i = 0; i &lt; 5000; i++) {<br>            counter1++;<br>        }<br>        return counter1;<br>     }<br>);<br>FutureTask&lt;Integer&gt; task2 = new FutureTask&lt;&gt;(<br>    () -&gt; {<br>        Integer counter2 = 0;<br>        for (int i = 0; i &lt; 5000; i++) {<br>            counter2--;<br>        }<br>        return counter2;<br>    }<br>);<br>Thread t1 = new Thread(task1);    <br>Thread t2 = new Thread(task2);<br>t1.start(); // start to run thread t1<br>t2.start(); // start to run thread t2<br>int counter1 = task1.get(); // get the result from thread t1<br>int counter2 = task2.get(); // get the result from thread t2<br>int result = counter1+counter2; // aggregate the final result<br>System.out.println(result);   // output must be 0<br>System.out.println(counter);  // output must be 0</pre><p>As long as references to immutable objects are made final, one can rest assured that there will be no thread safety issues on these immutable objects.</p><h4>Safety First, Then Come the Benefits</h4><p>If you have read this far, I hope you have a clearer mind about thread safety now. Thread safety is crucial in concurrent programming. Thread safety errors are hard to debug and reproduce. Fortunately, a variety of tools and data structures exist to help us ensure thread safety, so we can enjoy the benefits of better performance and resource utilization provided by concurrent programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8827d5ee234a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods to Inspect and Control Java Threads]]></title>
            <link>https://medium.com/@daijue/methods-to-inspect-and-control-java-threads-f602c26cb885?source=rss-f0af16954026------2</link>
            <guid isPermaLink="false">https://medium.com/p/f602c26cb885</guid>
            <category><![CDATA[java-thread]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <dc:creator><![CDATA[Daijue]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 18:30:28 GMT</pubDate>
            <atom:updated>2022-02-15T18:30:28.618Z</atom:updated>
            <content:encoded><![CDATA[<p>The word <strong><em>thread</em></strong> in computer science comes from the phrase “a thread of execution”, which basically defines the meaning of thread in the context of computing. Thus, it is no surprising that in Java the class representing threads is called <strong><em>Thread</em></strong>. <strong><em>Thread</em></strong> is the essential class in Java if you want to do any type of Java concurrent programming. The <strong><em>Thread</em></strong> class contains important methods to manipulate objects of <strong><em>Thread</em></strong>. This article will present not just what the methods do, but also how to use them to maneuver your threads through a naturally unpredictable world of concurrency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*C1m0HZ9s16Ob0T8sg9jt1w.png" /><figcaption>Methods for Threads</figcaption></figure><h4>start() vs. run()</h4><p>As a multi-threading programmer, you defines run behavior of the threads and starts the threads by calling start. Let me explain. The <em>run()</em> method is defined in the <em>Thread</em> class as follows:</p><pre>public class Thread implements Runnable {<br>    ...<br>    private Runnable target;<br>    ...<br>    @Override<br>    public void run() {<br>        if (target != null) {<br>            target.run();<br>        }<br>    }<br>    ...<br>}</pre><p>If a <em>Runnable</em> object is passed to the <em>Thread</em> constructor, then the variable <em>target</em> is set to the <em>Runnable</em> object. In this case, <em>Thread</em> <em>run()</em> method calls the <em>target</em> <em>run()</em> method. Otherwise, <em>Thread</em> <em>run()</em> method does nothing. Thus, in order for your thread to do something meaningful, you can either extend <em>Thread</em> and override the <em>run()</em> method or implement the <em>Runnable</em> <em>run()</em> method and pass a <em>Runnable</em> object to <em>thread</em> constructor. This is what I meant to define the behavior of threads. Details are also provided in the article of <a href="https://medium.com/@daijue/get-threads-created-and-running-in-java-c6ce4a3e35be"><strong><em>Get Threads Created and Running in Java</em></strong></a>.</p><p>Note that even if you defined the <em>run()</em> method, you are not the one to call it. The code below does not execute the <em>run()</em> method in another thread, it is executed in the exact same thread that calls it:</p><pre>Thread myThread = new Thread() {<br>    @Override<br>    public void run() {<br>        ... // code intended to run in another thread<br>    }<br>};<br>myThread.run(); // running the code in current thread, not intended!</pre><p>Who calls <em>run()</em> then? The short answer is Java Virtual Machine (JVM). The long answer is that once the <em>start()</em> method is called on the thread object, JVM starts to execute the thread and calls its <em>run()</em> method. In another words, <em>start()</em> is the method that is actually used to start a new thread and make it run.</p><pre>Thread myThread = new Thread() {<br>    @Override<br>    public void run() {<br>        ... // code intended to run in another thread<br>    }<br>};<br>myThread.start(); // starts the thread and make the code in run()<br>                  // execute in the new thread</pre><h4>Names for Threads</h4><p>If you do not give your threads names, names are given by default. Default names are in the form of <em>Thread-i</em>, where <em>i</em> is an integer starting from 0. So you will see <em>Thread-0</em>, <em>Thread-1</em> etc. as default thread names.</p><p>If you are not satisfied with the default names, you can name your thread in two ways:</p><ol><li>Using the parameter of the <em>Thread</em> constructors. For example, the constructors <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread(java.lang.String)"><strong>Thread</strong></a>(<a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html">String</a> name) and <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread(java.lang.Runnable,%20java.lang.String)"><strong>Thread</strong></a>(<a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html">Runnable</a> target, <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html">String</a> name) can both be used to give names to threads.</li></ol><pre>Thread myThread = new Thread(&quot;MyAwesomeThread&quot;) {<br>    @Override<br>    public void run() {<br>        ... // code intended to run in another thread<br>    }<br>};</pre><p>2. Using the <em>setName()</em> Method. After the Thread object is constructed, a name can be given by using the <em>setName()</em> method:</p><pre>Thread myThread = new Thread() {<br>    @Override<br>    public void run() {<br>        ... // code intended to run in another thread<br>    }<br>};<br>myThread.setName(&quot;MyAwesomeThread&quot;);</pre><p>Thread names can be obtained using the <em>getName()</em> method.</p><h4>Priorities for Threads</h4><p>You, as a programmer, can determine when to start a thread by calling the <em>start()</em> method. After that, when a thread actually gets to run on CPU is out of your control. On a regular machine, there will always be many processes and threads ready to run. The operating system scheduler determines which thread has the right to use CPU at which time slice. A higher priority thread usually has a better chance to use the CPU than a lower priority thread. However, the OS scheduler is like a teenager kid, do not even think about controlling it, the best you can do is to give your opinions. Setting priorities for threads is simply a suggestion to the scheduler, the scheduler may or may not consider it.</p><p>In the <em>Thread</em> class, a value between 1–10 is used to indicate the priority of a thread:</p><pre>// The minimum priority that a thread can have.<br>public static final int MIN_PRIORITY = 1;<br>// The default priority that is assigned to a thread.<br>public static final int NORM_PRIORITY = 5;<br>// The maximum priority that a thread can have.<br>public static final int MAX_PRIORITY = 10;</pre><p>A thread’s priority can be set using the <em>setPriority()</em> method and obtained using the <em>getPriority()</em> method.</p><h4><em>States for Threads</em></h4><p>From the JVM perspective, a thread can be in one of the six states at any point of its life. The states are defined in the <em>Thread</em> class as follows:</p><pre>public enum State {<br>        NEW,<br>        RUNNABLE,<br>        BLOCKED,<br>        WAITING,<br>        TIMED_WAITING,<br>        TERMINATED;<br>}</pre><p>To obtain the state of a thread, use the <em>getState()</em> method.</p><p>When a Thread object is created yet not started, it is in a <strong>NEW</strong> state:</p><pre>Thread t = new Thread(()-&gt;{ ... });<br>System.out.println(t.getState()); // output NEW</pre><p>Once the <em>start()</em> method is called, it is in <strong>RUNNABLE</strong> state:</p><pre>Thread t = new Thread(()-&gt;{<br>    while(true) { ... }<br>});<br>t.start();<br>System.out.println(t.getState()); // output RUNNABLE</pre><p>A thread that has completed execution is in <strong>TERMINATED</strong> state:</p><pre>Thread t = new Thread(()-&gt;{<br>    ... // something that takes less than 1 second to run<br>});<br>t.start();<br>Thread.sleep(1000); // current thread goes to sleep for 1 second<br>System.out.println(t.getState()); // output TERMINATED</pre><p>When a thread is in <strong>WAITING</strong> state, it is waiting for an action from another thread. Calling one of the methods of <em>Object.wait()</em>, <em>Thread.join()</em>, <em>LockSupport.park()</em> can put a thread into the <strong>WAITING</strong> state. When a thread calls the<em> wait()</em> method on an Object, it is waiting for another thread to call <em>notify()</em> or <em>notifyAll()</em> on the same Object. When a thread calls the <em>join() </em>method on a thread object <em>t</em>, it is waiting for that thread <em>t</em> to terminate. When a thread is in the <strong>WAITING</strong> state due to a call to <em>LockSupport.park()</em>, then a corresponding <em>LockSupport.unpark()</em> method can bring the thread back to the <strong>RUNNABLE</strong> state. Below is an example of a thread <em>t2</em> waiting for a thread <em>t1</em> to complete:</p><pre>Thread t1 = new Thread(()-&gt;{ <br>    ... // do something for a while<br>});<br>t1.start();<br>Thread t2 = new Thread(()-&gt;{<br>    try {<br>        t1.join(); // wait for t1 to complete<br>    } catch (InterruptedException e) {<br>        e.printStackTrace();<br>    }<br>});<br>t2.start();<br>Thread.sleep(1000); // wait for both threads to run a bit<br>System.out.println(t2.getState()); // output WAITING</pre><p>When a thread is waiting for an action from another thread, but only up to a specified amount of time, then the thread is in <strong>TIMED_WAITING</strong> state. Calling one of the methods of <em>Thread.sleep(long millis), Thread.sleep(long millis, int nanos), Object.wait(long timeout)</em>, <em>Object.wait(long timeout, int nanos), Thread.join(long millis)</em>, <em>Thread.join(long millis, int nanos), LockSupport.parkNanos(long nanos), LockSupport.parkUntil(long deadline)</em>, can put a thread into the <strong>TIMED_WAITING</strong> state. Below is an example of a thread <em>t1</em> in <strong>TIME_WAITING</strong> state due to going to sleep for 5 seconds:</p><pre>Thread t1 = new Thread(()-&gt;{<br>    try {<br>        Thread.sleep(5000); // t1 goes to sleep for 5 seconds<br>    } catch (InterruptedException e) {<br>        e.printStackTrace();<br>    }<br>});<br>t1.start();<br>Thread.sleep(1000); // let t1 fall into sleep then check t1’s state<br>System.out.println(t1.getState()); // output TIMED_WAITING</pre><p>When a thread is waiting to enter a synchronized block/method, it is said to be blocked by a monitor lock, thus it is in <strong>BLOCKED</strong> state. In the code below, thread <em>t1</em> gets to start first and hold the monitor lock for <em>o</em>. Before <em>t1</em> wakes up from its 5 seconds sleep, thread <em>t2</em> cannot get the same monitor lock for o and has to be in BLOCKED state:</p><pre>Object o = new Object();<br>Thread t1 = new Thread(()-&gt;{<br>    synchronized(o) {<br>        try {<br>            Thread.sleep(5000);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>});<br>t1.start();<br>Thread t2 = new Thread(()-&gt;{<br>    synchronized(o) {}<br>});<br>t2.start();<br>Thread.sleep(1000);<br>System.out.println(t2.getState()); // output BLOCKED</pre><p>Note that <em>Thread.sleep()</em> method does not release the monitor lock even though it does not use CPU and simply idles. What a waste, isn’t it?</p><h4>Thread Interruption</h4><p>When you set off a thread to go free running, you always have the power to interrupt what the thread is doing by using the <em>interrupt()</em> method. Thread interruption in Java is done in a really gentle way. No matter what the target thread is doing, it always has an elegant way out.</p><p>Imagine while the target thread is crunching some hard numbers diligently, another thread, thinking the target thread has worked for an unreasonably long time and should be interrupted, calls the <em>interrupt()</em> method on the target thread. This interruption, however, is more like a reminder. What the interrupting thread does is to set an internal flag called the <em>interrupt status</em>. The interrupted thread can check its <em>interrupt status</em> by using either the <em>isInterrupted()</em> method or the <em>interrupted()</em> method (the difference is that the <em>isInterrupted()</em> method will not clear the<em> interrupt status </em>while the <em>interrupted()</em> method will reset the<em> interrupt status </em>to false). It is actually entirely up to the interrupted thread to determine what to do if it finds out that the flag for<em> interrupt status</em> is set. Usually the interrupted thread does some cleaning up work before it terminate itself. Below is an example of how to interrupt a running thread:</p><pre>Thread t1 = new Thread(()-&gt; {<br>    while (true) {<br>        if (Thread.currentThread().<strong>interrupted</strong>()) {<br>            ... // clean up a bit before breaking from the loop<br>            break;<br>        }<br>        ... // crunch some numbers<br>    }<br>});<br>Thread.sleep(5000);<br>t1.<strong>interrupt</strong>();</pre><p>In the above, thread <em>t1</em> is allowed to constantly crunch number in a loop for 5 seconds before it finds out about being interrupted and exits the loop. Note the kind of freedom <em>t1</em> is given to handle its own fate in case of an interruption.</p><p>Interruption can also be given to a waiting thread — a thread that is blocked by calling one of the <em>wait()</em>, <em>join()</em>, <em>sleep()</em> methods (including the versions with parameters for duration of time). In this case, an invocation of the <em>interrupt()</em> method on the waiting target thread causes it to receive an <em>InterruptedException</em>. In addition, the <em>interrupt status</em> flag is reset to false. For this reason, when an <em>InterruptedException</em> is caught by a waiting thread, it is usually a good idea to invoke the <em>interrupt()</em> method again to set the <em>interrupt status</em>, making the next check for <em>isInterrupted() </em>return true. This pattern is what is known as <strong>two phase termination</strong>, as illustrated in the code below:</p><pre>Thread t1 = new Thread(()-&gt; {<br>    while (true) {<br>        if (Thread.currentThread().<strong>isInterrupted</strong>()) {<br>           ... // clean up a bit<br>           break;<br>        }<br>        ... // do this every second<br>        try {<br>            Thread.sleep(1000);<br>        } catch (<strong>InterruptedException</strong> e) {<br>            // without the following line, cannot break from the loop<br>            Thread.currentThread().<strong>interrupt</strong>(); // IMPORTANT!<br>        }<br>    }<br>});<br>Thread.sleep(5000);<br>t1.<strong>interrupt</strong>();</pre><h4><strong>Join a Thread Means Wait for Its Termination</strong></h4><p>There are three versions of the thread join methods:<em> join()</em>, <em>join(long millis)</em>, <em>join(long millis, int nanos)</em>. The ones with the parameters specify the time to wait before the join methods return. If <em>join() </em>is called with no parameter or the parameters are set to zero, the wait time is forever. The <em>join</em> methods return either when the wait time has passed or when the target thread has ended, whichever occurs earlier.</p><p>Internally in the implementation, the <em>join</em> methods call the <em>wait</em> methods and the <em>isAlive</em> methods of the thread instances in a loop where <em>wait</em> waits for the <em>isAlive</em> condition. Therefore, applications are not recommended to use <em>wait</em>, <em>notify</em>, <em>notifyAll </em>methods on thread instances.</p><h4>sleep() vs yield()</h4><p>Both the <em>sleep()</em> method and the<em> yield()</em> method express their willingness of not using the processor. However, <em>sleep()</em> is the more sincere one since it truly ceases execution for the specified amount of time, freeing the processor. On the other hand, <em>yield()</em> is more like a gesture of being polite. It gives hint to the scheduler about its willingness to yield its current use of the processor. It is still up to the scheduler to decide whether or not to schedule the yielding thread for the next time slice of processor usage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f602c26cb885" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>