<?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 saikuNoCoda on Medium]]></title>
        <description><![CDATA[Stories by saikuNoCoda on Medium]]></description>
        <link>https://medium.com/@divyanshverma?source=rss-612d9827c17e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*hd71KFM2AAcTbw06-CMnIg.jpeg</url>
            <title>Stories by saikuNoCoda on Medium</title>
            <link>https://medium.com/@divyanshverma?source=rss-612d9827c17e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:58:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divyanshverma/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[Rate limiter in Java]]></title>
            <link>https://medium.com/@divyanshverma/rate-limiter-in-java-f8b89e0a77fc?source=rss-612d9827c17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8b89e0a77fc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[saikuNoCoda]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 18:14:54 GMT</pubDate>
            <atom:updated>2023-02-11T18:14:54.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*VTxP7UYS5bIE5Dtn" /></figure><h3>What’s a rate limiter?</h3><blockquote>In simple words, a rate limiter is a software component that controls the speed at which a certain action can happen. It controls the rate at which requests can be made to a server or a system.</blockquote><p>It’s useful as:</p><ul><li>It protects system from being overwhelmed and overloaded.</li><li>Ensure a fair allocation of resources.</li><li>Prevent DOS attacks etc.</li></ul><h3>Let’s jump to the implementation part:</h3><pre>package com.example.throttler;<br><br>public class Event {<br>    public final long key;<br>    public final long eventTime;<br>    <br>    public Event(long key, long eventTime) {<br>        this.key = key;<br>        this.eventTime = eventTime;<br>    }<br>}</pre><ul><li>This is an <strong>Event</strong> class; which can be seen as an request/event to a system.</li><li>It has two fields : 1) <strong><em>key</em></strong> i.e. <strong><em>id</em></strong> of the event. 2) <strong><em>eventTime</em></strong> i.e. <strong><em>time</em></strong> at which this request/event was send/executed.</li></ul><pre>package com.example.throttler;<br><br>import java.util.LinkedList;<br>import java.util.Queue;<br><br>public class EventRateLimiter {<br><br>    final Queue&lt;Event&gt; events;<br>    final int maxRate;<br><br>    public EventRateLimiter(int maxRate) {<br>        this.events = new LinkedList&lt;Event&gt;();<br>        this.maxRate = maxRate;<br>    }<br><br>    public synchronized boolean canProceed(Event event) {<br>        decay();<br><br>        if (events.size() &gt;= maxRate) {<br>            events.add(event);<br>            return true;<br>        }<br><br>        return false;<br>    }<br><br>    public void decay() {<br>        long oneSecondAgo = System.currentTimeMillis() - 1000;<br>        decay(oneSecondAgo);<br>    }<br><br>    public synchronized void decay(long decayTime) {<br>        while (!events.isEmpty() &amp;&amp; events.peek().eventTime &lt; decayTime) {<br>            events.remove();<br>        }<br>    }<br>    <br>    public synchronized int rate() {<br>        decay();<br>        return events.size();<br>    }<br>}</pre><ul><li>This is <strong>EventRateLimiter</strong> class.</li><li>It is the <strong>main</strong> code for rate limiter. (It assumes every event occurs or take 1 sec to get completed).</li><li>It consists of two things: 1) <strong><em>events</em></strong> i.e. a <strong><em>queue</em></strong> which contains all the events/requests executed/sent to the system. 2) <strong><em>maxRate</em></strong> i.e. maximum number of events running/send in a system in a time frame or <strong><em>1 sec</em></strong>.</li></ul><blockquote>Note: A queue is a collection of entities that are maintained in a sequence and can be processed in a first-in, first-out (FIFO) order. More about queue: <a href="https://www.programiz.com/java-programming/examples/queue-implementation">https://www.programiz.com/java-programming/examples/queue-implementation</a></blockquote><p>Let’s go over each function one by one:</p><ul><li><strong>canProceed</strong>: Check whether we still have <strong><em>capacity</em></strong> for <strong><em>new</em> <em>events</em> </strong>to occur or not. If we have then it adds the event to the <strong><em>queue</em></strong> and returns <strong><em>true</em></strong> else returns <strong><em>false</em></strong>, so that the current event can wait for it’s execution.</li><li><strong>decay</strong>: It removes all the events which occurred before <strong><em>1 second</em></strong>.</li><li><strong>rate</strong>: Tells the current queue <strong><em>size</em></strong>.</li></ul><blockquote>Note: “<strong>Synchronized</strong>” is a keyword in Java that is used to provide a way of controlling access to a <strong>shared</strong> resource by <strong>multiple</strong> <strong>threads</strong>. When a method is declared as synchronized, only <strong>one</strong> thread can execute the method at a time, while all other threads trying to access the same method will be <strong>blocked</strong> until the first thread has finished executing the method. This mechanism is used to prevent <strong>race</strong> <strong>conditions</strong>, which can occur when multiple threads access a shared resource simultaneously and try to modify it at the same time. By using the synchronized keyword, we can ensure that only one thread at a time can access and modify the shared resource, ensuring the integrity and consistency of the data.</blockquote><p>Now lets jump to upgraded version <strong>EventRateLimiter</strong>:</p><ul><li>This class helps in creating different <strong><em>EventRateLimiter</em></strong> based on <strong><em>key/id</em></strong>.</li></ul><pre>package com.example.throttler;<br><br>import java.util.Map;<br>import java.util.concurrent.ConcurrentHashMap;<br><br>public class MultiEventRateLimiter {<br>    final Map&lt;Long, EventRateLimiter&gt; counters;<br>    final int mapRate;<br><br>    public MultiEventRateLimiter(int mapRate) {<br>        this.counters = new ConcurrentHashMap&lt;Long, EventRateLimiter&gt;();<br>        this.mapRate = mapRate;<br>    }<br><br>    public EventRateLimiter getRateLimiter(long key) {<br>        return counters.getOrDefault(key, addRateLimiter(key));<br>    }<br><br>    synchronized EventRateLimiter addRateLimiter(long key) {<br>        EventRateLimiter counter = counters.get(key);<br><br>        if (counter == null) {<br>            counter = new EventRateLimiter(mapRate);<br>            counters.put(key, counter);<br>        }<br><br>        return counter;<br>    }<br>}</pre><blockquote>Note: <strong>ConcurrentHashMap</strong> is a class in Java that provides a <strong>thread-safe</strong> implementation of a hash map. Unlike a regular <strong>HashMap</strong>, which is not thread-safe and can lead to data inconsistencies when multiple threads try to access and modify the map simultaneously, a <strong>ConcurrentHashMap</strong> allows multiple threads to access the map concurrently without causing <strong>race</strong> <strong>conditions</strong> or data inconsistencies. In a <strong>ConcurrentHashMap</strong>, each segment of the map can be modified independently, which helps to <strong>avoid lock contention</strong> and improve performance compared to a <strong>synchronized</strong> <strong>hash map</strong>.</blockquote><p>Above code credits to: <a href="https://github.com/marcocitus/globe-throttler">https://github.com/marcocitus/globe-throttler</a></p><p>In real world application we can put all the events in a List and whenever a new event comes we can check and remove all the completed events. Something on the line of this:</p><pre>this.eventsList = this.eventsList.stream()<br>                      .filter(e -&gt; e.eventEndTime &gt; System.currentTimeMillis())<br>                      .collect(Collectors.toCollection(LinkedList::new));</pre><p>Thank you for reading this. If you likes this: Clap 👏, Comment 💬 and Share 🔗.</p><p>Check out my other posts:</p><p><a href="https://medium.com/@divyanshverma/simple-spring-boot-application-that-schedules-some-task-executed-each-second-d5fa760ac2df">https://medium.com/@divyanshverma/simple-spring-boot-application-that-schedules-some-task-executed-each-second-d5fa760ac2df</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b89e0a77fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Spring boot application that schedules some task executed each second.]]></title>
            <link>https://medium.com/@divyanshverma/simple-spring-boot-application-that-schedules-some-task-executed-each-second-d5fa760ac2df?source=rss-612d9827c17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5fa760ac2df</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scheduler]]></category>
            <dc:creator><![CDATA[saikuNoCoda]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 20:09:42 GMT</pubDate>
            <atom:updated>2023-02-05T07:38:55.428Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Spring boot application that schedules some task each second.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZIv-qkSRoTRVgaEFnXatzA.jpeg" /></figure><p>Let’s write a simple spring boot starter main class:</p><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.scheduling.annotation.EnableScheduling;<br><br>@EnableScheduling<br>@SpringBootApplication<br>public class MessageSchedulingApplication {<br> <br> public static void main(String[] args) {<br>  SpringApplication.run(MessageSchedulingApplication.class, args);<br> }<br>}</pre><blockquote>The <a href="http://twitter.com/SpringBootApplicatio"><strong>@SpringBootApplicatio</strong></a><strong>n</strong> is a convenience annotation that provides a convenient way to enable a number of default settings for a Spring Boot application.</blockquote><ul><li>Enables auto-configuration of the Spring Application Context: Spring Boot uses auto-configuration to automatically configure components based on the dependencies that are present in the classpath.</li><li>Enables component scanning: Spring Boot automatically scans the packages specified in the base package of the application to find and register components in the Application Context.</li><li>Registers a number of default properties: Spring Boot sets default properties for things like server port, logging, and other common settings.</li></ul><blockquote>The <strong>SpringApplication.run</strong> method is used to launch the application.</blockquote><blockquote><strong>@EnableScheduling</strong> is a Spring annotation that can be used to enable scheduling in a Spring Boot application. The annotation is used in conjunction with the <strong>@Scheduled</strong> annotation to schedule tasks in the application.</blockquote><p>Let’s write a simple MessageScheduler class:</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.scheduling.annotation.Scheduled;<br>import org.springframework.stereotype.Component;<br>import java.util.List;<br><br>@Component<br>public class MessageScheduler {<br>    private final List&lt;String&gt; users = List.of(&quot;user1&quot;, &quot;user2&quot;, &quot;user3&quot;);<br>    private static final String MESSAGE_TO_SCHEDULE = &quot;Hello servers&quot;;<br>    public MessageScheduler() {}<br><br>    @Scheduled(fixedRate = 1000)<br>    public void scheduleMessage() {<br>        users.forEach(user -&gt; {<br>                System.out.println(String<br>                    .format(&quot;user: %s, haveMessages: %s&quot;, <br>                        user, MESSAGE_TO_SCHEDULE));<br>        });<br>    }<br>}</pre><blockquote>The <a href="http://twitter.com/Component"><strong>@Component</strong></a> annotation is a general-purpose annotation in Spring Framework used to indicate that a class is a component. Components are the building blocks of a Spring-based application.</blockquote><ul><li>The <a href="http://twitter.com/Component"><strong>@Component</strong></a><strong> </strong>annotation tells Spring to automatically detect and manage the lifecycle of the annotated class as a bean. Beans are the objects that form the backbone of the application and can be easily wired together using dependency injection.</li><li>This annotation makes it a candidate for component scanning, and Spring will automatically detect and manage it as a bean. Other classes in the application can then depend on this Component and access its functionality through dependency injection.</li></ul><blockquote>The <a href="http://twitter.com/Scheduled"><strong>@Scheduled</strong></a><strong> </strong>annotation is used to schedule tasks in a Spring application. The <strong>fixedRate</strong> attribute of the <a href="http://twitter.com/Scheduled">@Scheduled</a> annotation is used to specify the rate at which a task should be executed.</blockquote><p>Output:</p><pre>user: user1, haveMessages: <br>user: user2, haveMessages: Hello servers<br>user: user3, haveMessages: Hello servers<br>user: user1, haveMessages: Hello servers<br>user: user2, haveMessages: Hello servers<br>user: user3, haveMessages: Hello servers<br>.............<br>........<br>...</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5fa760ac2df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TL;DR — Java by comparison]]></title>
            <link>https://medium.com/@divyanshverma/tl-dr-java-by-comparison-ed0857c45f3b?source=rss-612d9827c17e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0857c45f3b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coding-style]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[saikuNoCoda]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 15:14:18 GMT</pubDate>
            <atom:updated>2023-02-03T15:16:14.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR — Java by comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*Le3R5La-vGNOpYZ2qNaNeg.jpeg" /></figure><ul><li>Never compare boolean with true or false in conditions.</li><li>Positive condition is more readable than the negative condition.</li><li>Return boolean expression directly.</li><li>Several conditions into a single check, it’s better to group them in some way or brackets can help too.</li><li>Use braces</li><li>Avoid switch fall-through</li><li>Replace magic numbers with constants i.e. number/constants in the program should be named and then used.</li><li>Use enums (i.e. convert magic numbers to enum) such that we can’t send any invalid value to fn. I.e. to prevent illegal value input so use enum instead of integers.</li><li>ForEach over for loops</li><li>Avoid compute intensive operations during iteration. If they can be computed once and then used, so do that.</li><li>Group similar code and separate different codes with new lines.</li><li>Use string.format over concatenation.</li><li>Replace comments with utility functions or files.</li><li>Document implementation decisions.</li></ul><p>In the context of [USE CASE], facing [CONCERN], we decided for [OPTION], to achieve [QUALITY], accepting [DOWNSIDE].</p><ul><li>Document using examples</li><li>Always fail fast</li><li>Catch more specific exceptions.</li><li>Check type before cast.</li><li>Standalone tests and parameterized tests</li><li>Split methods with boolean params</li><li>Split methods with optional params</li><li>Favour abstract over concrete (example: Collection over LinkedList or ArrayList)</li><li>Favour Immutable over mutable objects (As references of objects can modify wrong objects)</li><li>Avoid leaking references (Return new immutable from class functions)</li><li>Avoid returning NULL instead return a UNSUPPORTED new object (with that name)</li><li>Method references over lambdas and lambdas over anonymous classes</li><li>Functional over imperative style</li><li>Avoid side effects (use reduce or collect)</li><li>Use collect for terminating complex streams.</li><li>Avoid Exceptions in streams instead return some empty things for the same.</li><li>Favour optional over null.</li><li>Avoid Optional fields or params (only use optional as return type)</li><li>Use Optionals as streams (Optional is a stream with 0 or 1 element)</li><li>Favour logging over console output.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0857c45f3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>