<?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 Abhijeet Karmakar on Medium]]></title>
        <description><![CDATA[Stories by Abhijeet Karmakar on Medium]]></description>
        <link>https://medium.com/@abhijeetkarmakar1920?source=rss-25d66cc9b4c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BUW0vQniMzZmHKDszzRIEg.jpeg</url>
            <title>Stories by Abhijeet Karmakar on Medium</title>
            <link>https://medium.com/@abhijeetkarmakar1920?source=rss-25d66cc9b4c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:59:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhijeetkarmakar1920/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[System Design Interview: Scaling Image Classification & Analytics at Visa]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/system-design-interview-scaling-image-classification-analytics-at-visa-bacb5f4326a3?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bacb5f4326a3</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[visa]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 17:43:28 GMT</pubDate>
            <atom:updated>2026-02-27T17:43:28.882Z</atom:updated>
            <content:encoded><![CDATA[<p>In a recent Senior Software Engineer interview at Visa, I was tasked with designing a system that handles large-scale image uploads, performs automated classification, and provides real-time analytics to subscribed users.</p><p>Here is the architectural approach I took to balance high-write throughput with low-latency analytical reads.</p><h3>1. Requirements &amp; Scoping</h3><h3>Functional Requirements (FR)</h3><ul><li><strong>Image Upload:</strong> Users can upload single or multiple images.</li><li><strong>Auto-Classification:</strong> System must identify objects/categories in the image using ML.</li><li><strong>Subscription Model:</strong> Access to analytics is gated based on user tiers (Basic vs. Premium).</li><li><strong>Real-time Dashboard:</strong> Users can view aggregated classification metrics (e.g., “Top 5 categories uploaded today”).</li></ul><h3>Non-Functional Requirements (NFR)</h3><ul><li><strong>Scalability:</strong> Must handle millions of uploads per day.</li><li><strong>Availability:</strong> High availability for both the upload and dashboard services.</li><li><strong>Durability:</strong> Images and classification results must not be lost.</li><li><strong>Consistency:</strong> Eventual consistency is acceptable for analytics, but the upload must be highly reliable.</li></ul><h3>2. Core Entities</h3><p>To keep the data model clean, I identified three primary entities:</p><ul><li><strong>User/Subscriber:</strong> Stores profile data and subscription_tier (Free, Pro, Enterprise).</li><li><strong>Image Metadata:</strong> Stores the image_url, user_id, timestamp, and status (Pending, Processed, Failed).</li><li><strong>Classification Result:</strong> Stores the tags identified (e.g., &quot;Car&quot;, &quot;Nature&quot;) and the confidence_score.</li></ul><h3>3. API Design</h3><p>I proposed a RESTful approach for the main interactions:</p><ul><li><strong>POST</strong> /v1/images/upload-url<br><em>Purpose:</em> Get a presigned S3 URL to avoid bottlenecking the app server.</li><li><strong>GET</strong> /v1/analytics/dashboard<br><em>Purpose:</em> Fetch aggregated data for the user’s dashboard.</li><li><strong>GET</strong> /v1/subscriptions/status<br><em>Purpose:</em> Validate access levels.</li></ul><h3>4. High-Level Design (HLD)</h3><p>The architecture is split into two main flows: the <strong>Write Path</strong> (Ingestion) and the <strong>Read Path</strong> (Analytics).</p><h3>The Write Path (Ingestion &amp; AI)</h3><ol><li><strong>Direct Upload:</strong> The client requests a Presigned URL from the <strong>Upload Service</strong>. The image is uploaded directly to <strong>Amazon S3</strong>.</li><li><strong>Async Trigger:</strong> An S3 Event triggers a <strong>Lambda</strong> function that pushes a message into an <strong>SQS Queue</strong>. This decouples the upload from the processing.</li><li><strong>ML Processing:</strong> <strong>Classification Workers</strong> consume from SQS and send the image to an AI model (like AWS Rekognition).</li><li><strong>Metadata Storage:</strong> Results are saved in <strong>DynamoDB</strong> (for fast lookups) and the raw image metadata is stored in a <strong>Relational DB</strong> (PostgreSQL) for transactional integrity.</li></ol><h3>The Read Path (Real-time Analytics)</h3><ol><li><strong>Stream Ingestion:</strong> Classification results are pushed to <strong>Amazon Kinesis</strong>.</li><li><strong>Stream Processing:</strong> <strong>Apache Flink</strong> or Kinesis Analytics performs windowed aggregations (e.g., counting tags per minute).</li><li><strong>Serving Layer:</strong> Aggregated data is stored in <strong>Redis</strong> for sub-millisecond dashboard rendering.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOKy2pCIGE2xObHOrLZSEQ.png" /></figure><h3>5. Deep Dives</h3><h3>Handling the “Visa Scale” with Backpressure</h3><p>One critical discussion point was handling spikes in traffic. By using <strong>SQS</strong>, we protect our ML workers. If the AI processing slows down, the messages simply build up in the queue rather than crashing the service. We can then auto-scale the workers based on the ApproximateNumberOfMessagesVisible metric.</p><h3>Subscription Gating at the Edge</h3><p>To ensure low latency for the dashboard, I suggested checking subscription status at the <strong>API Gateway</strong> level using a <strong>Lambda@Edge</strong> or a sidecar cache. This prevents unauthorized requests from even reaching our expensive analytics processing layer.</p><h3>Data Partitioning in DynamoDB</h3><p>To avoid “hot partitions” (e.g., one celebrity user uploading thousands of images), I proposed using a composite primary key: partition_key = user_id and sort_key = timestamp. For global analytics, we would use <strong>Global Secondary Indexes (GSI)</strong> based on tags.</p><h3>Conclusion</h3><p>This design demonstrates a modern, event-driven approach to a common fintech/data problem. By offloading heavy processing to asynchronous workers and using a dedicated streaming pipeline for analytics, we ensure the system remains responsive and cost-effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bacb5f4326a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flipkart | SDE 2 | Interview Experience]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/flipkart-sde-2-interview-experience-e52db909af0b?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e52db909af0b</guid>
            <category><![CDATA[flipkart]]></category>
            <category><![CDATA[sde2]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 16:06:00 GMT</pubDate>
            <atom:updated>2026-02-09T16:06:00.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOuLCigx7jooROLwJ-bcwg.png" /></figure><p>Recently went through the interview process for the Software Development Engineer-2 role at Flipkart, and wanted to share a quick breakdown of the rounds and my learnings.</p><h4>Round 1 — Hiring Manager Round</h4><p>A deep dive into my current project architecture. The discussion focused heavily on:<br>Architectural decisions &amp; trade-offs<br>How I approach problems when only requirements are given<br>Thought process, ownership, and behavioral aspects<br>This round tested clarity of thinking more than just technical knowledge.</p><h4>Round 2 — Machine Coding Round</h4><p>End-to-end implementation with emphasis on:<br>Clean code and structure<br>Edge cases<br>Scalability and extensibility</p><h4>Round 3 — Problem Solving / DSA</h4><p>String manipulation (Medium)<br>Graph problem using DFS (Medium)</p><h4>Round 4 — Low Level Design (Booking System)</h4><p>Deep dive into:<br>Database schema design<br>API design<br>Follow-up questions around scalability, constraints, and real-world scenarios<br>Locking Mechanisms (pessimistic vs optimistic vs distributed locks)</p><h4>Round 5 — High Level Design (Variant of Job Scheduler)</h4><p>More detailed discussions around:<br>Architectural choices<br>CAP tradeoffs for different modules in the system<br>Trade-offs between different design approaches<br>How decisions change with scale and business requirements</p><p># Key Takeaway:<br> Flipkart’s interviews strongly emphasize fundamentals, clarity of thought, and real-world system design experience. Being able to explain why you choose a solution is as important as the solution itself.<br>Hope this helps anyone preparing for SDE-2 interviews. Happy to discuss or answer questions — feel free to reach out! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52db909af0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visa | Senior Software Engineer (Backend + AI) | Interview Experience]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/visa-senior-software-engineer-backend-ai-interview-experience-3b6d951dae89?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b6d951dae89</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[visa]]></category>
            <category><![CDATA[senior-software-engineer]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 10:58:21 GMT</pubDate>
            <atom:updated>2026-02-09T10:58:21.822Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoCWvUlXH82lDrlBFICFFw.png" /></figure><p>I recently completed the interview process for Senior Software Engineer (Backend + AI) at Visa. Sharing my experience for anyone preparing for similar backend + AI roles.</p><h4>Application: Referral</h4><h4>Round 1 — Online Assessment (CodeSignal | 70 mins)</h4><p>4 coding questions<br>2 easy<br>1 easy but implementation-heavy<br>1 medium (Trie-based problem)</p><h4>Round 2 — Technical Interview (Medium)</h4><p>Core concepts: DNS, Java, Spring Boot, Kafka, Microservices<br>2 DSA problems (1 easy, 1 medium)<br>DSA questions aligned with the NeetCode 150 list</p><h4>Round 3 — System Design (Hard)</h4><p>Designed an upload/download service with backend processing for classification<br>Subscription-based access model<br>Real-time dashboard monitoring using stream processing<br>Discussion on Flink vs Spark trade-offs (latency, state management, scalability)</p><h4>Round 4 — Hiring Manager Round</h4><p>Deep dive into my PR Review Tool project<br>LLM-focused discussions:<br>Why LangGraph over Spring AI<br>MCP concepts and tools<br>Graph design (number of nodes, orchestration)<br>Preventing hallucinations<br>Chat memory for feedback and continuous learning<br>Followed by general behavioral questions</p><h4>Verdict: Selected</h4><p>Overall, the process was challenging, well-structured, and very practical, especially around real-world backend systems and applied AI design.</p><p>Resources:<br>DSA — <a href="https://www.linkedin.com/in/mazhar-imam-khan-95a34ab3/">Mazhar Imam Khan</a> <a href="https://www.linkedin.com/company/takeuforward/">takeUforward</a> <br>System Design — <a href="https://www.linkedin.com/company/hello-interview/">Hello Interview</a> <a href="https://www.linkedin.com/company/educative-inc/">Educative</a> Jordan has no life<br>Hope this helps others preparing for Visa or similar roles.<br>Happy to answer questions or discuss preparation strategies 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b6d951dae89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extensible Order Notification System | LLD | Flipkart | Cleartrip]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/extensible-order-notification-system-lld-flipkart-cleartrip-3a606c026493?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a606c026493</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 14:33:48 GMT</pubDate>
            <atom:updated>2025-10-31T14:33:48.164Z</atom:updated>
            <content:encoded><![CDATA[<p>This problem was asked in SDE 2 machine coding round in Flipkart. Lately it’s been asked in several other companies like Cleartrip, Goldman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*Sd5891X76EV6XINpRxBV9w.png" /></figure><h3>1. The Problem at Hand</h3><p>We need to design a notification system that can:</p><ul><li>Notify multiple stakeholders (e.g., CUSTOMER, SELLER, DELIVERY).</li><li>Handle various order lifecycle events (e.g., ORDERED, SHIPPED, DELIVERED).</li><li>Allow each stakeholder to subscribe to specific events for a specific order.</li><li>Allow them to choose their preferred notification channels (e.g., EMAIL, SMS).</li><li>Be easily extensible to add new channels (like Slack) or new events (like RETURNED) in the future.</li></ul><h3>2. Core Design: Decoupling with Strategy and Factory</h3><p>Our design hinges on a few key patterns to keep things separated and flexible.</p><ul><li><strong>Strategy Pattern:</strong> We’ll treat each notification channel (Email, SMS) as a “strategy.” We’ll define a common NotificationChannel interface that every channel must implement. This allows our system to <em>use</em> a channel without knowing its <em>implementation</em> details.</li><li><strong>Factory Pattern:</strong> We’ll use a NotificationChannelFactory to create and provide instances of these channels. This decouples the client (our service) from the concrete channel classes (e.g., new EmailNotificationChannel()).</li><li><strong>Singleton Services:</strong> To keep the wiring simple for this demo, our core services (SubscriptionService, OrderEventService) will be singletons.</li><li><strong>Event-Based Subscriptions:</strong> The core data structure will be a map that links an orderId and an OrderEventType to a list of Subscription objects. When an event fires, we just look up the matching subscriptions and notify them.</li></ul><h3>3. The Building Blocks: Models and Enums</h3><p>First, let’s define the core data structures. We use simple enum types to represent our fixed sets of data.</p><pre>public enum OrderEventType { ORDERED, SHIPPED, DELIVERED }<br><br>public enum MemberType { CUSTOMER, SELLER, DELIVERY }<br><br>public enum NotificationChannelType { EMAIL, SMS }</pre><p>Next, our domain models. We use a record for the immutable Member and a class with a Builder pattern for the Notification payload.</p><pre>// src/model/Member.java<br>public record Member(String id, MemberType type, String name) {}</pre><pre>// src/model/Notification.java<br>public class Notification {<br>    private String timestamp, orderId, memberId, message;<br>    private OrderEventType eventType;<br>    private NotificationChannelType channel;<br>    <br>    // Private constructor for the builder<br>    private Notification() {}<br>    // Public method to format the final message<br>    public String sendMessage(){<br>        return String.format(&quot;[%s][NOTIFICATION][%s][%s][%s][%s] - \&quot;%s\&quot;&quot;,<br>            timestamp, orderId, eventType, memberId, channel, message);<br>    }<br>    <br>    // Getters<br>    public String getOrderId(){ return orderId; }<br>    public String getMemberId(){ return memberId; }<br>    public NotificationChannelType getChannel(){ return channel; }<br>    // --- Builder Inner Class ---<br>    public static class Builder {<br>        Notification n = new Notification();<br>        public Builder setTimestamp(String s){ n.timestamp=s; return this; }<br>        public Builder setOrderId(String s){ n.orderId=s; return this; }<br>        public Builder setEventType(OrderEventType e){ n.eventType=e; return this; }<br>        public Builder setMemberId(String s){ n.memberId=s; return this; }<br>        public Builder setChannel(NotificationChannelType ch){ n.channel=ch; return this; }<br>        public Builder setMessage(String s){ n.message=s; return this; }<br>        public Notification build(){ return n; }<br>    }<br>}</pre><p>The most important model is the Subscription. This object holds the logic for fanning out an event to a member&#39;s configured channels. Notice how its update method iterates over its list of channels and sends a notification to each.</p><pre>// src/model/Subscription.java<br>public record Subscription(String subscriptionId, Member member, List&lt;NotificationChannel&gt; channels) {<br>    // ... constructor, addChannel, removeChannel ...<br>  public Subscription(String subscriptionId, Member member, List&lt;NotificationChannel&gt; channels) {<br>          this.subscriptionId = subscriptionId;<br>          this.member = member;<br>          this.channels = new ArrayList&lt;&gt;(channels);<br>      }<br>      public void addChannel(NotificationChannel channel){ channels.add(channel); }<br>      public void removeChannel(NotificationChannel channel){ channels.remove(channel); }<br>    // This is the fan-out logic<br>      public void update(String orderId, OrderEventType type, LocalDateTime timestamp){<br>          NotificationService service = NotificationService.getInstance();<br>          for (NotificationChannel channel : channels) {<br>              // Build a stakeholder-specific message<br>              String message = NotificationMessageFactory.build(member, type);<br>              <br>              // Create the notification payload<br>              Notification notification = new Notification.Builder()<br>                  .setChannel(channel.getType())<br>                  .setEventType(type)<br>                  .setOrderId(orderId)<br>                  .setMemberId(member.id())<br>                  .setTimestamp(timestamp.toString())<br>                  .setMessage(message)<br>                  .build();<br>              <br>              // Send it!<br>              service.sendNotification(channel, notification);<br>          }<br>      }<br>  }</pre><h3>4. The “How”: Strategy and Factory in Action</h3><p>This is the heart of our extensible design.</p><h3>The Strategy</h3><p>First, we define the “contract” or interface that all notification channels must follow.</p><pre>// src/strategy/NotificationChannel.java<br>public interface NotificationChannel {<br>    void send(Notification notification);<br>    NotificationChannelType getType();<br>}</pre><p>Implementing this is trivial. We can create as many as we need, and the rest of our system doesn’t care <em>how</em> they work, only that they <em>can</em> send.</p><pre>// src/strategy/EmailNotificationChannel.java<br>public class EmailNotificationChannel implements NotificationChannel{<br>    public void send(Notification notification){ <br>        System.out.println(notification.sendMessage()); <br>    }<br>    public NotificationChannelType getType(){ return NotificationChannelType.EMAIL; }<br>}<br><br>// src/strategy/SMSNotificationChannel.java<br>public class SMSNotificationChannel implements NotificationChannel{<br>    public void send(Notification notification){ <br>        System.out.println(notification.sendMessage()); <br>    }<br>    public NotificationChannelType getType(){ return NotificationChannelType.SMS; }<br>}</pre><h3>The Factories</h3><p>How do we get an EmailNotificationChannel? We ask a factory. This NotificationChannelFactory holds a map of instances, ensuring we only have one instance of each channel (a flyweight-style approach).</p><pre>// src/factory/NotificationChannelFactory.java<br>public class NotificationChannelFactory {<br>    private static final Map&lt;NotificationChannelType, NotificationChannel&gt; notificationChannelMap = new HashMap&lt;&gt;();<br>public static NotificationChannel getNotificationChannel(NotificationChannelType type){<br>        // Compute if absent ensures thread-safe, lazy initialization<br>        notificationChannelMap.computeIfAbsent(type, k -&gt; createNotificationChannel(type));<br>        return notificationChannelMap.get(type);<br>    }<br>    <br>    private static NotificationChannel createNotificationChannel(NotificationChannelType type){<br>        return switch (type){<br>            case SMS -&gt; new SMSNotificationChannel();<br>            case EMAIL -&gt; new EmailNotificationChannel();<br>        };<br>    }<br>}</pre><p>We also use a factory to build our messages. This NotificationMessageFactory is crucial for good UX—it ensures a customer gets a &quot;Congrats!&quot; message while a seller gets an &quot;Action required&quot; message for the <em>same</em> ORDERED event.</p><p>Java</p><pre>// src/factory/NotificationMessageFactory.java (stakeholder-aware)<br>public class NotificationMessageFactory {<br>    // Maps to hold templates: Event -&gt; Member -&gt; Message<br>    private static final Map&lt;OrderEventType, Map&lt;MemberType, String&gt;&gt; BASE_MESSAGES = new EnumMap&lt;&gt;(OrderEventType.class);<br>    private static final Map&lt;OrderEventType, String&gt; EVENT_DEFAULTS = new EnumMap&lt;&gt;(OrderEventType.class);<br>    // Static initializer block to populate templates<br>    static {<br>        // ... (populating maps for ORDERED, SHIPPED, DELIVERED) ...<br>        // Example for ORDERED:<br>        Map&lt;MemberType, String&gt; ordered = new EnumMap&lt;&gt;(MemberType.class);<br>        ordered.put(MemberType.SELLER, &quot;an item has been placed from your shop&quot;);<br>        ordered.put(MemberType.CUSTOMER, &quot;congrats! your order has been placed&quot;);<br>        ordered.put(MemberType.DELIVERY, &quot;an order has been placed for your pickup&quot;);<br>        BASE_MESSAGES.put(OrderEventType.ORDERED, ordered);<br>        // ...<br>    }<br>    public static String build(Member member, OrderEventType type){<br>        MemberType mType = member != null ? member.type() : null;<br>        return resolveBaseMessage(type, mType);<br>    }<br>    private static String resolveBaseMessage(OrderEventType type, MemberType memberType){<br>        // ... (logic to find the best message, falling back to defaults) ...<br>        if (type == null) return &quot;order update&quot;;<br>        Map&lt;MemberType, String&gt; byMember = BASE_MESSAGES.get(type);<br>        String eventDefault = EVENT_DEFAULTS.getOrDefault(type, &quot;order update&quot;);<br>        if (byMember == null || memberType == null) return eventDefault;<br>        return byMember.getOrDefault(memberType, eventDefault);<br>    }<br>}</pre><h3>5. Wiring It All Together: The Services</h3><p>With our models and patterns in place, the services that run the system are surprisingly simple.</p><h3>SubscriptionService</h3><p>This is the “brain” that manages who is subscribed to what. Its core is a Map&lt;String, Map&lt;OrderEventType, List&lt;Subscription&gt;&gt;&gt;, which maps an orderId to its event subscriptions.</p><pre>// src/service/SubscriptionService.java<br>public class SubscriptionService {<br>    // The core data structure: orderId -&gt; eventType -&gt; List&lt;Subscription&gt;<br>    private final Map&lt;String, Map&lt;OrderEventType, List&lt;Subscription&gt;&gt;&gt; subscriptions;<br>    <br>    // Singleton pattern<br>    private SubscriptionService(){ subscriptions = new HashMap&lt;&gt;(); }<br>    private static class SubscriptionServiceHolder{ public static final SubscriptionService INSTANCE = new SubscriptionService(); }<br>    public static SubscriptionService getInstance(){ return SubscriptionServiceHolder.INSTANCE; }<br>  public void createSubscription(String orderId, Member member, List&lt;OrderEventType&gt; eventTypes, List&lt;NotificationChannelType&gt; channelTypes){<br>          Map&lt;OrderEventType, List&lt;Subscription&gt;&gt; map = subscriptions.computeIfAbsent(orderId, k -&gt; new HashMap&lt;&gt;());<br>          for (OrderEventType type : eventTypes){<br>              List&lt;Subscription&gt; list = map.computeIfAbsent(type, k -&gt; new ArrayList&lt;&gt;());<br>              List&lt;NotificationChannel&gt; channels = channelTypes.stream()<br>                  .map(NotificationChannelFactory::getNotificationChannel).toList();<br>              String subId = &quot;SUB&quot; + UUID.randomUUID();<br>              list.add(new Subscription(subId, member, channels));<br>          }<br>      }<br>      <br>      public List&lt;Subscription&gt; getSubscriptions(String orderId, OrderEventType type){ <br>          return subscriptions.get(orderId).get(type); <br>      }<br>      public void unsubscribe(String orderId, Member member, OrderEventType type){<br>          // ... (logic to find and remove subscription) ...<br>        Subscription sub = subscriptions.get(orderId).get(type).stream().filter(s -&gt; s.member().equals(member)).findFirst().get();<br>        subscriptions.get(orderId).get(type).remove(sub);<br>        System.out.println(&quot;[SUBSCRIPTION CHANGE] &quot; + member.id() + &quot; unsubscribed from &quot; + type + &quot; for &quot; + orderId);<br>      }<br>      public void editChannelInSubscription(String orderId, Member member, NotificationChannelType channelType, boolean add){<br>          // ... (logic to find subscription and add/remove channel) ...<br>        Map&lt;OrderEventType, List&lt;Subscription&gt;&gt; map = subscriptions.get(orderId);<br>                for (List&lt;Subscription&gt; list : map.values()){<br>                    for (Subscription subscription : list){<br>                        if (subscription.member().equals(member)){<br>                            if (add) subscription.addChannel(NotificationChannelFactory.getNotificationChannel(channelType));<br>                            else subscription.removeChannel(NotificationChannelFactory.getNotificationChannel(channelType));<br>                        }<br>                    }<br>                }<br>          }<br>    }</pre><h3>OrderEventService</h3><p>This is the main entry point for the rest of your application. When an order is shipped, the OrderService would simply call this.</p><p>Java</p><pre>// src/service/OrderEventService.java<br>public class OrderEventService {<br>    // Singleton pattern<br>    private OrderEventService() {}<br>    private static class OrderEventServiceHolder { private static final OrderEventService INSTANCE = new OrderEventService(); }<br>    public static OrderEventService getInstance(){ return OrderEventServiceHolder.INSTANCE; }<br>    private final SubscriptionService subscriptionService = SubscriptionService.getInstance();<br>    public void publishEvent(String orderId, OrderEventType type){<br>        List&lt;Subscription&gt; subscriptions = subscriptionService.getSubscriptions(orderId, type);<br>        if (subscriptions == null) subscriptions = Collections.emptyList();<br>        <br>        LocalDateTime timestamp = LocalDateTime.now();<br>        // Delegate to each subscription<br>        for (Subscription sub : subscriptions){ <br>            sub.update(orderId, type, timestamp); <br>        }<br>    }<br>}</pre><h3>NotificationService</h3><p>This is the final “worker” that performs the send operation and — as a bonus — keeps an in-memory history for replay.</p><p>Java</p><pre>// src/service/NotificationService.java<br>public class NotificationService {<br>    // Singleton pattern<br>    private NotificationService() {}<br>    private static final class NotificationServiceHolder{ public static final NotificationService INSTANCE = new NotificationService(); }<br>    public static NotificationService getInstance(){ return NotificationServiceHolder.INSTANCE; }<br>    // In-memory history: (orderId|memberId) -&gt; List&lt;Notification&gt;<br>    private final Map&lt;String, List&lt;Notification&gt;&gt; history = new HashMap&lt;&gt;();<br>    private String key(String orderId, String memberId){ return orderId + &quot;|&quot; + memberId; }<br>    public void sendNotification(NotificationChannel channel, Notification notification){<br>        // 1. Save to history<br>        history.computeIfAbsent(<br>            key(notification.getOrderId(), notification.getMemberId()), <br>            k -&gt; new ArrayList&lt;&gt;()<br>        ).add(notification);<br>        <br>        // 2. Send<br>        channel.send(notification);<br>    }<br>    public void replayNotifications(String orderId, String memberId){<br>        List&lt;Notification&gt; list = history.getOrDefault(key(orderId, memberId), Collections.emptyList());<br>        if (list.isEmpty()){<br>            System.out.println(&quot;[REPLAY] No notifications to replay for order=&quot; + orderId + &quot;, member=&quot; + memberId);<br>            return;<br>        }<br>        for (Notification n : list){<br>            // Get the correct channel from the factory and resend<br>            NotificationChannel channel = NotificationChannelFactory.getNotificationChannel(n.getChannel());<br>            channel.send(n);<br>        }<br>    }<br>}</pre><h3>6. Seeing It Run: End-to-End Demo</h3><p>Let’s run a simulation. We’ll have a customer, “Alice,” and a “Book Seller” subscribe to events for “order1”.</p><p>Java</p><pre>// src/NotificationClient.java<br>public class NotificationClient {<br>    public static void main(String... args) {<br>        SubscriptionService subscriptionService = SubscriptionService.getInstance();<br>        OrderEventService orderEventService = OrderEventService.getInstance();<br>        NotificationService notificationService = NotificationService.getInstance();<br>        // 1. Create stakeholders<br>        Member alice = new Member(&quot;customer1&quot;, MemberType.CUSTOMER, &quot;Alice&quot;);<br>        Member seller = new Member(&quot;seller1&quot;, MemberType.SELLER, &quot;Book Seller&quot;);<br>        // 2. Alice subscribes to all events on EMAIL<br>        subscriptionService.createSubscription(&quot;order1&quot;, alice,<br>            List.of(OrderEventType.ORDERED, OrderEventType.SHIPPED, OrderEventType.DELIVERED),<br>            List.of(NotificationChannelType.EMAIL));<br>        // 3. Seller subscribes to just ORDERED on EMAIL<br>        subscriptionService.createSubscription(&quot;order1&quot;, seller,<br>            List.of(OrderEventType.ORDERED), List.of(NotificationChannelType.EMAIL));<br>        // 4. Fire ORDERED event<br>        System.out.println(&quot;--- Publishing ORDERED ---&quot;);<br>        orderEventService.publishEvent(&quot;order1&quot;, OrderEventType.ORDERED);<br>        <br>        // 5. Alice unsubscribes from SHIPPED<br>        subscriptionService.unsubscribe(&quot;order1&quot;, alice, OrderEventType.SHIPPED);<br>        // 6. Fire SHIPPED event (Alice won&#39;t be notified)<br>        System.out.println(&quot;--- Publishing SHIPPED ---&quot;);<br>        orderEventService.publishEvent(&quot;order1&quot;, OrderEventType.SHIPPED);<br>        <br>        // 7. Alice adds SMS as a channel<br>        subscriptionService.editChannelInSubscription(&quot;order1&quot;, alice, NotificationChannelType.SMS, true);<br>        <br>        // 8. Fire DELIVERED event (Alice gets EMAIL and SMS)<br>        System.out.println(&quot;--- Publishing DELIVERED ---&quot;);<br>        orderEventService.publishEvent(&quot;order1&quot;, OrderEventType.DELIVERED);<br>        // 9. Replay all notifications for Alice<br>        System.out.println(&quot;--- Replaying notifications for Alice (customer1) ---&quot;);<br>        notificationService.replayNotifications(&quot;order1&quot;, &quot;customer1&quot;);<br>    }<br>}</pre><h3>Expected Output</h3><p>(Timestamps omitted for clarity)</p><pre>--- Publishing ORDERED ---<br>[...][NOTIFICATION][order1][ORDERED][customer1][EMAIL] - &quot;congrats! your order has been placed&quot;<br>[...][NOTIFICATION][order1][ORDERED][seller1][EMAIL] - &quot;an item has been placed from your shop&quot;<br>[SUBSCRIPTION CHANGE] customer1 unsubscribed from SHIPPED for order1<br>--- Publishing SHIPPED ---<br>(No output, as Alice unsubscribed and Seller was never subscribed)<br>--- Publishing DELIVERED ---<br>[...][NOTIFICATION][order1][DELIVERED][customer1][EMAIL] - &quot;hooray! your order has been delivered&quot;<br>[...][NOTIFICATION][order1][DELIVERED][customer1][SMS] - &quot;hooray! your order has been delivered&quot;<br>--- Replaying notifications for Alice (customer1) ---<br>[...][NOTIFICATION][order1][ORDERED][customer1][EMAIL] - &quot;congrats! your order has been placed&quot;<br>[...][NOTIFICATION][order1][DELIVERED][customer1][EMAIL] - &quot;hooray! your order has been delivered&quot;<br>[...][NOTIFICATION][order1][DELIVERED][customer1][SMS] - &quot;hooray! your order has been delivered&quot;</pre><p>It works perfectly! The replay correctly shows only Alice’s notifications.</p><h3>7. The Payoff: Extending the System</h3><p>So, how easy is it to extend?</p><ul><li><strong>To add a new channel (e.g., Slack):</strong></li><li>Create SlackNotificationChannel.java implementing NotificationChannel.</li><li>Add SLACK to the NotificationChannelType enum.</li><li>Add case SLACK -&gt; new SlackNotificationChannel() to the NotificationChannelFactory.</li><li>…That’s it. The rest of the system will support it automatically.</li><li><strong>To add a new stakeholder (e.g., </strong><strong>WAREHOUSE):</strong></li><li>Add WAREHOUSE to the MemberType enum.</li><li>Add warehouse-specific messages to NotificationMessageFactory.</li><li>…Done.</li><li><strong>To add a new event (e.g., </strong><strong>RETURNED):</strong></li><li>Add RETURNED to the OrderEventType enum.</li><li>Add default and stakeholder-specific messages for it in NotificationMessageFactory.</li><li>…Done.</li></ul><h3>8. Conclusion: Real-World Considerations</h3><p>This demo provides a solid, extensible foundation. For a production-grade system, you would add a few more pieces:</p><ul><li><strong>Concurrency:</strong> Our in-memory HashMaps are not thread-safe. You&#39;d replace them with ConcurrentHashMap and use thread-safe lists for subscriptions.</li><li><strong>Asynchronous Sending:</strong> You don’t want your OrderEventService to block while sending an email. You&#39;d wrap the NotificationService.sendNotification call in an ExecutorService (a thread pool) to make it asynchronous.</li><li><strong>Message Queue (The “Real” Way):</strong> For true decoupling and durability, the OrderEventService wouldn&#39;t call the SubscriptionService directly. It would publish an event message to a <strong>Message Queue</strong> (like Kafka or RabbitMQ). A separate fleet of &quot;Notification&quot; consumers would listen to this queue, look up subscriptions, and send the notifications. This makes the system resilient to failures and infinitely scalable.</li></ul><p>The complete code could be found in the github link —</p><p><a href="https://github.com/abhij33t99/low-level-design/tree/main/notification-system">https://github.com/abhij33t99/low-level-design/tree/main/notification-system</a></p><p>Thank you for reading! I hope you found this practical breakdown of a notification system useful. If you enjoy deep dives into software design, Java patterns, and system architecture, be sure to <strong>follow me for more content</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a606c026493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency In Depth-4 (Phaser & Exchangers)]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/java-concurrency-in-depth-4-phaser-exchangers-42009348fca5?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/42009348fca5</guid>
            <category><![CDATA[phaser]]></category>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[exchanger]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 14:19:51 GMT</pubDate>
            <atom:updated>2024-11-18T13:22:44.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Concurrency In Depth-4 (Phaser &amp; Exchanger)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKnpZ3D65KhVxR_OV5wh1w.jpeg" /></figure><p>In this section, we will learn how to use couple of high-level mechanisms to synchronize multiple threads. They are as follows :</p><ul><li><strong>Phaser</strong>: The Phaser class is another mechanism provided by the Java language that controls the execution of concurrent tasks divided in phases. All the threads must finish one phase before they can continue with the next one.</li><li><strong>Exchanger</strong>: The Exchanger class is another mechanism provided by the Java language that provides a point of data interchange between two threads.</li></ul><h3>Phaser — Running concurrent-phased tasks</h3><p>One of the most complex and powerful functionalities offered by the Java concurrency API is the ability to execute concurrent-phased tasks using the <strong>Phaser</strong> class.</p><p>This mechanism is useful when we have some <strong>concurrent tasks divided into steps</strong>. The Phaser class provides us with a mechanism to <strong>synchronize</strong> threads at the end of each step, so no thread will start with the second step until all the threads have finished the first one.</p><p>A Phaser object can be in two states:</p><ul><li><strong>Active</strong>: Phaser enters this state when it accepts the registration of new participants and its synchronization at the end of each phase. In this state, Phaser works as it has been explained in this recipe. This state is not mentioned in the Java concurrency API.</li><li><strong>Termination</strong>: By default, Phaser enters this state when all the participants in Phaser have been deregistered, which means it has zero participants. Further, Phaser is in the termination state when the method onAdvance() returns true.</li></ul><pre>package abhij33t;<br><br>import java.io.File;<br>import java.time.Instant;<br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.Phaser;<br>import java.util.concurrent.TimeUnit;<br>class FileSearch implements Runnable {<br>    private final String path;<br>    private final String fileExtension;<br>    private List&lt;String&gt; results;<br>    private Phaser phaser;<br>    public FileSearch(String path, String fileExtension, Phaser phaser) {<br>        this.path = path;<br>        this.fileExtension = fileExtension;<br>        this.phaser = phaser;<br>        results = new ArrayList&lt;&gt;();<br>    }<br>    public void run() {<br>       phaser.arriveAndAwaitAdvance();<br>        System.out.printf(&quot;%s: Starting.\n&quot;,<br>                Thread.currentThread().getName());<br>        File file = new File(path);<br>        if (file.isDirectory())<br>            proccessDirectory(file);<br>        if (!checkResults())<br>            return;<br>        filterResults();<br>        if (!checkResults())<br>            return;<br>        showInfo();<br>        phaser.arriveAndDeregister();<br>        System.out.printf(&quot;%s: Work completed.\n&quot;,<br>                Thread.currentThread().getName());<br>    }<br>    private void proccessDirectory(File file) {<br>        var files = file.listFiles();<br>        if (files != null) {<br>            for (File f : files) {<br>                if (f.isDirectory()) {<br>                    proccessDirectory(f);<br>                } else {<br>                    processFile(f);<br>                }<br>            }<br>        }<br>    }<br>    private void processFile(File file) {<br>        if (file.getName().endsWith(fileExtension)) {<br>            results.add(file.getAbsolutePath());<br>        }<br>    }<br>    private void filterResults() {<br>        List&lt;String&gt; newResults = new ArrayList&lt;&gt;();<br>        var date = Instant.now().toEpochMilli();<br>        for (String result : results) {<br>            var file = new File(result);<br>            var lastModified = file.lastModified();<br>            if (date - lastModified &lt; TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)) {<br>                newResults.add(result);<br>            }<br>        }<br>        results = newResults;<br>    }<br>    private boolean checkResults() {<br>        if (results.isEmpty()) {<br>            System.out.printf(&quot;%s: Phase %d: 0 results.\n&quot;,<br>                    Thread.currentThread().getName(),<br>                    phaser.getPhase());<br>            System.out.printf(&quot;%s: Phase %d: End.\n&quot;,<br>                    Thread.currentThread().getName(),<br>                    phaser.getPhase());<br>            phaser.arriveAndDeregister();<br>            return true;<br>        } else {<br>            System.out.printf(&quot;%s: Phase %d: %d results.\n&quot;,<br>                    Thread.currentThread().getName(),<br>                    phaser.getPhase(), results.size());<br>            phaser.arriveAndAwaitAdvance();<br>            return false;<br>        }<br>    }<br>    private void showInfo() {<br>        for (String result : results) {<br>            var file = new File(result);<br>            System.out.printf(&quot;%s: %s\n&quot;,<br>                    Thread.currentThread().getName(),<br>                    file.getAbsolutePath());<br>        }<br>        phaser.arriveAndAwaitAdvance();<br>    }<br>}<br>public class PhaserImpl {<br>    public static void main(String[] args) {<br>        Phaser phaser = new Phaser(3);<br>        FileSearch fileSearch = new FileSearch(&quot;/Users/abhijeetkarmakar/IdeaProjects/JavaConcurrency&quot;, &quot;log&quot;, phaser);<br>        FileSearch apps = new FileSearch(&quot;/Users/abhijeetkarmakar/IdeaProjects/JavaConcurrency&quot;, &quot;app&quot;, phaser);<br>        FileSearch docs = new FileSearch(&quot;/Users/abhijeetkarmakar/IdeaProjects/JavaConcurrency&quot;, &quot;java&quot;, phaser);<br>        Thread fileSearchThread = new Thread(fileSearch, &quot;System&quot;);<br>        fileSearchThread.start();<br>        Thread appsThread = new Thread(apps, &quot;System&quot;);<br>        appsThread.start();<br>        Thread docsThread = new Thread(docs, &quot;System&quot;);<br>        docsThread.start();<br>        try{<br>            fileSearchThread.join();<br>            appsThread.join();<br>            docsThread.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } finally {<br>            System.out.println(&quot;Terminated: &quot;+ phaser.isTerminated());<br>        }<br>    }<br>}</pre><h3>Controlling phase change in concurrent-phased tasks</h3><p>The Phaser class provides a method that is executed each time phaser changes the phase. It’s the <strong>onAdvance</strong>() method.</p><p>It receives two parameters: the number of the current phases and the number of registered participants. It returns a <strong>Boolean</strong> value false if Phaser continues its execution or the value true if Phaser has finished and has to enter the termination state.</p><pre>package abhij33t;<br><br>import java.util.Date;<br>import java.util.concurrent.Phaser;<br>import java.util.concurrent.TimeUnit;<br>class MyPhaser extends Phaser {<br>    @Override<br>    protected boolean onAdvance(int phase, int registeredParties) {<br>        return switch (phase) {<br>            case 0 -&gt; studentsArrived();<br>            case 1 -&gt; finishFirstExcercise();<br>            case 2 -&gt; finishSecondExercise();<br>            case 3 -&gt; finishExam();<br>            default -&gt; true;<br>        };<br>    }<br>    private boolean studentsArrived() {<br>        System.out.print(&quot;Phaser: The exam is going to start. The students are ready.\n&quot;);<br>        System.out.printf(&quot;Phaser: We have %d students.\n&quot;,<br>                getRegisteredParties());<br>        return false;<br>    }<br>    private boolean finishFirstExcercise() {<br>        System.out.print(&quot;Phaser: The first exercise is finished.\n&quot;);<br>        System.out.print(&quot;Phaser: It&#39;s time for the second one.\n&quot;);<br>        return false;<br>    }<br>    private boolean finishSecondExercise() {<br>        System.out.print(&quot;Phaser: All the students have finished the second exercise.\n&quot;);<br>        System.out.print(&quot;Phaser: It&#39;s time for the third one.\n&quot;);<br>        return false;<br>    }<br>    private boolean finishExam() {<br>        System.out.print(&quot;Phaser: All the students have finished the exam.\n&quot;);<br>        System.out.print(&quot;Phaser: Thank you for your time.\n&quot;);<br>        return true;<br>    }<br>}<br> class Student implements Runnable {<br>    private final Phaser phaser;<br>    public Student(Phaser phaser) {<br>        this.phaser = phaser;<br>    }<br>    @Override<br>    public void run() {<br>        System.out.printf(&quot;%s: Has arrived to do the exam. %s\n&quot;, Thread.currentThread().getName(),new Date());<br>        phaser.arriveAndAwaitAdvance();<br>        System.out.printf(&quot;%s: Is going to do the first exercise.%s\n&quot;, Thread.currentThread().getName(),new Date());<br>        doExercise1();<br>        System.out.printf(&quot;%s: Has done the first exercise.%s\n&quot;, Thread.currentThread().getName(),new Date());<br>        phaser.arriveAndAwaitAdvance();<br>        System.out.printf(&quot;%s: Is going to do the second exercise. %s\n&quot;,Thread.currentThread().getName(), new Date());<br>        doExercise2();<br>        System.out.printf(&quot;%s: Has done the second exercise.%s\n&quot;, Thread.currentThread().getName(),new Date());<br>        phaser.arriveAndAwaitAdvance();<br>        System.out.printf(&quot;%s: Is going to do the third exercise.%s\n&quot;, Thread.currentThread().getName(),new Date());<br>        doExercise3();<br>        System.out.printf(&quot;%s: Has finished the exam.%s\n&quot;, Thread.currentThread().getName(),new Date());<br>        phaser.arriveAndAwaitAdvance();<br>    }<br>     private void doExercise1() {<br>         try {<br>             long duration = (long) (Math.random() * 10);<br>             TimeUnit.SECONDS.sleep(duration);<br>         } catch (InterruptedException e) {<br>             e.printStackTrace();<br>         }<br>     }<br>     private void doExercise2() {<br>         try {<br>             long duration = (long) (Math.random() * 10);<br>             TimeUnit.SECONDS.sleep(duration);<br>         } catch (InterruptedException e) {<br>             e.printStackTrace();<br>         }<br>     }<br>     private void doExercise3() {<br>         try {<br>             long duration = (long) (Math.random() * 10);<br>             TimeUnit.SECONDS.sleep(duration);<br>         } catch (InterruptedException e) {<br>             e.printStackTrace();<br>         }<br>     }<br>}<br>public class PhaseImpl2 {<br>    public static void main(String[] args) {<br>        MyPhaser phaser = new MyPhaser();<br>        Student[] students = new Student[5];<br>        for (int i = 0; i &lt; students.length; i++) {<br>            students[i] = new Student(phaser);<br>            phaser.register();<br>        }<br>        Thread[] threads=new Thread[students.length];<br>        for (int i=0; i&lt;students.length; i++){<br>            threads[i]=new Thread(students[i],&quot;Student &quot;+i);<br>            threads[i].start();<br>        }<br>        for (int i=0; i&lt;students.length; i++){<br>            try {<br>                threads[i].join();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>        System.out.printf(&quot;Main: The phaser has finished: %s.\n&quot;, phaser.isTerminated());<br>    }<br>}</pre><h3>Exchanger — Exchanging data between concurrent tasks</h3><p>The Java concurrency API provides a synchronization utility that allows interchange of data between two concurrent tasks. In more detail, the <strong>Exchanger</strong> class allows you to have a definition of a <strong>synchronization point between two threads</strong>.</p><p>When the two threads arrive at this point, they interchange a data structure such that the data structure of the first thread goes to the second one and vice versa.</p><pre>package abhij33t;<br><br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.Exchanger;<br>class ExProducer implements Runnable {<br>    private List&lt;String&gt; buffer;<br>    private final Exchanger&lt;List&lt;String&gt;&gt; exchanger;<br>    public ExProducer(List&lt;String&gt; buffer, Exchanger&lt;List&lt;String&gt;&gt; exchanger) {<br>        this.buffer = buffer;<br>        this.exchanger = exchanger;<br>    }<br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            System.out.printf(&quot;Producer: Cycle %d\n&quot;, i);<br>            for (int j = 0; j &lt; 10; j++) {<br>                String message = &quot;Event &quot; + i * 10 + j;<br>                System.out.printf(&quot;Producer: %s\n&quot;, message);<br>                buffer.add(message);<br>            }<br>            try {<br>                buffer = exchanger.exchange(buffer);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>            System.out.println(&quot;Producer: &quot; + buffer.size());<br>        }<br>    }<br>}<br>class ExConsumer implements Runnable {<br>    private List&lt;String&gt; buffer;<br>    private final Exchanger&lt;List&lt;String&gt;&gt; exchanger;<br>    public ExConsumer(List&lt;String&gt; buffer, Exchanger&lt;List&lt;String&gt;&gt; exchanger) {<br>        this.buffer = buffer;<br>        this.exchanger = exchanger;<br>    }<br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            System.out.printf(&quot;Consumer: Cycle %d\n&quot;, i);<br>            try {<br>                buffer = exchanger.exchange(buffer);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>            System.out.println(&quot;Consumer: &quot; + buffer.size());<br>            for (int j = 0; j &lt; 10; j++) {<br>                String message = buffer.getFirst();<br>                System.out.println(&quot;Consumer: &quot; + message);<br>                buffer.removeFirst();<br>            }<br>        }<br>    }<br>}<br>public class ExchangerImpl {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; buffer1 = new ArrayList&lt;&gt;();<br>        List&lt;String&gt; buffer2 = new ArrayList&lt;&gt;();<br>        Exchanger&lt;List&lt;String&gt;&gt; exchanger = new Exchanger&lt;&gt;();<br>        Thread producer = new Thread(new ExProducer(buffer1, exchanger));<br>        Thread consumer = new Thread(new ExConsumer(buffer2, exchanger));<br>        producer.start();<br>        consumer.start();<br>    }<br>}</pre><p>The Exchanger class has another version of the exchange method: <strong>exchange(V data, long time, TimeUnit unit)</strong>. where, V is the type used as a parameter in the declaration of Phaser (List in our case). The thread will sleep until it’s interrupted, another thread arrives, or the specified time passes. In this case, a <strong>TimeoutException</strong> is thrown.</p><p>That’s all for this article. Thanks for reading, Peace! ☮️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42009348fca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency In Depth-3 (Semaphores, Countdown Latches, Cyclic Barriers)]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/java-concurrency-in-depth-3-semaphores-countdown-latches-cyclic-barriers-3acbec729cdd?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3acbec729cdd</guid>
            <category><![CDATA[cyclic-barrier]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <category><![CDATA[countdownlatch]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 14:02:26 GMT</pubDate>
            <atom:updated>2024-11-17T14:12:29.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uqtD4ZBjaehTBeKxXAzWA.jpeg" /></figure><p>In this section, we will learn how to use high-level mechanisms to synchronize multiple threads. These high-level mechanisms are as follows:</p><ul><li><strong>Semaphores</strong>: A semaphore is a counter that controls access to one or more shared resources. This mechanism is one of the basic tools of concurrent programming and is provided by most programming languages.</li><li><strong>CountDownLatch</strong>: The CountDownLatch class is a mechanism provided by the Java language that allows a thread to wait for the finalization of multiple operations.</li><li><strong>CyclicBarrier</strong>: The CyclicBarrier class is another mechanism provided by the Java language that allows the synchronization of multiple threads at a common point.</li></ul><h3>Semaphores — Controlling concurrent access to one or more copies of a resource</h3><p>When a thread wants to access one of the shared resources, it must first acquire the <strong>semaphore</strong>.</p><p>If the internal counter of the semaphore is greater than 0, the semaphore decrements the counter and allows access to the shared resource. Otherwise, if the counter is 0, the semaphore puts the thread to sleep until the counter is greater than 0.</p><pre>package abhij33t;<br><br>import java.util.Date;<br>import java.util.Arrays;<br>import java.util.concurrent.Semaphore;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.locks.Lock;<br>import java.util.concurrent.locks.ReentrantLock;<br><br>class SPrintQueue {<br>    private final Semaphore semaphore;<br>    private final boolean[] freePrinters;<br>    private final Lock printersLock;<br><br>    public SPrintQueue() {<br>        this.semaphore = new Semaphore(3);<br>        this.freePrinters = new boolean[3];<br>        this.printersLock = new ReentrantLock();<br>        Arrays.fill(freePrinters, true);<br>    }<br><br>    public void printJob(Object document) {<br>        try {<br>            semaphore.acquire();<br>            int assignedPrinter = getPrinter();<br>            long duration = (long) (Math.random() * 10);<br>            System.out.printf(&quot;%s-%s : Printing using printer %d for %d seconds\n&quot;,<br>            new Date(), Thread.currentThread().getName(), assignedPrinter, duration);<br>            TimeUnit.SECONDS.sleep(duration);<br>        } catch (InterruptedException e) { <br>            e.printStackTrace();<br>        } finally {<br>            semaphore.release();<br>        }<br>    }<br><br>    private int getPrinter() {<br>        int ret = -1;<br>        try{<br>        printersLock.lock();<br>        for (int i = 0; i &lt; freePrinters.length; i++) {<br>            if (freePrinters[i]) {<br>                ret = i;<br>                break;<br>            }<br>        }<br>    } catch(Exception e) {<br>        e.printStackTrace();<br>    } finally {<br>        printersLock.unlock();<br>    }<br>        return ret;<br>    }<br><br>}<br><br>class SJob implements Runnable {<br>    private final SPrintQueue printQueue;<br>    public SJob(SPrintQueue printQueue) {<br>        this.printQueue = printQueue;<br>    }<br>    @Override<br>    public void run() {<br>        System.out.printf(&quot;%s: Going to print a document\n&quot;,Thread.currentThread().getName());<br>        printQueue.printJob(new Object());<br>        System.out.printf(&quot;%s: The document has been printed\n&quot;, Thread.currentThread().getName());<br>    }<br>}<br><br>public class SemaphoresImpl {<br>    public static void main(String[] args) {<br>        SPrintQueue printQueue = new SPrintQueue();<br>        Thread[] threads = new Thread[10];<br>        for (int i=0; i&lt;10; i++) {<br>            threads[i] = new Thread(new SJob(printQueue), &quot;Thread &quot;+i );<br>        }<br>        for (int i=0; i&lt;10; i++)<br>            threads[i].start();<br>        for (int i=0; i&lt;10; i++) {<br>            try {<br>                threads[i].join();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}</pre><p>The Semaphore class has three additional versions of the acquire() method:</p><ul><li><strong>acquireUninterruptibly</strong>(): This version of the acquire operation ignores the interruption of the thread and doesn’t throw any exceptions.</li><li><strong>tryAcquire</strong>(): This method tries to acquire the semaphore. If it can, it returns the true value. But if it can’t, it returns false instead of being blocked and waits for the release of the semaphore.</li><li><strong>tryAcquire(long timeout, TimeUnit unit)</strong>: This method is equivalent to the previous one, but it waits for the semaphore for the period of time specified in the parameters. If the period of time ends and the method hasn’t acquired the semaphore, it will return false.</li></ul><p>The acquire(), acquireUninterruptibly(), tryAcquire(), and release() methods have an additional version, which has an int parameter. This parameter represents the number of permits the thread that uses them wants to acquire or release, in other words, the number of units that this thread wants to delete or add to the internal counter of the semaphore.</p><p>The Semaphore class admits a second parameter in its constructor. This parameter must take a Boolean value which determines the fairness of a semaphore.</p><h3>Countdown Latches — Waiting for multiple concurrent events</h3><p>The Java concurrency API provides a class that allows one or more threads to wait until a set of operations are made. It’s called the <strong>CountDownLatch</strong> class. This class is initialized with an integer number, which is the number of operations the threads are going to wait for.</p><p>When a thread wants to wait for the execution of these operations, it uses the <strong>await</strong>() method. This method puts the thread to sleep until the operations are completed.</p><p>When one of these operations finishes, it uses the <strong>countDown</strong>() method to decrement the internal counter of the CountDownLatch class. When the counter arrives at 0, the class wakes up all the threads that were sleeping in the await() method.</p><pre>package abhij33t;<br><br>import java.util.concurrent.CountDownLatch;<br>import java.util.concurrent.TimeUnit;<br><br>class VideoConference implements Runnable {<br>    private final CountDownLatch countDownLatch;<br><br>    public VideoConference(int count) {<br>        countDownLatch = new CountDownLatch(count);<br>    }<br><br>    public void arrive(String name) {<br>        System.out.printf(&quot;%s has arrived\n&quot;, name);<br>        countDownLatch.countDown();<br>        System.out.printf(&quot;Waiting for %d participants\n&quot;, countDownLatch.getCount());<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            System.out.println(&quot;Conference started!! Waiting for participants&quot;);<br>            countDownLatch.await();<br>            System.out.printf(&quot;All participants have arrived, starting presentation\n&quot;);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}<br><br>class Participant implements Runnable {<br>    private final String name;<br>    private final VideoConference conference;<br><br>    public Participant(String name, VideoConference conference) {<br>        this.name = name;<br>        this.conference = conference;<br>    }<br><br>    @Override<br>    public void run() {<br>        long duration = (long) (Math.random() * 10);<br>        try {<br>            TimeUnit.SECONDS.sleep(duration);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>        conference.arrive(name);<br>    }<br>}<br><br>public class CountdownLatchImpl {<br>    public static void main(String[] args) {<br>        VideoConference conference = new VideoConference(5);<br>        Thread conferenceThread = new Thread(conference);<br>        conferenceThread.start();<br>        for (int i = 0; i &lt; 5; i++) {<br>            Participant participant = new Participant(&quot;Participant &quot; + i, conference);<br>            Thread thread = new Thread(participant);<br>            thread.start();<br>        }<br>    }<br>}</pre><p>The CountDownLatch class has another version of the await() method, which is as follows:</p><ul><li><strong>await(long time, TimeUnit unit)</strong>: In this method, the thread will continue to sleep until it’s interrupted, that is, either the internal counter of CountDownLatch arrives at 0 or the specified time passes.</li></ul><h3>CyclicBarrier — Synchronizing tasks in a common point</h3><p>The Java concurrency API provides a synchronizing utility that allows the synchronization of two or more threads at a determined point. It’s the <strong>CyclicBarrier</strong> class.</p><p>The CyclicBarrier class is initialized with an integer number, which is the <strong>number of threads</strong> that will be synchronized at a determined point.</p><p>When the thread calls the <strong>await</strong>() method, the CyclicBarrier class blocks the thread that is sleeping until the other threads arrive. When the last thread calls the await() method of the CyclicBarrier object, it wakes up all the threads that were waiting and continues with its job.</p><p>We can pass an <strong>additional Runnable object </strong>as an initialization parameter, and the CyclicBarrier class executes this object as a thread when all the threads arrive at the common point.</p><pre>package abhij33t;<br><br>import java.util.Random;<br>import java.util.concurrent.BrokenBarrierException;<br>import java.util.concurrent.CyclicBarrier;<br><br>class MatrixMock {<br>    private final int[][] data;<br><br>    public MatrixMock(int size, int length, int number) {<br>        int count = 0;<br>        data = new int[size][length];<br>        Random rand = new Random();<br>        for (int i = 0; i &lt; size; i++) {<br>            for (int j = 0; j &lt; length; j++) {<br>                data[i][j] = rand.nextInt(10);<br>                if (data[i][j] == number) {<br>                    count++;<br>                }<br>            }<br>        }<br>        System.out.printf(&quot;Mock: There are %d occurrences of %d in the matrix\n&quot;, count, number);<br>    }<br><br>    public int[] getRow(int index) {<br>        if (index &gt;= 0 &amp;&amp; index &lt; data.length) {<br>            return data[index];<br>        }<br>        return null;<br>    }<br>}<br><br>class Results {<br>    private final int[] data;<br><br>    public Results(int size) {<br>        data = new int[size];<br>    }<br><br>    public void setData(int index, int value) {<br>        data[index] = value;<br>    }<br><br>    public int[] getData() {<br>        return data;<br>    }<br>}<br><br>class Searcher implements Runnable {<br>    private final int firstRow;<br>    private final int lastRow;<br>    private final MatrixMock matrix;<br>    private final CyclicBarrier barrier;<br>    private final int number;<br>    private final Results results;<br><br>    public Searcher(int firstRow, int lastRow, int number, MatrixMock matrix, CyclicBarrier barrier, Results results) {<br>        this.firstRow = firstRow;<br>        this.lastRow = lastRow;<br>        this.matrix = matrix;<br>        this.barrier = barrier;<br>        this.number = number;<br>        this.results = results;<br>    }<br><br>    @Override<br>    public void run() {<br>        int count = 0;<br>        System.out.printf(&quot;%s: Searching from row %d to %d\n&quot;, Thread.currentThread().getName(), firstRow, lastRow);<br>        for (int i = firstRow; i &lt; lastRow; i++) {<br>            int[] row = matrix.getRow(i);<br>            count = 0;<br>            for (int j = 0; j &lt; row.length; j++) {<br>                if (row[j] == number)<br>                    count++;<br>            }<br>            results.setData(i, count);<br>        }<br>        System.out.printf(&quot;%s: Row processed, found %d occurrences\n&quot;, Thread.currentThread().getName(), count);<br>        try {<br>            barrier.await();<br>        } catch (InterruptedException | BrokenBarrierException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}<br><br>class Grouper implements Runnable {<br>    private final Results results;<br><br>    public Grouper(Results results) {<br>        this.results = results;<br>    }<br><br>    @Override<br>    public void run() {<br>        int result = 0;<br>        System.out.printf(&quot;Grouper: Grouping results\n&quot;);<br>        int[] data = results.getData();<br>        for (int i : data)<br>            result += i;<br>        System.out.printf(&quot;Grouper: Result = %d\n&quot;, result);<br>    }<br>}<br><br>public class CyclicBarrierImpl {<br>    public static void main(String[] args) {<br>        final int ROWS = 10000;<br>        final int NUMBERS = 1000;<br>        final int SEARCH = 5;<br>        final int SEARCHERS = 5;<br>        final int ROWS_PARTICIPANT = 2000;<br><br>        MatrixMock matrix = new MatrixMock(ROWS, NUMBERS, SEARCH);<br>        Results results = new Results(ROWS);<br>        Grouper grouper = new Grouper(results);<br>        CyclicBarrier barrier = new CyclicBarrier(SEARCHERS, grouper);<br>        Searcher[] searchers = new Searcher[SEARCHERS];<br>        for (int i = 0; i &lt; SEARCHERS; i++) {<br>            searchers[i] = new Searcher(i * ROWS_PARTICIPANT, (i + 1) * ROWS_PARTICIPANT, SEARCH, matrix, barrier, results);<br>        }<br>        for (Searcher searcher : searchers) {<br>            new Thread(searcher).start();<br>        }<br>        System.out.println(&quot;Main: Main thread finished&quot;);<br>    }<br>}</pre><h3><strong>Difference b/w Latch and Barrier</strong></h3><p>One of the most important <strong>differences</strong> between <strong>Latch</strong> and <strong>Barrier</strong> is that a CyclicBarrier object can be reset to its initial state, assigning to its internal counter the value with which it was initialized using <strong>reset</strong>().</p><p>When this occurs, all the threads that were waiting in the await() method receive a <strong>BrokenBarrierException</strong>.</p><p>When there are various threads waiting in the await() method and one of them is interrupted, the one that is interrupted receives an <strong>InterruptedException</strong>, but other threads receive a <strong>BrokenBarrierException</strong>; CyclicBarrier is placed in the <strong>broken</strong> state. The CyclicBarrier class provides the <strong>isBroken</strong>() method. It returns true if the object is in the broken state; otherwise, it returns false.</p><p>That’s all for now. Thanks for reading! ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3acbec729cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency In Depth-2 (Synchronized, ReentrantLock, StampedLock)]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/java-concurrency-in-depth-2-synchronized-reentrantlock-stampedelock-ef0271daee25?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef0271daee25</guid>
            <category><![CDATA[reentrant-lock]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <category><![CDATA[stampede-lock]]></category>
            <category><![CDATA[synchronization]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 23:38:42 GMT</pubDate>
            <atom:updated>2024-11-17T14:16:51.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f08SLiLaGW5KOxhCCER4PQ.jpeg" /></figure><p>Hey everyone,</p><p>I’ve created these notes after consulting several Java books. The books I referenced are:</p><ul><li>Gonzalez J.F. — <em>Java 9 Concurrency Cookbook</em>, 2nd Edition</li><li>Brian Goetz — <em>Java Concurrency In Practice</em></li><li>Ron Veen — <em>Virtual Threads, Structured Concurrency, and Scoped Values</em></li></ul><h3>Introduction</h3><p>One of the most common situations in concurrent programming occurs when more than one execution thread shares a resource.</p><p>These shared resources can provoke error situations or data inconsistency, and we have to implement mechanisms to avoid these errors. These situations are called race conditions and they occur when different threads have access to the same shared resource at the same time.</p><p>The solution for these problems lies in the concept of critical section. A critical section is a block of code that accesses a shared resource and can’t be executed by more than one thread at the same time. The two basic synchronization mechanisms offered by the Java language:</p><ul><li>The synchronized keyword</li><li>The Lock interface and its implementations</li></ul><h3>Synchronizing a method</h3><p>The synchronized keyword is used to control concurrent access to a method or a block of code. When we use the synchronized keyword with a method, the object reference is implicit. When we use the synchronized keyword in one or more methods of an object, only one execution thread will have access to all these methods.</p><p>Static methods have a different behavior. Only one execution thread will have access to one of the static methods declared with the synchronized keyword, but a different thread can access other non-static methods of an object of that class.</p><pre>package abhij33t;<br>import java.util.concurrent.TimeUnit;<br>class ParkingCash {<br>    private static final int cost = 2;<br>    private long cash;<br>    public ParkingCash() {<br>        cash = 0;<br>    }<br>    public synchronized void vehiclePay() {<br>        cash += cost;<br>    }<br>    public void close() {<br>        System.out.printf(&quot;Closing accounting&quot;);<br>        long totalAmmount;<br>        synchronized(this) {<br>            totalAmmount = cash;<br>            cash = 0;<br>        }<br>        System.out.printf(&quot;The total amount is : %d&quot;,<br>            totalAmmount);<br>    }<br>}<br>class ParkingStats {<br>    private long numberCars;<br>    private long numberMotorcycles;<br>    private ParkingCash cash;<br>    private final Object controlCars, controlMotorcycles;<br>    public ParkingStats(ParkingCash cash) {<br>        numberCars = 0;<br>        numberMotorcycles = 0;<br>        this.cash = cash;<br>        controlCars = new Object();<br>        controlMotorcycles = new Object();<br>    }<br>    public void carComeIn() {<br>        synchronized(controlCars) {<br>            numberCars++;<br>        }<br>    }<br>    public void carGoOut() {<br>        synchronized(controlCars) {<br>            numberCars - ;<br>        }<br>        cash.vehiclePay();<br>    }<br>    public void motoComeIn() {<br>        synchronized(controlMotorcycles) {<br>            numberMotorcycles++;<br>        }<br>    }<br>    public void motoGoOut() {<br>        synchronized(controlMotorcycles) {<br>            numberMotorcycles - ;<br>        }<br>        cash.vehiclePay();<br>    }<br>    public long getNumberCars() {<br>        return numberCars;<br>    }<br>    public long getNumberMotorcycles() {<br>        return numberMotorcycles;<br>    }<br>}<br>class Sensor implements Runnable {<br>    private ParkingStats stats;<br>    public Sensor(ParkingStats stats) {<br>        this.stats = stats;<br>    }<br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            stats.carComeIn();<br>            stats.carComeIn();<br>            try {<br>                TimeUnit.MILLISECONDS.sleep(50);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>            stats.motoComeIn();<br>            try {<br>                TimeUnit.MILLISECONDS.sleep(50);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>            stats.motoGoOut();<br>            stats.carGoOut();<br>            stats.carGoOut();<br>        }<br>    }<br>}<br>public class SynchronizedImpl {<br>    public static void main(String[] args) {<br>        ParkingCash cash = new ParkingCash();<br>        ParkingStats stats = new ParkingStats(cash);<br>        System.out.printf(&quot;Parking Simulator\n&quot;);<br>        int numberSensors = 2 * Runtime.getRuntime()<br>            .availableProcessors();<br>        Thread threads[] = new Thread[numberSensors];<br>        for (int i = 0; i &lt; numberSensors; i++) {<br>            Sensor sensor = new Sensor(stats);<br>            Thread thread = new Thread(sensor);<br>            thread.start();<br>            threads[i] = thread;<br>        }<br>        for (int i = 0; i &lt; numberSensors; i++) {<br>            try {<br>                threads[i].join();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>        System.out.printf(&quot;Number of cars: %d\n&quot;,<br>            stats.getNumberCars());<br>        System.out.printf(&quot;Number of motorcycles: %d\n&quot;,<br>            stats.getNumberMotorcycles());<br>        cash.close();<br>    }<br>}</pre><p>The synchronized keyword penalizes the performance of the application, so we must only use it on methods that modify shared data in a concurrent environment.</p><h3>Using conditions in synchronized code</h3><p>A classic problem in concurrent programming is the producer-consumer problem. We have a data buffer, one or more producers of data that save it in the buffer, and one or more consumers of data that take it from the buffer.</p><p>As the buffer is a shared data structure, we have to control access to it using a synchronization mechanism, such as the synchronized keyword, but here we have more limitations. A producer can’t save data in the buffer if it’s full, and a consumer can’t take data from the buffer if it’s empty.</p><p>For these types of situations, Java provides the wait(), notify(), and notifyAll() methods implemented in the Object class.</p><ul><li>wait :- When the thread calls the wait() method, JVM puts the thread to sleep and releases the object that controls the synchronized block of code that it’s executing and allows other threads to execute other blocks of synchronized code protected by this object.</li><li>notify/notifyAll :- To wake up the thread, we must call the notify() or notifyAll() methods inside a block of code protected by the same object.</li></ul><pre>package abhij33t;<br>import java.util.Date;<br>import java.util.LinkedList;<br>import java.util.Queue;<br>class EventStorage {<br>    private int maxSize;<br>    private Queue &lt; Date &gt; storage;<br>    public EventStorage() {<br>        this.maxSize = 10;<br>        storage = new LinkedList &lt; &gt; ();<br>    }<br>    public synchronized void set() {<br>        while (storage.size() == maxSize) {<br>            try {<br>                wait();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>        storage.offer(new Date());<br>        System.out.printf(&quot;Set: %d&quot;, storage.size());<br>        notify();<br>    }<br>    public synchronized void get() {<br>        while (storage.size() == 0) {<br>            try {<br>                wait();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>        String element = storage.poll().toString();<br>        System.out.printf(&quot;Get: %d: %s\n&quot;, storage.size(), element);<br>        notify();<br>    }<br>}<br>class Producer implements Runnable {<br>    private EventStorage storage;<br>    public Producer(EventStorage storage) {<br>        this.storage = storage;<br>    }<br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 100; i++) {<br>            storage.set();<br>        }<br>    }<br>}<br>class Consumer implements Runnable {<br>    private EventStorage storage;<br>    public Consumer(EventStorage storage) {<br>        this.storage = storage;<br>    }<br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 100; i++) {<br>            storage.get();<br>        }<br>    }<br>}<br>public class WaitNotifyImpl {<br>    public static void main(String[] args) {<br>        EventStorage storage = new EventStorage();<br>        Producer producer = new Producer(storage);<br>        Consumer consumer = new Consumer(storage);<br>        Thread t1 = new Thread(producer);<br>        Thread t2 = new Thread(consumer);<br>        t1.start();<br>        t2.start();<br>    }<br>}</pre><h3>Synchronising with locks</h3><p>Java provides another mechanism for synchronizing blocks of code. It’s a more powerful and flexible mechanism than the synchronized keyword. It’s based on the Lock (of the java.util.concurrent.locks package) interface and classes that implement it (as ReentrantLock). Advantages:-</p><ul><li>It allows us to structure synchronized blocks in a more flexible way.</li><li>With lock, we can execute the tryLock() method. This method returns a Boolean value indicating whether there is another thread running the code protected by this lock.</li><li>The ReadWriteLock interface allows a separation of read and write operations with multiple readers and only one modifier.</li><li>The constructor of the ReentrantLock class admits a boolean parameter named fair; this parameter allows us to control its behavior. The false value is the default value and it’s called the non-fair mode. In this mode, if some threads are waiting for a lock and the lock has to select one of these threads to get access to the critical section, it randomly selects any of them.</li><li>The true value is called the fair mode. In this mode, if some threads are waiting for a lock and the lock has to select one to get access to a critical section, it selects the thread that has been waiting for the longest period of time.</li></ul><pre>package abhij33t;<br><br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.locks.Lock;<br>import java.util.concurrent.locks.ReentrantLock;<br><br>class PrintQueue {<br>    private Lock queueLock;<br><br>    public PrintQueue(boolean fairFlag) {<br>        this.queueLock = new ReentrantLock(fairFlag);<br>    }<br><br>    public void printJob(Object document) {<br>        queueLock.lock();<br>        try {<br>            Long duration = (long) (Math.random() * 10000);<br>            System.out.println(Thread.currentThread().getName() + &quot;: PrintQueue: Printing a Job during &quot; +<br>                    (duration / 1000) + &quot; seconds&quot;);<br>            TimeUnit.SECONDS.sleep(duration);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } finally {<br>            queueLock.unlock();<br>        }<br>        // repeating it to see the fairFlag difference<br>        queueLock.lock();<br>        try {<br>            Long duration = (long) (Math.random() * 10000);<br>            System.out.println(Thread.currentThread().getName() + &quot;: PrintQueue: Printing a Job during &quot; +<br>                    (duration / 1000) + &quot; seconds&quot;);<br>            Thread.sleep(duration);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } finally {<br>            queueLock.unlock();<br>        }<br>    }<br>}<br><br>class Job implements Runnable {<br><br>    private PrintQueue printQueue;<br><br>    public Job(PrintQueue printQueue) {<br>        this.printQueue = printQueue;<br>    }<br><br>    @Override<br>    public void run() {<br>        System.out.printf(&quot;%s: Going to print a document\n&quot;,<br>                Thread.currentThread().getName());<br>        printQueue.printJob(new Object());<br>        System.out.printf(&quot;%s: The document has been printed\n&quot;,<br>                Thread.currentThread().getName());<br>    }<br>}<br><br>public class LockImpl {<br><br>    static void testPrintQueue(boolean fairMode) {<br>        PrintQueue printQueue = new PrintQueue(fairMode);<br>        Thread[] threads = new Thread[10];<br>        for (int i=0; i&lt;10; i++) {<br>            threads[i] = new Thread(new Job(printQueue), &quot;Thread &quot;+i );<br>        }<br>        for (int i=0; i&lt;10; i++)<br>            threads[i].start();<br>        for (int i=0; i&lt;10; i++) {<br>            try {<br>                threads[i].join();<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        System.out.printf(&quot;Running example with fair-mode = false\n&quot;);<br>        testPrintQueue(false);<br>        System.out.printf(&quot;Running example with fair-mode = true\n&quot;);<br>        testPrintQueue(true);<br>    }<br>}</pre><h3>Synchronizing data access with read/write locks</h3><p>The ReentrantReadWriteLock class has two locks: one for read operations and one for write operations. There can be more than one thread using read operations simultaneously, but only one thread can use write operations.</p><pre>package abhij33t;<br><br>import java.util.Date;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.locks.ReadWriteLock;<br>import java.util.concurrent.locks.ReentrantReadWriteLock;<br><br>class PriceInfo {<br>    private double price1;<br>    private double price2;<br>    private ReadWriteLock lock;<br><br>    public PriceInfo() {<br>        this.price1 = 1;<br>        this.price2 = 1;<br>        lock = new ReentrantReadWriteLock();<br>    }<br><br>    public double getPrice1() {<br>        lock.readLock().lock();<br>        double value = price1;<br>        lock.readLock().unlock();<br>        return value;<br>    }<br><br>    public double getPrice2() {<br>        lock.readLock().lock();<br>        double value = price2;<br>        lock.readLock().unlock();<br>        return value;<br>    }<br><br>    public void setPrices(double price1, double price2) {<br>        lock.writeLock().lock();<br>        System.out.printf(&quot;%s: PricesInfo: Write Lock Adquired.\n&quot;,<br>                new Date());<br>        try {<br>            TimeUnit.SECONDS.sleep(10);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>        this.price1 = price1;<br>        this.price2 = price2;<br>        System.out.printf(&quot;%s: PricesInfo: Write Lock Released.\n&quot;,<br>                new Date());<br>        lock.writeLock().unlock();<br>    }<br>}<br><br>class Reader implements Runnable {<br>    private PriceInfo pricesInfo;<br><br>    public Reader(PriceInfo priceInfo) {<br>        this.pricesInfo = priceInfo;<br>    }<br><br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 20; i++) {<br>            System.out.printf(&quot;%s: %s: Price 1: %f\n&quot;, new Date(),<br>                    Thread.currentThread().getName(),<br>                    pricesInfo.getPrice1());<br>            System.out.printf(&quot;%s: %s: Price 2: %f\n&quot;, new Date(),<br>                    Thread.currentThread().getName(),<br>                    pricesInfo.getPrice2());<br>        }<br>    }<br>}<br><br>class Writer implements Runnable {<br>    private PriceInfo pricesInfo;<br><br>    public Writer(PriceInfo priceInfo) {<br>        this.pricesInfo = priceInfo;<br>    }<br><br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 3; i++) {<br>            System.out.printf(&quot;%s: Writer: Attempt to modify the prices.\n&quot;, new Date());<br>            pricesInfo.setPrices(Math.random() * 10, Math.random() * 8);<br>            System.out.printf(&quot;%s: Writer: Prices have been modified.\n&quot;, new Date());<br>            try {<br>                Thread.sleep(2);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}<br><br>public class ReentrantReadWriteLockImpl {<br>    public static void main(String[] args) {<br>        PriceInfo priceInfo = new PriceInfo();<br>        Thread[] tReaders = new Thread[10];<br>        for (int i = 0; i &lt; 10; i++) {<br>            tReaders[i] = new Thread(new Reader(priceInfo));<br>        }<br>        for (int i = 0; i &lt; 10; i++)<br>            tReaders[i].start();<br>        new Thread(new Writer(priceInfo)).start(); //starting writer thread<br>    }<br>}</pre><h3>Using multiple conditions in a lock</h3><p>A lock may be associated with one or more conditions.The purpose of these conditions is to allow threads to have control of a lock and check whether a condition is true or not. If it’s false, the thread will be suspended until another thread wakes it up.</p><p>The Condition interface provides the mechanisms to suspend a thread and wake up a suspended thread. We can use await() and signal/signalAll() method to suspend and resume threads accordingly.</p><pre>package abhij33t;<br><br>import java.util.ArrayDeque;<br>import java.util.Deque;<br>import java.util.Random;<br>import java.util.concurrent.locks.Condition;<br>import java.util.concurrent.locks.ReentrantLock;<br><br>class FileMock {<br>    private String[] content;<br>    private int index;<br><br>    public FileMock(int size, int length) {<br>        content = new String[size];<br>        for (int i = 0; i &lt; size; i++) {<br>            StringBuilder buffer = new StringBuilder(length);<br>            for (int j = 0; j &lt; length; j++) {<br>                int randomCharacter = (int) Math.random() * 255;<br>                buffer.append((char) randomCharacter);<br>            }<br>            content[i] = buffer.toString();<br>        }<br>        index = 0;<br>    }<br><br>    public boolean hasMoreLines() {<br>        return index &lt; content.length;<br>    }<br><br>    public String getLine() {<br>        if (this.hasMoreLines()) {<br>            System.out.println(&quot;Mock: &quot; + (content.length - index));<br>            return content[index++];<br>        }<br>        return null;<br>    }<br>}<br><br>class Buffer {<br>    private final Deque&lt;String&gt; buffer;<br>    private final int maxSize;<br>    private final ReentrantLock lock;<br>    private final Condition lines;<br>    private final Condition spaces;<br>    private boolean pendingLines;<br><br>    public Buffer(int capacity) {<br>        this.maxSize = capacity;<br>        buffer = new ArrayDeque&lt;&gt;();<br>        lock = new ReentrantLock();<br>        lines = lock.newCondition();<br>        spaces = lock.newCondition();<br>        pendingLines = true;<br>    }<br><br>    public void insert(String line) {<br>        lock.lock();<br>        try {<br>            while (buffer.size() == maxSize)<br>                spaces.await();<br>            buffer.offer(line);<br>            System.out.printf(&quot;%s : Inserted line : %d\n&quot;, Thread.currentThread().getName(), buffer.size());<br>            lines.signalAll();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br><br>    public String get() {<br>        String line = null;<br>        lock.lock();<br>        try {<br>            while (buffer.size() == 0 &amp;&amp; hasPendingLines())<br>                lines.await();<br>            if (hasPendingLines()) {<br>                line = buffer.poll();<br>                System.out.printf(&quot;%s : Line Readed : %d\n&quot;, Thread.currentThread().getName(), buffer.size());<br>                spaces.signalAll();<br>            }<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } finally {<br>            lock.unlock();<br>        }<br>        return line;<br>    }<br><br>    public synchronized void setPendingLines(boolean pendingLines) {<br>        this.pendingLines = pendingLines;<br>    }<br><br>    public synchronized boolean hasPendingLines() {<br>        return pendingLines || buffer.size() &gt; 0;<br>    }<br>}<br><br>class ProducerL implements Runnable {<br>    private FileMock mock;<br>    private Buffer buffer;<br><br>    public ProducerL(FileMock fileMock, Buffer buffer) {<br>        this.buffer = buffer;<br>        this.mock = fileMock;<br>    }<br><br>    @Override<br>    public void run() {<br>        buffer.setPendingLines(true);<br>        while (mock.hasMoreLines()) {<br>            String line = mock.getLine();<br>            buffer.insert(line);<br>        }<br>        buffer.setPendingLines(false);<br>    }<br>}<br><br>class ConsumerL implements Runnable {<br>    private Buffer buffer;<br><br>    public ConsumerL(Buffer buffer) {<br>        this.buffer = buffer;<br>    }<br><br>    @Override<br>    public void run() {<br>        while (buffer.hasPendingLines()) {<br>            String line = buffer.get();<br>            processLine(line);<br>        }<br>    }<br><br>    private void processLine(String line) {<br>        try {<br>            Thread.sleep(new Random().nextInt(100));<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}<br><br>public class ProducerConsumerViaLock {<br>    public static void main(String[] args) {<br>        FileMock fileMock = new FileMock(100, 10);<br>        Buffer buffer = new Buffer(20);<br>        ProducerL producer = new ProducerL(fileMock, buffer);<br>        Thread producerThread = new Thread(producer, &quot;Producer&quot;);<br>        ConsumerL consumers[] = new ConsumerL[3];<br>        Thread consumersThreads[] = new Thread[3];<br>        for (int i = 0; i &lt; 3; i++) {<br>            consumers[i] = new ConsumerL(buffer);<br>            consumersThreads[i] = new Thread(consumers[i], &quot;Consumer &quot; + i);<br>        }<br>        producerThread.start();<br>        for (int i = 0; i &lt; 3; i++) {<br>            consumersThreads[i].start();<br>        }<br>    }<br>}</pre><p>The Condition interface has other versions of the await() method, which are as follows:</p><ul><li>await(long time, TimeUnit unit)</li><li>awaitUninterruptibly() :- The thread will sleep until another thread calls the signal() or signalAll() methods, which can’t be interrupted</li><li>awaitUntil(Date date)</li></ul><h3>Advanced locking with the StampedLock class</h3><p>The StampedLock class provides a special kind of lock that is different from the ones provided by the Lock or ReadWriteLock interfaces.</p><p>The first point to note about this kind of lock is that its main purpose is to be a helper class to implement thread-safe components, so its use will not be very common in normal applications.</p><p>The most important features of StampedLock locks are as follows:</p><ul><li>Write: In this mode, we get exclusive access to the lock. No other thread can have control of the lock in this mode.</li><li>Read: In this mode, we have non-exclusive access to the lock. There can be other threads that have access to the lock in this mode or the Optimistic Read mode.</li><li>Optimistic Read: Here, the thread doesn’t have control over the block. Other threads can get control of the lock in write mode. When we get a lock in the Optimistic Read mode and want to access the shared data protected by it, we will have to check whether we can access them or not using the validate() method.</li></ul><p>The StampedLock class provides methods to:</p><ul><li>Acquire control over the lock in one of the previous modes. If the methods (readLock(), writeLock(), readLockInterruptibly()) are unable to get control of the lock, the current thread is suspended until it gets the lock.</li><li>Acquire control over the lock in one of the previous modes. If the methods (tryOptimisticRead(), tryReadLock(), tryWriteLock()) are unable to get control of the lock, they return a special value to indicate this circumstance.</li><li>Convert one mode into another, if possible. If not, the methods (asReadLock(), asWriteLock(), asReadWriteLock()) return a special value.</li></ul><p>A StampedLock lock is not a reentrant lock, such as the Lock and ReadWriteLock interfaces. If we call a method that tries to get the lock again, it may be blocked and we’ll get a deadlock.</p><pre>package abhij33t;<br><br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.locks.StampedLock;<br><br>class Position {<br>    int x, y;<br>    public int getX() {<br>        return x;<br>    }<br>    public void setX(int x) {<br>        this.x = x;<br>    }<br>    public int getY() {<br>        return y;<br>    }<br>    public void setY(int y) {<br>        this.y = y;<br>    }<br>}<br><br>class WriterSL implements Runnable {<br>    private final Position position;<br>    private final StampedLock lock;<br><br>    public WriterSL(Position position, StampedLock lock) {<br>        this.lock = lock;<br>        this.position = position;<br>    }<br><br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            long stamp = lock.writeLock();<br>            try {<br>                System.out.printf(&quot;Writer: Lock acquired %d\n&quot;, stamp);<br>                position.setX(position.getX() + 1);<br>                position.setY(position.getY() + 1);<br>                TimeUnit.SECONDS.sleep(1);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            } finally {<br>                lock.unlockWrite(stamp);<br>                System.out.printf(&quot;Writer: Lock release %d\n&quot;, stamp);<br>            }<br>            try {<br>                TimeUnit.SECONDS.sleep(1);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}<br><br>class ReaderSL implements Runnable {<br>    private final Position position;<br>    private final StampedLock lock;<br><br>    public ReaderSL(Position position, StampedLock lock) {<br>        this.lock = lock;<br>        this.position = position;<br>    }<br><br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            long stamp = lock.readLock();<br>            try {<br>                System.out.printf(&quot;Reader: %d - (%d,%d)\n&quot;, stamp, position.getX(), position.getY());<br>                TimeUnit.MILLISECONDS.sleep(200);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            } finally {<br>                lock.unlockRead(stamp);<br>                System.out.printf(&quot;Reader: Lock release %d\n&quot;, stamp);<br>            }<br>        }<br>    }<br>}<br><br>class OptimisticReader implements Runnable {<br>    private final Position position;<br>    private final StampedLock lock;<br><br>    public OptimisticReader(Position position, StampedLock lock) {<br>        this.lock = lock;<br>        this.position = position;<br>    }<br><br>    @Override<br>    public void run() {<br>        long stamp;<br>        for (int i = 0; i &lt; 100; i++) {<br>            try {<br>                stamp = lock.tryOptimisticRead();<br>                int x = position.getX();<br>                int y = position.getY();<br>                if (lock.validate(stamp)) {<br>                    System.out.printf(&quot;OptmisticReader: %d - (%d,%d)\n&quot;,<br>                            stamp, x, y);<br>                } else {<br>                    System.out.printf(&quot;OptmisticReader: %d - Not Free\n&quot;,<br>                            stamp);<br>                }<br>                TimeUnit.MILLISECONDS.sleep(200);<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            }<br>        }<br>    }<br>}<br><br>public class StampedLockImpl {<br>    public static void main(String[] args) {<br>        Position position = new Position();<br>        StampedLock stampedLock = new StampedLock();<br>        Thread writerThread = new Thread(new WriterSL(position, stampedLock));<br>        Thread readerThread = new Thread(new ReaderSL(position, stampedLock));<br>        Thread optimisticReaderThread = new Thread(new OptimisticReader(position, stampedLock));<br><br>        writerThread.start();<br>        readerThread.start();<br>        optimisticReaderThread.start();<br><br>        try {<br>            writerThread.join();<br>            readerThread.join();<br>            optimisticReaderThread.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef0271daee25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Concurrency In Depth-1 (Threads, Runnable, ThreadGroup, UncaughtExceptionHandler…]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/java-concurrency-in-depth-1-threads-runnable-threadgroup-uncaughtexceptionhandler-80cb0ba4ccff?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/80cb0ba4ccff</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <category><![CDATA[runnable]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 23:14:32 GMT</pubDate>
            <atom:updated>2024-11-17T14:15:01.682Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Java Concurrency In Depth-1 (Threads, Runnable, ThreadGroup, UncaughtExceptionHandler, ThreadFactory)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPDcGvRslSGqOYBCgCOxJg.jpeg" /></figure><p>Hey everyone,</p><p>I’ve created these notes after consulting several Java books. The books I referenced are:</p><ul><li>Gonzalez J.F. — <em>Java 9 Concurrency Cookbook</em>, 2nd Edition</li><li>Brian Goetz — <em>Java Concurrency In Practice</em></li><li>Ron Veen — <em>Virtual Threads, Structured Concurrency, and Scoped Values</em></li></ul><h3>Creating, running, and setting the characteristics of a thread</h3><p>We have two ways of creating a thread in Java:</p><ul><li>Extending the Thread class and overriding the run() method.</li><li>Building a class that implements the Runnable interface and the run() method and then creating an object of the Thread class by passing the Runnable object as a parameter — this is the preferred approach and it gives us more flexibility.</li></ul><p>The Thread class saves some information attributes that can help us identify a thread, know its status, or control its priority. These attributes are:</p><ul><li>ID: This attribute stores a unique identifier for each thread.</li><li>Name: This attribute stores the name of the thread.</li><li>Priority: This attribute stores the priority of the Thread objects. In Java 9, threads can have priority between 1 and 10, where 1 is the lowest priority and 10 is the highest.</li><li>Status: This attribute stores the status of a thread. In Java, a thread can be present in one of the six states defined in the Thread.State enumeration: NEW,RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED. The following is a list specifying what each of these states means:</li><li>NEW: The thread has been created and it has not yet started</li><li>RUNNABLE: The thread is being executed in the JVM</li><li>BLOCKED: The thread is blocked and it is waiting for a monitor</li><li>WAITING: The thread is waiting for another thread</li><li>TIMED_WAITING: The thread is waiting for another thread with a specified waiting time</li><li>TERMINATED: The thread has finished its execution</li></ul><p>We can use the static method currentThread() of the Thread class to access the thread object that is running the current object.</p><pre>package abhij33t;<br><br>class RunnableImpl implements Runnable{<br>    @Override<br>    public void run() {<br>        System.out.printf(&quot;%s: Running via implementing Runnable class\n&quot;, Thread.currentThread().getName());<br>        StatsChecker.threadStats();<br>    }<br>}<br>class StatsChecker {<br>    static void threadStats() {<br>        System.out.printf(&quot;Id: %d\nName: %s\nPriority: %d\nState: %s\n&quot;,<br>                Thread.currentThread().getId(),<br>                Thread.currentThread().getName(),<br>                Thread.currentThread().getPriority(),<br>                Thread.currentThread().getState());<br>    }<br>}<br>public class ThreadImpl extends Thread{<br>    @Override<br>    public void run() {<br>        System.out.printf(&quot;%s: Running via extended Thread class\n&quot;, Thread.currentThread().getName());<br>        StatsChecker.threadStats();<br>    }<br>    public static void main(String[] args) {<br>        Thread t1 = new ThreadImpl();<br>        t1.start();<br>        Thread t2 = new Thread(new RunnableImpl());<br>        t2.start();<br>        // We can also use lambda expression as Runnable is a functional interface.<br>        new Thread(() -&gt; {<br>            System.out.printf(&quot;%s: Running via lambda expression\n&quot;, Thread.currentThread().getName());<br>            StatsChecker.threadStats();<br>        }).start();<br>    }<br>}</pre><h3>Interrupting a thread</h3><p>A Java program with more than one execution thread only finishes when the execution of all of its threads ends (more specifically, when all its non-daemon threads end their execution or when one of the threads uses the System.exit() method).</p><p>The Thread class has an attribute that stores a boolean value indicating whether the thread has been interrupted or not. When we call the interrupt() method of a thread, we set that attribute to true. The isInterrupted() method only returns the value of that attribute.</p><p>The Thread class has another method to check whether a thread has been interrupted or not. It’s the static method, interrupted(), that checks whether the current thread has been interrupted or not.</p><p>There is an important difference between the isInterrupted() and interrupted() methods. The first one doesn’t change the value of the interrupted attribute, but the second one sets it to false.</p><p>If the thread implements a complex algorithm divided into some methods or it has methods with recursive calls, we will need to use a better mechanism to control the interruption of the thread. Java provides the InterruptedException exception for this purpose. We can throw this exception when we detect the interruption of a thread and catch it in the run() method.</p><h3>Sleeping and resuming a thread</h3><p>Sometimes, we may be interested in pausing the execution of a thread during a determined period of time. We can use the sleep() method or the TimeUnit class for this purpose.</p><pre>package abhij33t;<br>import java.util.concurrent.TimeUnit;<br>public class SleepImpl {<br> public static void main(String[] args) {<br>   try {<br>     Long duration = (long) (Math.random() * 1000);<br>     System.out.printf(&quot;Sleeping for %d milliseconds\n&quot;, duration);<br>     TimeUnit.MILLISECONDS.sleep(duration);<br>   } catch (InterruptedException e) {<br>     e.printStackTrace();<br>   }<br> }<br>}</pre><p>The Java concurrency API has another method that makes a thread object leave the CPU. It’s the yield() method, which indicates to the JVM that the thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it’s only used for debugging purposes.</p><h3>Waiting for the finalization of a thread</h3><p>In some situations, we will have to wait for the end of the execution of a thread (the run() method ends its execution).For this purpose, we can use the join() method of the Thread class. Java provides two additional forms of the join() method:</p><ul><li>join (long milliseconds)</li><li>join (long milliseconds, long nanos)</li></ul><h3>Creating and running a daemon thread</h3><p>Java has a special kind of thread called daemon thread. They are low priority threads and JVM doesn’t wait for them, it shuts them when user threads have finished executing and gets terminated.</p><p>We can mark a thread as a daemon thread by calling setDaemon() method. We only can call the setDaemon() method before we call the start() method. Once the thread is running, we can’t modify its daemon status by calling the setDaemon() method. If we call it, we will get an IllegalThreadStateException exception.</p><h3>Processing uncontrolled exceptions in a thread</h3><p>When a checked exception is thrown inside the run() method of a thread object, we have to catch and treat them because the run() method doesn’t accept a throws clause.</p><p>When an unchecked exception is thrown inside the run() method of a thread object, the default behavior is to write the stack trace in the console and exit the program.</p><pre>package abhij33t;<br><br>public class ExpHandlerImpl implements Thread.UncaughtExceptionHandler {<br>    @Override<br>    public void uncaughtException(Thread t, Throwable e) {<br>        System.out.printf(&quot;Exception captured in thread : %s\n&quot;, t.getName());<br>        System.out.println(&quot;Exception: &quot;+e.getMessage());<br>    }<br><br>    public static void main(String[] args) {<br>        Thread t = new Thread(() -&gt; {<br>            var x = 1/0; //throws arithmetic exception<br>        });<br>        t.setUncaughtExceptionHandler(new ExpHandlerImpl());<br>        t.start();<br>    }<br>}</pre><p>The Thread class has another method related to the process of uncaught exceptions. It’s the static method setDefaultUncaughtExceptionHandler() that establishes an exception handler for all the thread objects in the application.</p><p>When an uncaught exception is thrown in the thread, the JVM looks for three possible handlers for this exception:</p><ul><li>uncaught exception handler of the thread objects</li><li>uncaught exception handler of ThreadGroup</li><li>default uncaught exception handler</li></ul><h3>Using thread local variables</h3><p>If we create an object of a class that implements the Runnable interface and then start various thread objects using the same Runnable object, all the threads would share the same attributes.</p><p>Sometimes, we will be interested in having an attribute that won’t be shared among all the threads that run the same object. The Java Concurrency API provides a clean mechanism called thread-local variables with very good performance.</p><p>The Java Concurrency API includes the InheritableThreadLocal class that provides inheritance of values for threads created from a thread. If thread A has a value in a thread-local variable and it creates another thread B, then thread B will have the same value as thread A in the thread-local variable.</p><p>We can override the childValue() method that is called to initialize the value of the child thread in the thread-local variable. It receives the value of the parent thread as a parameter in the thread-local variable.</p><pre>class ParentThread extends Thread {<br>    public static InheritableThreadLocal gfg_tl = new InheritableThreadLocal() {<br>        public Object childValue(Object parentValue) {<br>            return &quot;child data&quot;;<br>        }<br>    };<br>    public void run() {<br>        gfg_tl.set(&quot;parent data&quot;);<br>        System.out.println(&quot;Parent Thread Value :&quot; + gfg_tl.get());<br>        ChildThread gfg_ct = new ChildThread();<br>        gfg_ct.start();<br>    }<br>}<br>class ChildThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Child Thread Value :&quot; + ParentThread.gfg_tl.get());<br>    }<br>}<br>class ThreadLocalDemo {<br>    public static void main(String[] args) {<br>        ParentThread gfg_pt = new ParentThread();<br>        gfg_pt.start();<br>    }<br>}</pre><h3>Grouping threads and processing uncontrolled exceptions in a group of threads</h3><p>An interesting functionality offered by the concurrency API of Java is the ability to group threads. This allows us to treat the threads of a group as a single unit and provide access to the thread objects that belong to a group in order to do an operation with them.</p><p>Java provides the ThreadGroup class to work with a groups of threads. A ThreadGroup object can be formed by thread objects and another ThreadGroup object, generating a tree structure of threads.</p><pre>package abhij33t;<br>import java.util.Random;<br>public class ThreadGroupImpl extends ThreadGroup {<br>    public ThreadGroupImpl(String name) {<br>        super(name);<br>    }<br>    @Override<br>    public void uncaughtException(Thread t, Throwable e) {<br>        System.out.printf(&quot;Exception captured in thread : %s\n&quot;, t.getName());<br>        System.out.println(&quot;Exception: &quot; + e.getMessage());<br>        System.out.println(&quot;Terminating all threads&quot;);<br>        interrupt();<br>    }<br>    public static void main(String[] args) {<br>        Runnable r = new Runnable() {<br>            @Override<br>            public void run() {<br>                int result;<br>                Random random = new Random(Thread.currentThread().threadId());<br>                while (true) {<br>                    result = 100 / ((int) random.nextDouble() * 1000000);<br>                    if (Thread.currentThread().isInterrupted()) {<br>                        System.out.printf(&quot;Thread %s is interrupted\n&quot;, Thread.currentThread().getName());<br>                        return;<br>                    }<br>                }<br>            }<br>        };<br>        ThreadGroupImpl tg = new ThreadGroupImpl(&quot;MyThreadGroup&quot;);<br>        for (int i = 0; i &lt; 10; i++) {<br>            new Thread(tg, r).start();<br>        }<br>        System.out.println(&quot;Number of threads in MyThreadGroup: &quot; + tg.activeCount());<br>        System.out.println(&quot;Thread group info: &quot;);<br>        tg.list();<br>    }<br>}</pre><h3>Creating Threads Through Factory</h3><p>Java provides an interface, the ThreadFactory interface, to implement a thread object factory. Some advanced utilities of the Java concurrency API use thread factories to create threads.</p><pre>package abhij33t;<br>import java.util.ArrayList;<br>import java.util.Date;<br>import java.util.Iterator;<br>import java.util.List;<br>import java.util.concurrent.ThreadFactory;<br>public class ThreadFactoryImpl implements ThreadFactory {<br>    private int counter;<br>    private String name;<br>    private List &lt; String &gt; stats;<br>    public ThreadFactoryImpl(String name) {<br>        this.name = name;<br>        counter = 0;<br>        stats = new ArrayList &lt;&gt; ();<br>    }<br>    @Override<br>    public Thread newThread(Runnable r) {<br>        Thread t = new Thread(r);<br>        counter++;<br>        stats.add(String.format(&quot;Created thread %d with name %s on %s\n&quot;, t.getId(), t.getName(), new Date()));<br>        return t;<br>    }<br>    public String getStats() {<br>        StringBuffer buffer = new StringBuffer();<br>        Iterator &lt; String &gt; it = stats.iterator();<br>        while (it.hasNext()) {<br>            buffer.append(it.next());<br>            buffer.append(&quot;\n&quot;);<br>        }<br>        return buffer.toString();<br>    }<br>    public static void main(String[] args) {<br>        ThreadFactoryImpl factory = new ThreadFactoryImpl(&quot;MyThreadFactory&quot;);<br>        Thread t;<br>        Task task = new Task();<br>        System.out.println(&quot;Starting the threads&quot;);<br>        for (int i = 0; i &lt; 10; i++) {<br>            t = factory.newThread(task);<br>            t.start();<br>        }<br>        System.out.printf(&quot;Factory stats:\n&quot;);<br>        System.out.printf(&quot;%s\n&quot;, factory.getStats());<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80cb0ba4ccff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Loosely Coupled Logging System in Java]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/designing-a-loosely-coupled-logging-system-in-java-f4eca48d731f?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4eca48d731f</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 16:55:15 GMT</pubDate>
            <atom:updated>2024-07-01T16:55:15.375Z</atom:updated>
            <content:encoded><![CDATA[<p>As software developers, we understand the importance of logging in our applications. Logging helps us debug issues, track performance, and monitor system behavior. However, designing a logging system that is flexible, scalable, and easy to maintain can be a challenging task. In this post, we’ll explore a loosely coupled logging system in Java that allows users to choose the sink type and logging level.</p><h4>Requirements</h4><p>Our logging system should meet the following requirements:</p><ul><li>Allow users to choose the sink type (console, file, database, etc.)</li><li>Each sink type should have its own default logging level</li><li>Logs with a priority less than the default logging level should not be logged</li><li>The system should be loosely coupled to allow for easy extension and maintenance</li></ul><h4>Design</h4><p>To meet these requirements, we’ll design a logging system with the following components:</p><ul><li>Enums: We’ll define two enums, LoggingLevel and SinkType, to represent the logging levels and sink types, respectively.</li><li>OutputWriter Interface: We’ll define an OutputWriter interface that provides methods for writing logs, getting the default logging level, and closing the output writer.</li><li>OutputWriter Implementations: We’ll create concrete implementations of the OutputWriter interface for each sink type (console, file, database, etc.).</li><li>OutputWriter Factory: We’ll create a factory class that provides the correct output writer based on the sink type.</li><li>Logging Service: We’ll create a service class that interacts with the output writer and provides a logging interface to the user.</li></ul><h4>Implementation</h4><p>Let’s take a look at the implementation details:</p><h4>Enums</h4><pre>package org.example.loggingsystem.enums;<br><br>public enum LoggingLevel {<br>    DEBUG(0),<br>    INFO(1),<br>    WARN(2),<br>    ERROR(3),<br>    FATAL(4);<br>    private final int priority;<br><br>    LoggingLevel(int priority) {<br>        this.priority = priority;<br>    }<br><br>    public int getPriority() {<br>        return priority;<br>    }<br>}</pre><pre>package org.example.loggingsystem.enums;<br><br>public enum SinkType {<br>    CONSOLE,<br>    FILE,<br>    DATABASE<br>}</pre><h4>OutputWriter and it’s implementations</h4><pre>package org.example.loggingsystem.outputwriter;<br><br>import org.example.loggingsystem.enums.LoggingLevel;<br><br>public interface OutputWriter {<br>    void write(String message, LoggingLevel level);<br>    LoggingLevel getDefaultLevel();<br>    void close();<br>}</pre><pre>package org.example.loggingsystem.outputwriter;<br><br>import org.example.loggingsystem.enums.LoggingLevel;<br><br>public class ConsoleOutputWriter implements OutputWriter{<br>    private final LoggingLevel level;<br>    public ConsoleOutputWriter(LoggingLevel level) {<br>        this.level = level;<br>    }<br>    @Override<br>    public void write(String message, LoggingLevel level) {<br>        System.out.println(level.toString() + &quot; :: &quot; + message);<br>    }<br><br>    @Override<br>    public LoggingLevel getDefaultLevel() {<br>        return level;<br>    }<br><br>    @Override<br>    public void close() {<br>        System.out.println(&quot;Are you dumb or what??&quot;);<br>    }<br>}</pre><pre>package org.example.loggingsystem.outputwriter;<br><br>import org.example.loggingsystem.enums.LoggingLevel;<br><br>import java.io.BufferedWriter;<br>import java.io.FileWriter;<br>import java.io.IOException;<br>import java.io.PrintWriter;<br>import java.nio.file.Files;<br>import java.nio.file.Path;<br><br>public class FileOutputWriter implements OutputWriter{<br><br>    private final LoggingLevel level;<br>    private final String location =&quot;/home/abhij33t/IdeaProjects/LowLevelDesign/logging-system/src/main/resources/Log.txt&quot;;<br>    private PrintWriter printWriter;<br>    public FileOutputWriter(LoggingLevel level){<br>        this.level = level;<br>        Path path = Path.of(location);<br>        try{<br>            if(!Files.exists(path))<br>                Files.createFile(path);<br>            this.printWriter = new PrintWriter(new BufferedWriter(new FileWriter(location, true)));<br>        }catch (IOException ex) {<br>            System.out.println(ex.getMessage());<br>        }<br><br>    }<br><br>    @Override<br>    public void write(String message, LoggingLevel level) {<br>        this.printWriter.println(level.toString() + &quot; :: &quot; + message);<br>    }<br><br>    @Override<br>    public LoggingLevel getDefaultLevel() {<br>        return level;<br>    }<br><br>    @Override<br>    public void close() {<br>        System.out.println(&quot;Always close the resources to avoid memory leak and to prevent undesirable output in the file&quot;);<br>        this.printWriter.close();<br>    }<br>}</pre><h4>OutputWriter Factory</h4><pre>package org.example.loggingsystem.outputwriter;<br><br><br>import org.example.loggingsystem.enums.LoggingLevel;<br>import org.example.loggingsystem.enums.SinkType;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>// output writers impl will be singleton<br>public class OutputWriterFactory {<br>    private static Map&lt;SinkType, OutputWriter&gt; cache = new HashMap&lt;&gt;();<br><br>    public static OutputWriter getOutputWriter(SinkType type) {<br>        if(cache.containsKey(type))<br>            return cache.get(type);<br>        else<br>            return createOutputWriter(type);<br>    }<br><br>    private static OutputWriter createOutputWriter(SinkType type){<br>        if (type == SinkType.CONSOLE){<br>            ConsoleOutputWriter consoleOutputWriter = new ConsoleOutputWriter(LoggingLevel.ERROR);<br>            cache.put(type, consoleOutputWriter);<br>            return consoleOutputWriter;<br>        }<br>        else if (type == SinkType.FILE) {<br>            FileOutputWriter fileOutputWriter = new FileOutputWriter(LoggingLevel.INFO);<br>            cache.put(type, fileOutputWriter);<br>            return fileOutputWriter;<br>        } else if (type == SinkType.DATABASE) {<br>            // just throwing an exception here, you can throw a beautiful message<br>            throw new RuntimeException(&quot;Not implemented yet!!&quot;);<br>        }<br>        return null;<br>    }<br>}</pre><h4>LoggingService</h4><pre>package org.example.loggingsystem.service;<br><br>import org.example.loggingsystem.enums.LoggingLevel;<br>import org.example.loggingsystem.enums.SinkType;<br>import org.example.loggingsystem.outputwriter.OutputWriter;<br>import org.example.loggingsystem.outputwriter.OutputWriterFactory;<br><br>public class LoggingService {<br>    private OutputWriter outputWriter;<br>    public LoggingService(SinkType type) {<br>        this.outputWriter = OutputWriterFactory.getOutputWriter(type);<br>    }<br><br>    public void log(String message, LoggingLevel level){<br>        if (level.getPriority() &gt;= outputWriter.getDefaultLevel().getPriority())<br>            outputWriter.write(message, level);<br>    }<br><br>    public void close() {<br>        outputWriter.close();<br>    }<br>}</pre><h4>Main</h4><pre>package org.example;<br><br>import org.example.loggingsystem.enums.LoggingLevel;<br>import org.example.loggingsystem.enums.SinkType;<br>import org.example.loggingsystem.service.LoggingService;<br><br>public class App <br>{<br>    public static void main( String[] args )<br>    {<br>        LoggingService consoleLoggingService = new LoggingService(SinkType.CONSOLE);<br>        consoleLoggingService.log(&quot;Hi, I am Abhijeet!&quot;, LoggingLevel.ERROR);<br>        consoleLoggingService.log(&quot;Hi, I am Rahul!&quot;, LoggingLevel.INFO); // will not appear<br>        consoleLoggingService.log(&quot;Hi, I am Mac!&quot;, LoggingLevel.FATAL);<br><br>        LoggingService fileOutputLoggingService = new LoggingService(SinkType.FILE);<br>        fileOutputLoggingService.log(&quot;Hey, Now I am logging into a file&quot;, LoggingLevel.ERROR);<br>        fileOutputLoggingService.log(&quot;Hey, Now I am logging into a file2&quot;, LoggingLevel.INFO);<br>        fileOutputLoggingService.log(&quot;Hey, Now I am logging into a file3&quot;, LoggingLevel.FATAL);<br>        fileOutputLoggingService.log(&quot;This will not appear&quot;, LoggingLevel.DEBUG);<br>        fileOutputLoggingService.log(&quot;This will appear&quot;, LoggingLevel.WARN);<br>        fileOutputLoggingService.close();<br><br><br>    }<br>}</pre><h3>Conclusion</h3><p>In this post, we’ve designed a loosely coupled logging system in Java that allows users to choose the sink type and logging level. The system is flexible, scalable, and easy to maintain, making it suitable for a wide range of applications. By using enums, interfaces, and factory classes, we’ve decoupled the logging system from the specific implementation details, allowing for easy extension and modification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4eca48d731f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low Level Design of GoodReads /Social Cataloging App— 1]]></title>
            <link>https://medium.com/@abhijeetkarmakar1920/low-level-design-of-goodreads-social-cataloging-app-1-f5010456ee33?source=rss-25d66cc9b4c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5010456ee33</guid>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Abhijeet Karmakar]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 00:42:03 GMT</pubDate>
            <atom:updated>2024-06-01T01:20:10.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Low Level Design of Goodreads /Social Cataloging App— 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1S4CfnAnwfP0Ir1Zdrcyg.gif" /></figure><blockquote>Question : Design Goodreads.</blockquote><ul><li>User should be able to add books and friends.</li><li>User should be able to get a list of their books.</li><li>Users should be able to get list of their top books that their friends have read.</li><li>Users should be able to get list of top books that their network has read.</li></ul><blockquote>Approach</blockquote><p><strong>Models:</strong> We first create the necessary models for our app: user and book. These are simple Java POJO classes with Lombok annotations to handle basic getters, setters, and string representation.</p><ul><li><strong>Book:</strong> Represents a book with attributes like title and a unique identifier (e.g., UUID).</li><li><strong>User:</strong> Represents a user with attributes like name, a unique user ID, a list of friend IDs, and a list of book IDs.</li></ul><pre>package com.goodreads.model;<br><br>import lombok.Getter;<br>import lombok.Setter;<br>import lombok.ToString;<br><br>import java.util.UUID;<br><br>@Getter<br>@Setter<br>@ToString<br>public class Book {<br>    private String bookName;<br>    private String bookId;<br><br>    public Book(String bookName) {<br>        this.bookName = bookName;<br>        this.bookId = UUID.randomUUID().toString();<br>    }<br><br>}</pre><pre>package com.goodreads.model;<br><br>import lombok.Getter;<br>import lombok.Setter;<br><br>import java.util.HashSet;<br>import java.util.Set;<br>import java.util.UUID;<br><br>@Getter<br>@Setter<br>public class User {<br>    private String userId;<br>    private String name;<br>    private Set&lt;String&gt; friends;<br>    private Set&lt;String&gt; books;<br><br>    public User(String name) {<br>        this.name = name;<br>        this.userId = UUID.randomUUID().toString();<br>        this.friends = new HashSet&lt;&gt;();<br>        this.books = new HashSet&lt;&gt;();<br>    }<br>}</pre><p>Now, we need to create respective services for user and book management. These services will provide methods for:</p><p><strong>User Service:</strong></p><ul><li>createUser(String username): Creates a new user with the provided username.</li><li>getUser(String userId): Retrieves a user by their ID. (Optional methods can be added for removing users, etc.)</li><li>addFriend(String userId, String friendId): Adds a friend connection between two users.</li><li>addBookToList(String userId, String bookId): Adds a book to a user&#39;s reading list.</li></ul><p><strong>Book Service:</strong></p><ul><li>addBook(String bookName): Creates a new book with the provided name.</li><li>getBook(String bookId): Retrieves a book by its ID. (Optional methods can be added for searching or filtering books.)</li></ul><pre>package com.goodreads.service;<br><br>import com.goodreads.model.User;<br><br>import java.util.HashMap;<br>import java.util.Map;<br><br>//singleton class<br>public class UserService {<br><br>    private static UserService userServiceInstance;<br>    private final Map&lt;String, User&gt; users;<br><br>    public static UserService getUserServiceSingleton() {<br>        if(userServiceInstance == null)<br>          userServiceInstance = new UserService();<br>        return userServiceInstance;<br>    }<br><br>    private UserService() {<br>        this.users = new HashMap&lt;&gt;();<br>    }<br><br>    public Map&lt;String, User&gt; getUsers() {<br>        return users;<br>    }<br><br>    public User createUser(String username) {<br>        User user = new User(username);<br>        users.put(user.getUserId(), user);<br>        return user;<br>    }<br><br>    public User removeUser(String userId) {<br>        if (users.containsKey(userId))<br>            return users.remove(userId);<br>        return null;<br>    }<br><br>    public void addFriend(String userId, String friendId) {<br>        users.get(userId).getFriends().add(friendId);<br>    }<br><br>    public void addBookToList(String userId, String bookId) {<br>        users.get(userId).getBooks().add(bookId);<br>    }<br>}</pre><pre>package com.goodreads.service;<br><br>import com.goodreads.model.Book;<br>import java.util.HashMap;<br>import java.util.Map;<br><br>//singleton class<br>public class BookService {<br><br>    private static BookService bookServiceInstance;<br>    private final Map&lt;String, Book&gt; books;<br><br>    public static BookService getBookServiceSingleton() {<br>        if (bookServiceInstance == null)<br>            bookServiceInstance = new BookService();<br>        return bookServiceInstance;<br>    }<br><br>    private BookService() {<br>        this.books = new HashMap&lt;&gt;();<br>    }<br><br>    public Map&lt;String, Book&gt; getBooks() {<br>        return this.books;<br>    }<br><br>    public Book addBook(String bookName) {<br>        Book book = new Book(bookName);<br>        this.books.put(book.getBookId(), book);<br>        return book;<br>    }<br><br>}</pre><p>Pretty straightforward methods, the only magical stuff is the private constructor method and a static getServiceNameSingleton method to ensure we always get the same instance.</p><p>Okay, now comes the part where we need to brainstorm a strategy to get books for a user or get the top books a user has read.</p><p>You got it right. <strong>We’re going to use the Strategy Pattern to define our algorithms for finding top books.</strong> Why do we need strategy? Well, today we have a simpler use case to fetch top books by read count. But tomorrow, we might get a requirement to fetch them by popularity or maybe pages. Using the Strategy Pattern, we can have multiple implementations of a strategy interface and use them as per requirements.</p><pre>package com.goodreads.strategy;<br><br>import com.goodreads.model.Book;<br>import com.goodreads.model.User;<br><br>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br><br>public interface BookLookupStrategy {<br>    List&lt;Book&gt; getTopUserBooksThatFriendsHaveRead(Map&lt;String, Book&gt; books, Map&lt;String, User&gt; users, String userId, int capacity);<br>    List&lt;Book&gt; getTopBooksThatNetworksHaveRead(Map&lt;String, Book&gt; books, Map&lt;String, User&gt; users, String userId, int capacity, int maxDepth);<br>    default List&lt;Book&gt; getBooks(Map&lt;String, Book&gt; books, Map&lt;String, User&gt; users, String userId) {<br>        return users.get(userId).getBooks()<br>                .stream()<br>                .map(books::get)<br>                .collect(Collectors.toList());<br>    }<br>}</pre><pre>package com.goodreads.strategy;<br><br>import com.goodreads.model.Book;<br>import com.goodreads.model.User;<br>import com.goodreads.util.Pair;<br><br>import java.util.*;<br>import java.util.stream.Collectors;<br><br>public class BookLookupStrategyImpl implements BookLookupStrategy {<br><br>    @Override<br>    public List&lt;Book&gt; getTopUserBooksThatFriendsHaveRead(Map&lt;String, Book&gt; books, Map&lt;String, User&gt; users, String userId, int capacity) {<br>        User user = users.get(userId);<br><br>        Map&lt;String, Integer&gt; popularityCounter = user.getBooks()<br>                .stream()<br>                .flatMap(<br>                        book -&gt; user.getFriends()<br>                                .stream()<br>                                .filter(friend -&gt; users.get(friend).getBooks().contains(book))<br>                                .map(friend -&gt; book)<br>                ).collect(Collectors.toMap(<br>                        book -&gt; book,<br>                        book -&gt; 1,<br>                        Integer::sum<br>                ));<br><br>        return popularityCounter.entrySet()<br>                .stream()<br>                .sorted(Map.Entry.comparingByValue())<br>                .limit(capacity)<br>                .map(entry -&gt; books.get(entry.getKey()))<br>                .collect(Collectors.toList());<br><br>    }<br><br>    @Override<br>    public List&lt;Book&gt; getTopBooksThatNetworksHaveRead(Map&lt;String, Book&gt; books, Map&lt;String, User&gt; users, String userId, int capacity, int maxDepth) {<br>        Set&lt;String&gt; visited = new HashSet&lt;&gt;();<br>        Queue&lt;Pair&lt;String, Integer&gt;&gt; queue = new LinkedList&lt;&gt;();<br>        Map&lt;String, Integer&gt; bookFrequency = new HashMap&lt;&gt;();<br>        queue.add(new Pair&lt;&gt;(userId, 0));<br>        visited.add(userId);<br>        while (!queue.isEmpty()) {<br>            Pair&lt;String, Integer&gt; currentPair = queue.poll();<br>            String currentUserId = currentPair.getFirst();<br>            if(currentPair.getSecond() == maxDepth)<br>                break;<br>            User currentUser = users.get(currentUserId);<br><br>            currentUser.getBooks().forEach(book -&gt; {<br>                bookFrequency.put(book, bookFrequency.getOrDefault(book, 0)+1);<br>            });<br><br>            currentUser.getFriends().forEach(friend -&gt; {<br>                if(!visited.contains(friend)) {<br>                    visited.add(friend);<br>                    queue.add(new Pair&lt;&gt;(friend, currentPair.getSecond()+1));<br>                }<br>            });<br>        }<br>        return bookFrequency.entrySet()<br>                .stream()<br>                .sorted(Map.Entry.comparingByValue())<br>                .limit(capacity)<br>                .map(book -&gt; books.get(book.getKey()))<br>                .collect(Collectors.toList());<br>    }<br>}</pre><pre>package com.goodreads.util;<br><br>import lombok.Getter;<br>import lombok.Setter;<br><br>@Getter<br>@Setter<br>public class Pair&lt;K,V&gt;{<br>    K first;<br>    V second;<br>    public Pair(K first, V second) {<br>        this.first = first;<br>        this.second = second;<br>    }<br>}</pre><p>We have a BookLookupStrategy interface that defines methods for finding top books. This interface may have one default implementation and a couple of abstract classes for specific lookup criteria (e.g., by read count, popularity).</p><p>Moving on to the concrete implementation class, it provides methods like getTopUserBooksThatFriendsHaveRead and getTopBooksThatNetworksHaveRead.</p><ul><li>getTopUserBooksThatFriendsHaveRead: This method iterates through all a user’s books. It checks if the user’s friends have the same book in their lists. If a friend has the book, the book’s count is incremented in a map that uses the book ID as the key and the frequency as the value. Finally, the map is sorted based on the frequency values, and the resulting list is returned.</li><li>getTopBooksThatNetworksHaveRead: This method employs Breadth-First Search (BFS) to traverse the user’s social network level by level. An argument is passed to restrict the search depth, preventing an infinite loop.</li></ul><p>Let’s conclude this part of the design here and continue building on it in the next section. As a newcomer, I appreciate any suggestions you might have.</p><p><a href="https://medium.com/@abhijeetkarmakar1920/low-level-design-of-goodreads-social-cataloging-app-2-0d2c823bfa34">Low Level Design of Goodreads /Social Cataloging App — 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5010456ee33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>