<?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 Srini on Medium]]></title>
        <description><![CDATA[Stories by Srini on Medium]]></description>
        <link>https://medium.com/@srimeda?source=rss-1890041237f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Srini on Medium</title>
            <link>https://medium.com/@srimeda?source=rss-1890041237f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:30:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srimeda/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[Load Balancers]]></title>
            <link>https://srimeda.medium.com/load-balancers-cbe4bfe73277?source=rss-1890041237f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbe4bfe73277</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[load-balancer]]></category>
            <dc:creator><![CDATA[Srini]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 08:40:31 GMT</pubDate>
            <atom:updated>2024-03-08T08:41:22.208Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is a load balancer?</strong></h3><p><strong>Load balancing</strong> is a technique to distribute incoming traffic or workloads across multiple servers. For this, we use <strong>load balancers</strong>.</p><p>A load balancer is a device or software component that acts as an intermediary between clients and a group of servers.</p><p>Its purpose is to evenly distribute workloads to prevent any server from being overloaded.</p><p><strong>In simple words, the load balancer is one of the key components in modern distributed systems to optimize resource usage, maximize performance, and ensure high availability, scalability, and reliability.</strong></p><h3><strong>Why do we need a load balancer?</strong></h3><p>Suppose we have a single server setup, where several clients are sending requests to a single server. When number of requests increase, there will be two critical issues:</p><ol><li><strong>Server Overloading</strong>: There is a limit to the number of requests a single server can handle. If the number of requests exceeds this limit, the server may become overloaded and unable to function properly.</li><li><strong>Single point of failure</strong>: If the single server goes down for a reason, the entire application will become unavailable to users. This can result in poor user experience and impact the reliability of the system.</li></ol><p>We can solve the above problems in two ways:</p><ul><li><strong>Horizontal Scaling</strong>: We can add more servers to our system. Now this will bring a new challenge: How to distribute the requests evenly across these servers? Answer is: we should use load balancers.</li><li><strong>Vertical Scaling</strong>: We can increase the power of our current server. But there are limits to how much we can increase the capabilities of a single machine.</li></ul><p><strong>The load balancer will not only help us to distribute requests across multiple servers but also increase system capacity to add more servers if the number of requests increases in the future.</strong></p><p>On the other side, load balancer also continuously checks the health of each server. If one of the server goes offline due to some reason, it will redirect the traffic going to that server to some other available server. So load balancers help us to ensure that the service remains available, even in the case of the failure of one server or multiple servers.</p><h3><strong>How a system with a load balancer works?</strong></h3><p>How user requests are served when there is a load balancer in the system? What are the key steps involved in this process? Let us understand the whole process starting from the DNS request.</p><p><strong>Step 1</strong>: User device sends a DNS request to a DNS server. Now DNS server maps the domain name in the request to an IP address.</p><p><strong>Step 2</strong>: DNS server responds to the device with the IP address of the requested domain. <strong>Here is one important thing: This IP address is the IP address of the load balancer! Due to this, web servers are not reachable directly by the end user and only the load balancer layer is visible.</strong></p><p><strong>Step 3</strong>: Now user device establishes a connection with the load balancer using the provided IP address. This connection is initiated over the HTTP(S) protocol.</p><p><strong>Step 4</strong>: Now load balancer receives the incoming request from the user device. At this point, the load balancer acts as the entry point for the traffic.</p><p><strong>Step 5</strong>: Now load balancer determines which web server should handle the request based on the load-balancing algorithm. This decision depends on factors like server availability, server load, and the logic of load-balancing algorithm.</p><p><strong>Step 6</strong>: Load balancer forwards the incoming request to the selected web server through private IPs. Here private IP address is unreachable for the end device and reachable only between servers in the same network. They are used for communication between servers.</p><p><strong>Step 7</strong>: The selected web server processes the request and generates a response. Now webserver sent back the response to the load balancer.</p><p><strong>Step 8</strong>: Load balancer receives the response from the web server and forwards it back to the user device.</p><p><strong>Step 9</strong>: Finally, user device receives the response from the load balancer. They treat it as if it originated directly from the requested server.</p><p>These steps may be different based on the load balancer configuration and the protocols.</p><p>Most of the time, load balancers also perform additional functions like SSL termination, session persistence, traffic monitoring, caching, etc.</p><h3><strong>Where do we add a load balancer?</strong></h3><p>Load balancers can be placed at different points in a system to distribute the workload. Some common places to use load balancers are:</p><ol><li><strong>Between clients and frontend web servers</strong>: This is often the first point of contact between the client and the system. So load balancers receives incoming requests from clients and distributes them across frontend web servers.</li><li><strong>Between frontend web servers and backend application servers</strong>: In a system with multiple frontend web servers, a load balancer can be used to distribute incoming requests from the web servers to the backend application servers.</li><li><strong>Between backend application servers and cache servers</strong>: Load balancers can be used to distribute requests from the application servers to cache servers, which store frequently accessed data in memory to reduce response times.</li><li><strong>Between cache servers and database servers</strong>: In systems with multiple cache servers, a load balancer can be used to distribute requests from cache servers to the database servers, which store the actual data. This helps to ensure that the database servers are not overwhelmed with requests.</li></ol><h3><strong>Types of load balancers</strong></h3><p>There are two main types of load balancers.</p><ul><li><strong>Software load balancers</strong>: are implemented as software applications that are installed on physical servers or virtual machines. They are configured to meet the specific needs of a system and provide greater flexibility in terms of customization. Scaling with software load balancers is also easier because we can add more capacity by adding more servers.</li><li><strong>Hardware load balancers</strong>: are physical devices that are installed in a network or in data centers. They are generally flexible and offer fewer options for customization. But they are often faster and more reliable than software load balancers because they are dedicated hardware devices that are designed specifically for load balancing.</li></ul><p>The main difference between them is the level of customization and scalability they offer.</p><p>Overall, the choice between a software or hardware load balancer depends on the specific requirements of the system.</p><p>Software load balancers are more suitable for systems that require a high level of customization and scalability, while hardware load balancers are better for systems that require high performance and reliability.</p><h3><strong>Load balancing algorithms</strong></h3><p>Load balancers use various load-balancing algorithms to distribute incoming network traffic across multiple servers in a balanced manner. So, it is the responsibility of these algorithms to select a server from a pool of servers available to direct each incoming request.</p><p>Here are some popular load balancing algorithms:</p><ol><li><strong>Round Robin method:</strong> Each request is sequentially distributed to the next server in a circular manner.</li><li><strong>Least Connections method:</strong> Directs new requests to the servers with the fewest active connections.</li><li><strong>Weighted Round Robin method:</strong> Similar to Round robin but there is a weight associated with each server. So the servers with the higher weights receive a larger portion of the load.</li><li>Least response time method: Considers the response times of the servers and directs the request to the server with the lowest response time.</li><li><strong>IP Hash method:</strong> Calculates the hash value based on client’s IP address to select the server from the pool. This will ensure that requests from the same client will be directed to the same server.</li></ol><p>Different algorithms have different strengths and weaknesses. So the correct choice of load balancing algorithm depends on the characteristics of the workload and the goals of the load balancing strategy.</p><p><strong>Advantages of load balancing:</strong></p><ol><li>Ensure that the application is always available and can scale as needed.</li><li>Prevent a single server from being overloaded with requests.</li><li>Provide encryption, authentication, and other functionalities to secure, manage and monitor the application. They can also provide efficient protection against DoS attacks.</li><li>End users only need to know the IP address of the load balancer, rather than the addresses of every server in the cluster, which provides a layer of abstraction.</li><li>Minimize server response time and maximize throughput by distributing requests evenly across servers.</li><li>Load balancers can do health checks and monitor the request handling capability of servers to ensure that they are functioning properly.</li><li>We can add or remove servers based on the number of requests.</li><li>Load balancers can be used to rollout software updates without taking the whole service down by taking one server at a time.</li></ol><p>Load balancing algorithms can be divided into two categories:</p><p><strong>Static load balancing algorithms:</strong></p><ol><li>These algorithms behaves the same way regardless of the state of the backend server serving the requests.</li><li>They are simpler and more efficient to implement, but they can lead to uneven distribution of requests.</li><li>Examples of static load balancing algorithms are <strong>round robin, weighted round robin, source IP hash, URL hash, randomized algorithm</strong>, etc.</li></ol><p><strong>Dynamic load balancing algorithms:</strong></p><ol><li>These algorithms take into account the state of the backend server and consider server load when distributing the requests.</li><li>They require communication between load balancers and servers, so they are slightly more complex but can distribute requests efficiently.</li><li>Examples of dynamic load balancing algorithms are <strong>least connection method, weighted least connection method, least response time method</strong>, etc.</li></ol><h3><strong>Round Robin Algorithm:</strong></h3><p>Round robin is a simple load balancing algorithm that directs client requests to different servers based on a rotating list.</p><p>The load balancer maintains a list of all the available servers and directs incoming requests in a round robin fashion.</p><p>The first request goes to the first server, second request goes to the second server and so on. When the load balancer reaches the end of the list, it goes back to the beginning and starts from the first server again.</p><p><strong>Advantages:</strong></p><ul><li>Easy to implement</li><li>Evenly distributes the requests between servers</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Doesn’t consider the server’s load or specifications, so there is a risk that a server with low capacity will receive a large number of requests and become overloaded.</li><li>It works best if every server in the load balancer list has roughly the same specification. Otherwise, a low processing server may have the same load as a high processing server.</li></ul><h3><strong>Weighted Round Robin Algorithm:</strong></h3><p>It is an advanced version of the Round robin algorithm. It distributes the incoming requests based on the weighted score of the servers.</p><p>The weight can be a number that reflects the server’s processing power or specifications. This allows the algorithm to consider server specifications when distributing traffic.</p><p><strong>Advantages and disadvantages:</strong></p><ul><li>It is slightly more complex than simple round robin algorithm, but it works well with servers with different specifications.</li><li>It does not consider the current load of each server or the relative computation cost of each request.</li><li>Based on the weighted score, some servers may receive higher proportion of the overall request count.</li></ul><h3><strong>Random Load balancing algorithm:</strong></h3><p>This algorithm randomly distributes the requests to servers using a Random number generator.</p><p>Like the round robin algorithm, this algorithm also works well for a group of servers with similar configurations.</p><h3><strong>Source IP hash load balancing algorithm:</strong></h3><p>The source IP hash load balancing algorithm selects the server based on a unique hash key. It generates the hash key by combining the source and destination IP addresses and allocates the request to a specific server.</p><p>If the session is broken, the key can be regenerated and the client request can be directed back to the same server that was originally handing it. In other words, this algorithm is useful when a dropped connection needs to be returned to the same server.</p><h3><strong>URL Hash Load balancing algorithm:</strong></h3><p>The URL hash load balancing algorithm generates a hash value based on the URL present in client requests. The requests are forwarded to servers based on the hash value. The load balancer caches the hash value of the URL, so subsequent requests that use the same URL result in cache hit and are forwarded to the same server.</p><p>URL hash algorithm is useful when load-balanced servers serve mostly unique content per server. In other words, all requests related to one process (e.g., running code) will go to one server, and all requests related to another process (e.g., payments) goes to another server, and so on.</p><h3><strong>Least connections Method:</strong></h3><p>The least connection method algorithm considers the current load on the server and aims to improve performance. It does this by sending requests to the server with the least number of active connections.</p><p><strong>Benefits and drawbacks:</strong></p><ul><li>The load balancer does additional calculations to determine the server with the least number of connections.</li><li>It is useful when there are many persistent connections in the traffic that are unevenly distributed between the servers. If the servers are busy with long computations, the connections between client and server stay alive for a long period of time.</li><li>The additional calculations required to determine the server with the least number of connections may increase the load on the load balancer itself.</li></ul><h3><strong>Weighted least connection method:</strong></h3><p>The weighted least connections load balancing algorithm distributes load based on both the number of current and active connections to each server and the relative capacity of each server.</p><p>It takes into account that some servers can handle more requests than the other.</p><p>Servers are rated based on their processing capabilities, allowing for a more fine-grained distribution of load.</p><h3><strong>Least response time method:</strong></h3><p>The Least response time load balancing algorithm is more advanced version of the least connection method. It forwards the request to the server with the fewest active connections and the least average response time.</p><ul><li>It relies on the time taken by a server to respond to a health monitoring request, using the speed of the response as an indicator of the server’s load.</li><li>It also considers number of active connections on each server.</li><li>The backend server that responds fast receives the subsequent request.</li><li>It may require additional calculations to determine the server with the least average response time.</li></ul><h3><strong>What is the difference between load balancer and reverse proxy?</strong></h3><p>They both are networking components used in web applications, but they serve different purposes and have distinct functionalities.</p><p><strong>Load Balancer</strong></p><ol><li>A load balancer is a device or software component that distributes the incoming traffic across multiple servers, ensuring optimal usage of resources, and preventing any single server from becoming overwhelmed with requests.</li><li>Load balancers can operate at different layers of the OSI model, including layer 4 (transport layer) and layer 7 (application layer)</li><li>They typically use various algorithms to determine how to distribute incoming requests, such as round-robin, least connections, or weighted round-robin.</li><li>Load balancers can enhance the availability and scalability of web applications by spreading the load across multiple servers, which helps improve performance and reliability.</li></ol><p><strong>Reverse Proxy</strong></p><ol><li>A reverse proxy is a server that sits between client and the actual backend servers, intercepting requests from clients and forwarding them to the appropriate backend servers.</li><li>Unlike a forward proxy, which is used to retrieve resources on behalf of clients from other servers, a reverse proxy manages inbound traffic on behalf of backend servers.</li><li>Reverse proxies can perform various functions, including load balancing, SSL/TLS termination, caching, compression, and security features such as DDoS protection and web application firewall (WAF) capabilities.</li><li>They can also provide a layer of abstraction between clients and backend servers, allowing for easier management of backend infrastructure and enabling features like URL rewriting and request routing.</li></ol><p><strong>References:</strong></p><p><a href="https://www.enjoyalgorithms.com/blog/load-balancers-in-system-design">https://www.enjoyalgorithms.com/blog/load-balancers-in-system-design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe4bfe73277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency]]></title>
            <link>https://srimeda.medium.com/java-concurrency-3d3366c71e90?source=rss-1890041237f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d3366c71e90</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java-thread]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[executorservice]]></category>
            <dc:creator><![CDATA[Srini]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 07:41:14 GMT</pubDate>
            <atom:updated>2021-08-28T07:41:14.568Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>The java.util.concurrent package provides tools for creating concurrent applications. The java.util.concurrent contains way too many features, and some of the most useful utilities from this package like:</p><ul><li>Executor</li><li>ExecutorService</li><li><a href="###ScheduledExecutorService">ScheduledExecutorService</a></li><li>Future</li><li>CountDownLatch</li><li>CyclicBarrier</li><li>Semaphore</li><li>ThreadFactory</li><li>BlockingQueue</li><li>DelayQueue</li><li>Locks</li><li>Phaser</li></ul><h3>Executor</h3><p>Executor is an interface that represents an object that executes provided or submitted tasks.</p><p>This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling,etc.</p><p>An Executor is used normally instead of explicitly creating threads. For example, rather than invoking</p><pre>new Thread(new RunnableTask()).start();</pre><p>for each of a set of tasks, you might use:</p><pre>Executor executor = anExecutor();<br>executor.execute(new RunnableTask1());<br>executor.execute(new RunnableTask2());</pre><p>However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller&#39;s thread:</p><pre>class DirectExecutor implements Executor {<br>    public void execute(Runnable r) {<br>        r.run();<br>    }<br>}</pre><p>More typically, tasks are executed in some thread other than the caller’s thread. The executor below spawns a new thread for each task.</p><pre>class ThreadPerTaskExecutor implements Executor {<br>    public void execute(Runnable r) {<br>        new Thread(r).start();<br>    }<br>}</pre><p>Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.</p><pre>class SerialExecutor implements Executor {<br>    final Queue tasks = new ArrayDeque&lt;&gt;();<br>    final Executor executor;<br>    Runnable active;</pre><pre>    SerialExecutor(Executor executor) {<br>        this.executor = executor;<br>    }</pre><pre>    public synchronized void execute(Runnable r) {<br>        tasks.add(() -&gt; {<br>            try {<br>                r.run();<br>            } finally {<br>            scheduleNext();<br>           }<br>        });<br>        if (active == null) {<br>            scheduleNext();<br>        }<br>    }<br> <br>    protected synchronized void scheduleNext() {<br>        if ((active = tasks.poll()) != null) {<br>            executor.execute(active);<br>        }<br>    }<br>}</pre><p>The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executorsclass provides convenient factory methods for these Executors.</p><p><strong>Memory consistency effects:</strong> Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.</p><h3>ExecutorService</h3><p>An ExecutorService is a complete solution for asynchronous processing. It manages an in-memory queue and schedules submitted tasks based on thread availability.</p><p>To use ExecutorService, we need to create one Runnable class.</p><pre>public class Task implements Runnable {<br>    @Override<br>    public void run() {<br>        // task details<br>    }<br>}</pre><p>Now we can create the ExecutorService instance and assign this task. At the time of creation, we need to specify the thread-pool size.</p><pre>ExecutorService executor = Executors.newFixedThreadPool(10);</pre><p>If we want to create a single-threaded ExecutorService instance, we can use newSingleThreadExecutor(ThreadFactory threadFactory) to create the instance.</p><p>Once the executor is created, we can use it to submit the task:</p><pre>public void execute() { <br>    executor.submit(new Task()); <br>}</pre><p>We can also create the Runnable instance while submitting the task.</p><pre>executor.submit(() -&gt; {<br>    new Task();<br>});</pre><p>Method submit extends base method Executor#execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion.</p><p>Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. ExecutorCompletionService can be used to write customized variants of these methods.)</p><p>It also provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.</p><p>An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown method will allow previously submitted tasks to execute before terminating, while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.</p><p>The Executors class provides factory methods for the executor services provided in this package.</p><h4>Usage Examples</h4><p>Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors#newFixedThreadPool factory method:</p><pre>class NetworkService implements Runnable {<br>    private final ServerSocket serverSocket;<br>    private final ExecutorService pool;</pre><pre>    public NetworkService(int port, int poolSize) throws IOException {<br>        serverSocket = new ServerSocket(port);<br>        pool = Executors.newFixedThreadPool(poolSize);<br>    }<br>    <br>    public void run() { // run the service<br>        try {<br>            for (;;) {<br>                pool.execute(new Handler(serverSocket.accept()));<br>            }<br>        } catch (IOException ex) {<br>            pool.shutdown();<br>        }<br>    }<br>}</pre><pre>class Handler implements Runnable {<br>    private final Socket socket;<br>    Handler(Socket socket) { this.socket = socket; }<br>    public void run() {<br>        // read and service request on socket<br>    }<br>}</pre><p>The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:</p><pre>void shutdownAndAwaitTermination(ExecutorService pool) {<br>    pool.shutdown(); // Disable new tasks from being submitted<br>    try {<br>      // Wait a while for existing tasks to terminate<br>      if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {<br>        pool.shutdownNow(); // Cancel currently executing tasks<br>        // Wait a while for tasks to respond to being cancelled<br>        if (!pool.awaitTermination(60, TimeUnit.SECONDS))<br>            System.err.println(&quot;Pool did not terminate&quot;);<br>      }<br>    } catch (InterruptedException ie) {<br>      // (Re-)Cancel if current thread also interrupted<br>      pool.shutdownNow();<br>      // Preserve interrupt status<br>      Thread.currentThread().interrupt();<br>    }<br>}</pre><p><strong>Memory consistency effects:</strong> Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn <em>happen-before</em> the result is retrieved via Future.get().</p><h3>ScheduledExecutorService</h3><p>ScheduledExecutorService is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically.</p><p>The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.</p><p>Commands submitted using the Executor#execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedulemethods, and are treated as requests for immediate execution.</p><p>All schedule methods accept <em>relative</em> delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a java.util.Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.</p><p>The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.</p><h4>Usage Example</h4><p>We can use both Runnable and Callable interface to define the task.</p><pre>public void execute() {<br>    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();<br>    Future future = executorService.schedule(() -&gt; {<br>        // ...<br>        return &quot;Hello world&quot;;<br>    }, 1, TimeUnit.SECONDS);<br> <br>    ScheduledFuture scheduledFuture = executorService.schedule(() -&gt; {<br>        // ...<br>    }, 1, TimeUnit.SECONDS);<br> <br>    executorService.shutdown();<br>}</pre><p>Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:</p><pre>import static java.util.concurrent.TimeUnit.*;</pre><pre>class BeeperControl {<br>    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);<br> <br>    public void beepForAnHour() {<br>        Runnable beeper = () -&gt; System.out.println(&quot;beep&quot;);<br>        ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);<br>        Runnable canceller = () -&gt; beeperHandle.cancel(false);<br>        scheduler.schedule(canceller, 1, HOURS);<br>    }<br>}</pre><p>ScheduledExecutorService can also schedule the task after some given fixed delay:</p><pre>executorService.scheduleAtFixedRate(() -&gt; {<br>    // ...<br>}, 1, 10, TimeUnit.SECONDS);<br> <br>executorService.scheduleWithFixedDelay(() -&gt; {<br>    // ...<br>}, 1, 10, TimeUnit.SECONDS);</pre><p>Here, the scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)method creates and executes a periodic action that is invoked firstly after the provided initial delay, and subsequently with the given period until the service instance shutdowns.</p><p>The scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit)method creates and executes a periodic action that is invoked firstly after the provided initial delay, and repeatedly with the given delay between the termination of the executing one and the invocation of the next one.</p><h3>Future</h3><p><em>Future is used to represent the result of an asynchronous operation</em>. It comes with methods for checking if the asynchronous operation is completed or not, and to get the computed result, etc.</p><p>The result can only be retreived using the method get when the computation has completed, blocking if necessary until its ready.</p><p>Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled.</p><p>We can use following code snippet to check if the future result is ready and fetch the data if the computation is done:</p><pre>if (future.isDone() &amp;&amp; !future.isCancelled()) {<br>    try {<br>        str = future.get();<br>    } catch (InterruptedException | ExecutionException e) {<br>        e.printStackTrace();<br>    }<br>}</pre><p>What’s more, the cancel(boolean mayInterruptIfRunning) API cancels the operation and releases the executing thread. If the value of mayInterruptIfRunning is true, the thread executing the task will be terminated instantly. Otherwise, in-progress tasks will be allowed to complete.</p><pre>public void invoke() {<br>    ExecutorService executorService = Executors.newFixedThreadPool(10);<br> <br>    Future future = executorService.submit(() -&gt; {<br>        // ...<br>        Thread.sleep(10000l);<br>        return &quot;Hello world&quot;;<br>    });<br>}</pre><p>We can also specify a timeout for a given operation. If the task takes more than this time, a TimeoutException is thrown:</p><pre>try {<br>    future.get(10, TimeUnit.SECONDS);<br>} catch (InterruptedException | ExecutionException | TimeoutException e) {<br>    e.printStackTrace();<br>}</pre><p>If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future&lt;?&gt; and return null as a result of the underlying task.</p><h4>FutureTask</h4><p>The FutureTask is a cancellable computation. This class provides a base implementation of Future that implements Runnable, and so may be executed by an Executor.</p><p>FutureTask contains methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the compuation.</p><p>For example, the above construction with submit could be replaced by:</p><pre>FutureTask future = new FutureTask&lt;&gt;(task);<br>executor.execute(future);</pre><p>The result can only be retrieved when the computation has completed. The get method will block if the computation has not yet completed. Once the computation has completed, the computation can not be restarted or cancelled (unless the computation is invoked using runAndReset)</p><p><strong>Memory consistency effects:</strong> Actions taken by the asynchronous computation happen-before actions following the corresponding Future.get() in another thread.</p><h3>CountDownLatch</h3><p>CountDownLatch (introduced in JDK 5) is a utility class which blocks a set of threads until some operations being performed in other threads completes.</p><p>A CountDownLatch is initialized with a given <em>count</em>. The await methods block until the current count reaches zero due to invocations of the countDown method, after which all waiting threads are released and any subsequent invocations of await return immediately.</p><p>This is a one-shot phenomenon — the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.</p><p>A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes.</p><p>A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking awaitwait at the gate until it is opened by a thread invoking countDown. A CountDownLatch initialized to <em>N</em> can be used to make one thread wait until <em>N</em> threads have completed some action, or some action has been completed N times.</p><p>A useful property of a CountDownLatch is that it doesn&#39;t require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.</p><p><strong>Sample usage:</strong> Here is a pair of classes in which a group of worker threads use two countdown latches:</p><ul><li>The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;</li><li>The second is a completion signal that allows the driver to wait until all workers have completed.</li></ul><pre>class Driver { // ...<br>  void main() throws InterruptedException {<br>    CountDownLatch startSignal = new CountDownLatch(1);<br>    CountDownLatch doneSignal = new CountDownLatch(N);</pre><pre>    for (int i = 0; i &lt; N; ++i) // create and start threads<br>      new Thread(new Worker(startSignal, doneSignal)).start();</pre><pre>    doSomethingElse();            // don&#39;t let run yet<br>    startSignal.countDown();      // let all threads proceed<br>    doSomethingElse();<br>    doneSignal.await();           // wait for all to finish<br>  }<br>}</pre><pre>class Worker implements Runnable {<br>  private final CountDownLatch startSignal;<br>  private final CountDownLatch doneSignal;<br>  Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {<br>    this.startSignal = startSignal;<br>    this.doneSignal = doneSignal;<br>  }<br>  public void run() {<br>    try {<br>      startSignal.await();<br>      doWork();<br>      doneSignal.countDown();<br>    } catch (InterruptedException ex) {} // return;<br>  }</pre><pre>  void doWork() { ... }<br>}</pre><p>Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier.)</p><pre>class Driver2 { // ...<br>  void main() throws InterruptedException {<br>    CountDownLatch doneSignal = new CountDownLatch(N);<br>    Executor e = ...</pre><pre>    for (int i = 0; i &lt; N; ++i) // create and start threads<br>      e.execute(new WorkerRunnable(doneSignal, i));</pre><pre>    doneSignal.await();           // wait for all to finish<br>  }<br>}</pre><pre>class WorkerRunnable implements Runnable {<br>  private final CountDownLatch doneSignal;<br>  private final int i;<br>  WorkerRunnable(CountDownLatch doneSignal, int i) {<br>    this.doneSignal = doneSignal;<br>    this.i = i;<br>  }<br>  public void run() {<br>    try {<br>      doWork(i);<br>      doneSignal.countDown();<br>    } catch (InterruptedException ex) {} // return;<br>  }<br>  void doWork() { ... }<br>}</pre><p>Memory consistency effects: Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.</p><h3>CyclicBarrier</h3><p>CyclicBarrier works almost the same as CountDownLatch except that we can reuse it. Unlike CountDownLatch, it allows multiple threads to wait for each other using await() method (known as barrier condition) before invoking the final task.</p><p>We need to create a Runnable task instance to initiate the barrier condition:</p><pre>public class Task implements Runnable {<br>    private CyclicBarrier barrier;<br> <br>    public Task(CyclicBarrier barrier) {<br>        this.barrier = barrier;<br>    }<br> <br>    @Override<br>    public void run() {<br>        try {<br>            LOG.info(Thread.currentThread().getName() + &quot; is waiting&quot;);<br>            barrier.await();<br>            LOG.info(Thread.currentThread().getName() + &quot; is released&quot;);<br>        } catch (InterruptedException | BrokenBarrierException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>Now we can invoke some threads to race for the barrier condition:</p><pre>public void start() {<br> <br>    CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -&gt; {<br>        // ...<br>        LOG.info(&quot;All previous tasks are completed&quot;);<br>    });<br> <br>    Thread t1 = new Thread(new Task(cyclicBarrier), &quot;T1&quot;); <br>    Thread t2 = new Thread(new Task(cyclicBarrier), &quot;T2&quot;); <br>    Thread t3 = new Thread(new Task(cyclicBarrier), &quot;T3&quot;); <br> <br>    if (!cyclicBarrier.isBroken()) { <br>        t1.start(); <br>        t2.start(); <br>        t3.start(); <br>    }<br>}</pre><p>Here, the isBroken() method checks if any of the threads got interrupted during the execution time. We should always perform this check before performing the actual process.</p><h3>Semaphore</h3><p>The Semaphore is used for blocking thread level access to some part of the physical or logical resource. A semaphore contains a set of permits; whenever a thread tries to enter the critical section, it needs to check the semaphore if a permit is available or not.</p><p>If a permit is not available (via tryAcquire()), the thread is not allowed to jump into the critical section; however, if the permit is available the access is granted, and the permit counter decreases.</p><p>Once the executing thread releases the critical section, again the permit counter increases (done by release()method).</p><p>We can specify a timeout for acquiring access by using the tryAcquire(long timeout, TimeUnit unit) method.</p><p>We can also check the number of available permits or the number of threads waiting to acquire the semaphore.</p><p>Following code snippet can be used to implement a semaphore:</p><pre>static Semaphore semaphore = new Semaphore(10);</pre><pre>public void execute() throws InterruptedException {<br>    LOG.info(&quot;Available permit : &quot; + semaphore.availablePermits());<br>    LOG.info(&quot;Number of threads waiting to acquire: &quot; + semaphore.getQueueLength());<br>    <br>    if (semaphore.tryAcquire()) {<br>        try {<br>            // ...<br>        }<br>        finally {<br>            semaphore.release();<br>        }<br>    }<br>}</pre><p>We can implement a Mutex like data-structure using Semaphore.</p><p>In the subsequent post, we can learn about ThreadFactory, BlockingQueue, DelayQueue, Locks, Phaser, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d3366c71e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Thread Lifecycle]]></title>
            <link>https://srimeda.medium.com/java-thread-lifecycle-b5353a6f5d4c?source=rss-1890041237f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5353a6f5d4c</guid>
            <dc:creator><![CDATA[Srini]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 07:37:10 GMT</pubDate>
            <atom:updated>2021-08-28T07:46:10.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Thread?</h3><p>A Thread is an independent path of execution in a program. Many threads can be spawned within a program, and these threads can run concurrently.</p><ul><li>A <em>thread</em> is a thread of execution.</li><li>The JVM allows an application to have multiple threads of execution running concurrently.</li><li>Each thread has a priority. Threads with higher priority are executed in preference to the threads with the lower priority.</li><li>Each thread may or may not have also marked a <em>Daemon</em>.</li><li>When a JVM starts up, there is usually a single non-daemon thread (which typically invokes the main method).</li><li>The JVM continues to execute the threads until either of the following occurs:</li><li>The exit method of Runtime class has been invoked and the security manager has allowed the exit method to execute.</li><li>All threads that are not <em>daemon</em> threads have died, either by returning from the run method call or by throwing an exception.</li></ul><h3>How does the JVM keep track of each thread’s execution?</h3><p>The JVM gives each thread its own method-call stack. In addition to keep tracking of the current byte code instruction, the method-call stack also tracks local variables, parameters the JVM passes to a method, and the method’s return value.</p><h3>Creating and Running Threads:</h3><p>Threads can be created in two ways:</p><ul><li>Extending Thread class and overriding run() method.</li><li>Building a class that implements Runnable interface and then creating an object of Thread class passing the Runnable object as a parameter.</li></ul><p>Below is a simple example of creating threads using the second approach. This example creates 10 threads, each of the thread calculate and prints the multiplication tables from 1 to 10.</p><p><strong>Steps to implement the example:</strong></p><ul><li>Create a class Name <em>Calculator</em> implementing <em>Runnable</em> interface.</li></ul><pre>public class Calculator implements Runnable</pre><ul><li>Declare a <em>private int</em> attribute named <em>number</em> and implement the constructor to initialize its value.</li></ul><pre>private int number;</pre><ul><li>Implement the <em>run()</em> method. This method calculates the multiplication table of the <em>number</em>.</li></ul><pre>@Override<br> public void run() {<br>  for (int i = 1; i &lt;= 10; i++) {<br>   System.out.printf(&quot;%s: %d * %d = %d\n&quot;, Thread.currentThread()<br>     .getName(), number, i, i * number);<br>  }<br> }</pre><ul><li>Implement the main class of the application, which contains <em>main() </em>method.</li><li>Inside the <em>main()</em> method, create a <em>for</em> loop with 10 iterations. Inside for loop, create an object of <em>Calculator</em> class, an object of the <em>Thread</em> class, pass the object of <em>Calculator</em> class as a parameter, and invoke the <em>start() </em>method of the <em>Thread</em> object.</li></ul><pre>public class Main {<br> public static void main(String[] args) {<br>  for(int i=0; i<br></pre><pre><strong>Below is the partial output of a sample run of the above code:</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/0*74MS-LyfVDWTjxfJ.png" /></figure><ul><li>Every Java Program has at least one thread in Execution. When we run a program, JVM runs the execution thread that calls main() method.</li><li>Creating an object to the Thread class doesn’t create an execution of the Thread. Or calling the run() method of the implemented Runnable interface will not create a new execution of Thread. Invoking start() method on creates a new execution thread.</li><li>When we call the start() method of Thread object, it creates another execution thread. Our program will have as many threads as calls to the start() method are made.</li><li>A Java program ends when all its threads(all non-daemon) finishes.</li><li>If the initial thread(the one that executes main() method) ends, the rest of threads continue with their execution until they finish.</li><li>If a thread is exited by calling System.exit(), all threads end their execution.</li></ul><h3>Life cycle of a Thread</h3><p>Understanding the lifecycle of threads is very important while programming in Threads.</p><p>A Thread can be various states during its life time. The following diagram describes all the states a thread can undergo and the method calls that cause the transition from one state to another:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*qZVyoSx2ECM1Hrgu.png" /></figure><p>Java Thread States</p><ol><li><strong>Runnable</strong>: A Thread starts its life from this state. Thread first enters into this state after the start() method of the thread is invoked. In this state, thread will be waiting for the scheduler to pick the thread for execution. The scheduler picks the threads based on their priorities. A thread can also re-enter this state either after running, waiting, sleeping or also while coming back from blocked state.</li><li><strong>Running</strong>: A thread is in running state means its currently running. There are several ways for thread to go into Runnable state. But there is only one way to come into Running state: the scheduler selects the thread for execution for the runnable pool. A thread runs until its swapped out, becomes blocked, or voluntarily give up its turn by invoking the static method Thread.yield().</li><li><strong>Dead</strong>: A thread enters this state when it completes execution. It may also enters this state when it is terminated by unrecoverable error condition. If a thread goes to this state means it can not be run again.</li><li><strong>Sleep</strong>: A Java thread may be forced to sleep (suspend) for some predefined time. In this state, thread is still alive but is not runnable, it might be return to runnable state later. It can throw InterruptedException.</li><li><strong>Blocked</strong>: A thread can enter blocked state because of waiting for the resources that are held by another thread.</li><li><strong>Blocked on I/O</strong>: Thread enters this state because of waiting for I/O resources. In this case, the thread will be sent back to Runnable state after the availability of resources.</li><li><strong>Blocked on Synchronization</strong>: Thread may enters this state while waiting for object lock. Thread will be moved to Runnable state after it acquires lock.</li><li><strong>Waiting</strong> state: A call to <em>Object.wait() </em>method causes the current object to wait. The thread remains in waiting state until some other thread invokes <em>notify() </em>or <em>notifyAll()</em> method of this object.</li></ol><p><strong>Release 5.0</strong> introduced the <em>Thread.getState()</em> method, which results in one of the following <em>Thread.State</em> values:</p><ul><li>NEW</li><li>RUNNABLE</li><li>BLOCKED</li><li>WAITING</li><li>TIMED_WAITING</li><li>TERMINATED</li></ul><p>The Thread class API also introduced a method <em>isAlive()</em>, which returns true if the thread has already been started and not stopped. If the method <em>isAlive() </em>returns false, the thread is either New, or is Dead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5353a6f5d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Seriously Organized]]></title>
            <link>https://srimeda.medium.com/get-seriously-organized-d821c26c0e13?source=rss-1890041237f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d821c26c0e13</guid>
            <category><![CDATA[organized]]></category>
            <dc:creator><![CDATA[Srini]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 07:23:47 GMT</pubDate>
            <atom:updated>2021-08-28T07:23:47.062Z</atom:updated>
            <content:encoded><![CDATA[<p>“The secret of all victory lies in the organization of the non-obvious.” — <strong>Marcus Aurelius</strong></p><p>There are so many advantages in getting organized. Organizing clears our mind, helps stay focused, saves time and money, reduces stress, boosts self confidence.</p><p>To get seriously organized, follow:</p><ol><li>Write everything down</li><li>Declutter your things regularly</li><li>Organize your closet</li><li>Always wash your dishes after eating</li><li>Take out the trash every morning</li><li>Plan your future goals</li><li>Develop a morning routine</li><li>Hang a cork board in your work or study room</li><li>Trash spam emails immediately</li><li>Declutter files on your computer</li><li>Sort your photos into folders</li><li>Close unused accounts</li><li>Spend 10–20 minutes a day tidying up a little</li><li>Plan your self care routine and stick to it</li><li>Plan your meals in advance</li><li>Make your bed as soon as you get up</li><li>Donate things you don’t need any more</li><li>Set a place for everything in your home</li><li>Make a plan before any bigger task</li><li>Shop mindfully and evaluate your purchases</li><li>Use separate laundry bags for colored, b&amp;w clothes</li><li>Always put things back in their place</li><li>Track your income and spending</li><li>Use neat paper for your notes</li><li>Spend an hour cleaning every week</li><li>Have a concealed trash can in every room</li><li>Get rid of clothes that are damaged or faded</li><li>Stock up on things you use regularly</li><li>Use marked storage boxes in your basement or garage</li><li>Keep a To-Do List… and even lists of everything</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d821c26c0e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Caching]]></title>
            <link>https://srimeda.medium.com/spring-boot-caching-9c53a831051a?source=rss-1890041237f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c53a831051a</guid>
            <dc:creator><![CDATA[Srini]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 21:00:12 GMT</pubDate>
            <atom:updated>2020-11-25T23:47:28.521Z</atom:updated>
            <content:encoded><![CDATA[<p>We use caches to avoid database invocation or cost-intensive calculations. Spring provides an Abstraction layer for implementing the Cache.</p><p><strong>Why do we need an abstraction layer?</strong></p><p>There are various Cache providers with their own API spec. If we want to use one of them for our application, we need to have a hard dependency on these Cache provider’s API. The Spring Cache Abstraction layer gives use the ability to use the caching mechanism provided by various providers without calling cache provider’s API directly.</p><p><strong>How it is done?</strong></p><ul><li>Spring Boot users can use the <em>spring-boot-starter-cache</em> starter package to easily add the caching:</li></ul><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><ul><li>The @EnableCachingannotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly.</li><li>The post-processor handles the @Cacheable and @CacheEvictannotations. You can refer to the Javadoc and <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html">the reference guide</a> for more detail.</li><li>Spring Boot automatically configures a suitable CacheManager to serve as a provider for the relevant cache. See <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html">the Spring Boot documentation</a> for more detail.</li><li>If we don’t specify a specific caching library, then the default cache store is the simple fallback that uses ConcurrentHashMap.</li><li>The caching abstraction supports a wide range of cache libraries and is fully compliant with JSR-107 (JCache).</li><li>If the CacheManager is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the CacheManagerCustomizer interface.</li></ul><p><strong>References:</strong></p><ul><li><a href="https://spring.io/guides/gs/caching/">Caching Data with Spring</a>: This guide walks us through the process of enabling caching on a Spring managed bean.</li><li><a href="https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-caching.html">33. Caching</a></li><li><a href="https://medium.com/programming-sharing/the-complete-guide-for-spring-cache-abstraction-6cdb8bc10bc1">The complete guide for Spring Cache Abstraction</a></li><li><a href="https://www.javadevjournal.com/spring/spring-caching/">Guide to Spring caching</a></li><li><a href="https://www.youtube.com/watch?v=SpQzWtqulhM&amp;ab_channel=SpringI%2FO">https://www.youtube.com/watch?v=SpQzWtqulhM&amp;ab_channel=SpringI%2FO</a></li><li><a href="https://www.baeldung.com/spring-cache-tutorial">A Guide To Caching in Spring | Baeldung</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c53a831051a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>