<?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 Prince Jha on Medium]]></title>
        <description><![CDATA[Stories by Prince Jha on Medium]]></description>
        <link>https://medium.com/@jhaprincet?source=rss-bf70386c4fb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DReLrBbC4zWna9R6WhRHYw.jpeg</url>
            <title>Stories by Prince Jha on Medium</title>
            <link>https://medium.com/@jhaprincet?source=rss-bf70386c4fb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:30:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jhaprincet/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[Factory Method]]></title>
            <link>https://medium.com/@jhaprincet/factory-method-55059c2b8505?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/55059c2b8505</guid>
            <category><![CDATA[factory-method]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-method-pattern]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 09:34:12 GMT</pubDate>
            <atom:updated>2023-01-30T09:34:12.453Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 7]]</p><ul><li><a href="#abba"><strong>Concept of Factory Method Pattern</strong></a></li><li><a href="#cd3d"><strong>Class Diagram for Data Driven Factory Method Pattern</strong></a></li><li><a href="#c60f"><strong>Code Example of Data Driven Factory Design</strong></a></li><li><a href="#73c6"><strong>Class Diagram for Config Driven Factory Method Pattern</strong></a></li><li><a href="#2ddb"><strong>Code Example of Config Driven Factory Design</strong></a></li></ul><h3>Concept of Factory Method Pattern:</h3><ul><li>Clients can create object based on the event type, or based on the data that is available at the time of creation.</li><li>Keep the client class independent of the concrete types of the object. Make the client interact with the object through an interface.</li><li>Allow the addition to new concrete types of the object at a later time without affecting the client code.</li></ul><p>There are several variations of the design pattern based on the data that is available or based on the configuration that is required.</p><h3>Class Design Diagram for Data Driven Factory Method Pattern:</h3><p>In Data Driven Factory Design the <em>Factory</em> takes into consideration data that is available at the time of product creation in order to determine which type of product is suitable for the purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbuAwqX4cRBWGfJg1-cy8g.png" /></figure><p>OR</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad3eLNpcbV3KDzBGV5SNng.png" /></figure><p>The Class Diagram of Data Driven Factory Design can be described as</p><p><em>Client: </em>Class in this role represents the user class. It is aware of the <em>ProductIF</em> interface which helps it to understand how to use the product. It is aware of the <em>FactoryIF</em> interface which helps it to understand how to use a product factory. <em>Client</em> class is independent of the concrete factory types, concrete product types. It is easy to add a product/product factory without affecting the client class.</p><p><em>FactoryIF:</em> Interface that represents the method that the concrete factory classes should implement. Usually declares a method which the user should be able to use. The Client class uses the interface to interact with the factory objects. The factory interface achieves independence between the concrete product factory classes and the clients.</p><p><em>FactoryA, FactoryB, FactoryC: </em>They implement the <em>FactoryIF</em> interface. The concrete factories know about the concrete product types. These classes encapsulate the logic of under what circumstances which product type to create.</p><p><em>ProductIF: </em>Interface that represents the methods which the <em>Client</em> class can use to interact with the concrete product types. The clients interact with the product objects using the interface. The <em>ProductIF</em> interface achieves independence between client and concrete product types.</p><p><em>ProductA, ProductB, ProductB</em>: They implement the <em>ProductIF</em> interface. They encapsulate the data and logic needed to represent the product.</p><p>Code Example to Demonstrate the use of Data Driven Factory Design.</p><pre>// TRY TO DISTRIBUTE CODE IN MULTIPLE FILES<br><br>enum Color {<br>   RED, YELLOW, GREEN, BLACK, BLUE<br>};<br><br>enum ContentType {<br>  TEXT, IMAGE, ANY<br>}<br><br>class PrintSetting {<br>   private final ContentType contentType; // content type represents what is contained<br>   private final int requiredSpeed; // number of characters per second to be printed<br>   private final double maxCost;<br>  <br>   public PrintSetting(ContentType type, int speed, double cost) {<br>      contentType = type;<br>      requiredSpeed = speed;<br>      maxCost = cost;<br>   }<br><br>  // check if the available printer satisfies the required settings<br>   public static boolean isSuitable(PrintSetting required, PrintSetting available) {<br>         boolean contentTypeOk = (required.contentType == available.contentType || <br>               available.contentType == ContentType.ANY);<br>         boolean speedOk = required.requiredSpeed &lt;= available.requiredSpeed;<br>         boolean costOk = required.maxCost &gt;= available.maxCost; <br>         return contentTypeOk &amp;&amp; speedOk &amp;&amp; costOk;<br>            <br>    }<br>}<br><br>interface Printer {<br>    public void print(String content);<br>}<br><br>interface PrinterFactory {<br>    public Printer createPrinter(PrintSetting dataSettings);<br>}<br><br>class InkJetPrinter implements Printer {<br>    public static final PrintSetting THRESHOLD = new PrintSetting(<br>        ContentType.TEXT, // prints only text<br>        210,    // medium speed<br>        6000.00 // maximum cost<br>    );<br><br>    private String name; // name of printer<br>    private Color color; // color of the ink<br>    <br>    public InkJetPrinter(String name, Color color) {<br>        this.name = name;<br>        this.color = color;<br>    }<br><br>    public void print(String content) {<br>       System.out.printf(&quot;INKJET PRINTER %s WORKING&quot;, name);<br>       System.out.println(&quot;Content Text ===&gt; &quot; + content);<br>    }<br>}<br><br>class DeskJetPrinter implements Printer {<br>    public static final PrintSetting THRESHOLD = new PrintSetting(<br>        ContentType.IMAGE, // prints only image<br>        300,    // medium speed<br>        8500.50 // maximum cost<br>    );<br><br>    private String name; // name of printer<br>    private Color color; // color of the ink<br>    <br>    <br>    public DeskJetPrinter(String name, Color color) {<br>        this.name = name;<br>        this.color = color;<br>    }<br><br>    public void print(String content) {<br>       System.out.printf(&quot;DESKJET PRINTER %s WORKING&quot;, name);<br>       System.out.println(&quot;Content Image ===&gt; &quot; + content);<br>    }<br>}<br><br>class LaserPrinter implements Printer {<br>    public static final PrintSetting THRESHOLD = new PrintSetting(<br>        ContentType.ANY, // prints all kind of docs<br>        600,    // medium speed<br>        12000.20 // maximum cost<br>    );<br><br>    private String name; // name of printer<br>    private Color color; // color of the ink<br>    <br>    <br>    public LaserPrinter(String name, Color color) {<br>        this.name = name;<br>        this.color = color;<br>    }<br><br>    public void print(String content) {<br>       System.out.printf(&quot;LASER PRINTER %s WORKING&quot;, name);<br>       System.out.println(&quot;Content Any ===&gt; &quot; + content);<br>    }<br>}<br><br>class ConcretePrinterFactory implements PrinterFactory {<br>    public Printer createPrinter(PrintSetting settings) {<br>       if (PrintSetting.isSuitable(settings, LaserPrinter.THRESHOLD)) {<br>            return new LaserPrinter(&quot;TAHER LASER&quot;, Color.BLACK);<br>       } else if (PrintSetting.isSuitable(settings, DeskJetPrinter.THRESHOLD)) {<br>            return new DeskJetPrinter(&quot;PRINCE DESKJET&quot;, Color.BLUE);<br>      } else if (PrintSetting.isSuitable(settings, InkJetPrinter.THRESHOLD)) {<br>            return new InkJetPrinter(&quot;TUSHAR INKJET&quot;, Color.BLACK); <br>      } <br>      else {<br>            return null;<br>      }<br>    }<br>}<br><br>public class Client {<br>    public static void main(String [] args) {<br>        PrinterFactory factoryObj = new ConcretePrinterFactory();<br>        PrintSetting requiredSetting = new PrintSetting(ContentType.ANY, 350, 18000);<br>        Printer printer = factoryObj.createPrinter(requiredSetting);<br>        printer.print(&quot;Wowwww!!!!!😍😍😍&quot;);<br><br>    }<br>}</pre><h3>Class Design Diagram for Configuration Driven Factory Method Pattern:</h3><p>In some scenarios, the Factory does not take into consideration the data that is available in order to decide which product type to create. Instead the factory only limits itself to creating a specific type of product. Such Factory have now resulted in a configuration based factory design where the kind of factory chosen by the client will lead to the kind of product that client will get to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EYfCadxoeN0mSvQUdzroA.png" /></figure><p>The Class Diagram of Configuration Driven Factory Design can be described as</p><p><em>Client: </em>Class in this role represents the user class. It is aware of the <em>ProductIF</em> interface which helps it to understand how to use the product. It is aware of the <em>FactoryIF</em> interface which helps it to understand how to use a product factory. <em>Client</em> class is independent of the concrete factory types, concrete product types. It is easy to add a product/product factory without affecting the client class.</p><p><em>FactoryIF: </em>Interface that represents the method that the concrete factory classes should implement. Usually declares a method which the user should be able to use. The Client class uses the interface to interact with the factory objects. The factory interface achieves independence between the concrete product factory classes and the clients.</p><p><em>FactoryA, FactoryB, FactoryC: </em>They implement the <em>FactoryIF</em> interface. The config driven design of factory is different in the role. Each concrete factory often associates itself to only one corresponding concrete product type. Adding a concrete product type may require adding a concrete factory corresponding to it.</p><p><em>ProductIF: </em>Interface that represents the methods which the <em>Client</em> class can use to interact with the concrete product types. The clients interact with the product objects using the interface. The <em>ProductIF</em> interface achieves independence between client and concrete product types.</p><p><em>ProductA, ProductB, ProductB</em>: They implement the product interface. They represent a concrete product. They encapsulate the data and logic needed to represent the product.</p><p>Example Code to demonstrate Config Driven Factory Design:</p><pre>// TRY TO DISTRIBUTE CODE IN MULTIPLE FILES<br>enum Color {<br>   RED, YELLOW, GREEN, BLACK, BLUE<br>};<br><br>enum BrakeIntensity {<br>    LOW, MEDIUM, HIGH<br>}<br><br>interface CarFactory {<br>   Car createCar();<br>}<br><br>interface Car {<br>    void accelerate(int amount);<br>    void horn();<br>    void brake(BrakeIntensity intensity);<br>}<br><br>class BmwFactory implements CarFactory {<br>    private Color color;<br>    <br>    public BmwFactory(Color theColor) {<br>           color = theColor;<br>    }<br><br>    public Car createCar() {<br>       return new Bmw(color);<br>    }<br>}<br><br>class AudiFactory implements CarFactory {<br>    private Color color;<br>    <br>    public AudiFactory(Color theColor) {<br>           color = theColor;<br>    }<br><br>    public Car createCar() {<br>       return new Audi(color);<br>    }<br>}<br><br>class LamboFactory implements CarFactory {<br>    private Color color;<br>    <br>    public LamboFactory(Color theColor) {<br>           color = theColor;<br>    }<br><br>    public Car createCar() {<br>       return new Lamborghini(color);<br>    }<br>}<br><br>class Lamborghini implements Car {<br>    private static int MAX_SPEED = 220;<br>    private static int LOW_INTENSITY_BRAKE = 10;<br>    private static int MEDIUM_INTENSITY_BRAKE = 25;<br><br>    private Color color;<br>    private int currentSpeed;<br><br>    public Lamborghini(Color theColor) {<br>       color = theColor;<br>       currentSpeed = 0;<br>    }<br><br>    public void accelerate(int amount) {<br>        currentSpeed = Math.min(currentSpeed + amount, MAX_SPEED);<br>        System.out.println(&quot;Lamborghini accelerate -&gt; now speed &quot; + currentSpeed);<br>    }<br><br>    public void horn() {<br>        System.out.println(&quot;Lamborghini HORNN!!!!&quot;);<br>    }<br><br>    public void brake(BrakeIntensity intensity) {<br>        if (intensity == BrakeIntensity.LOW) {<br>             currentSpeed = Math.max(currentSpeed - LOW_INTENSITY_BRAKE, 0);<br>        } else if (intensity == BrakeIntensity.MEDIUM) {<br>              currentSpeed = Math.max(currentSpeed - MEDIUM_INTENSITY_BRAKE, 0);<br>        } else {<br>               currentSpeed = 0;<br>        }<br>        System.out.println(&quot;Lamborghini brake -&gt; now speed &quot; + currentSpeed);<br>    }<br>}<br><br>class Audi implements Car {<br>    private static int MAX_SPEED = 180;<br>    private static int LOW_INTENSITY_BRAKE = 5;<br>    private static int MEDIUM_INTENSITY_BRAKE = 30;<br>    private Color color;<br>    private int currentSpeed;<br><br>    public Audi(Color theColor) {<br>       color = theColor;<br>       currentSpeed = 0;<br>    }<br><br>    public void accelerate(int amount) {<br>        currentSpeed = Math.min(currentSpeed + amount, MAX_SPEED);<br>        System.out.println(&quot;Audi accelerate -&gt; now speed &quot; + currentSpeed);<br>    }<br><br>    public void horn() {<br>        System.out.println(&quot;Audi HORNN!!!!&quot;);<br>    }<br><br>    public void brake(BrakeIntensity intensity) {<br>        if (intensity == BrakeIntensity.LOW) {<br>             currentSpeed = Math.max(currentSpeed - LOW_INTENSITY_BRAKE, 0);<br>        } else if (intensity == BrakeIntensity.MEDIUM) {<br>              currentSpeed = Math.max(currentSpeed - MEDIUM_INTENSITY_BRAKE, 0);<br>        } else {<br>               currentSpeed = 0;<br>        }<br>        System.out.println(&quot;Audi brake -&gt; now speed &quot; + currentSpeed);<br>    }<br>}<br><br>class Bmw implements Car {<br>    private static int MAX_SPEED = 200;<br>    private static int LOW_INTENSITY_BRAKE = 2;<br>    private static int MEDIUM_INTENSITY_BRAKE = 20;<br>    private Color color;<br>    private int currentSpeed;<br>        <br>    public Bmw(Color theColor) {<br>       color = theColor;<br>       currentSpeed = 0;<br>    }<br><br>    public void accelerate(int amount) {<br>        currentSpeed = Math.min(currentSpeed + amount, MAX_SPEED);<br>        System.out.println(&quot;BMW accelerate -&gt; now speed &quot; + currentSpeed);<br>    }<br><br>    public void horn() {<br>        System.out.println(&quot;BMW HORNN!!!!&quot;);<br>    }<br><br>    public void brake(BrakeIntensity intensity) {<br>        if (intensity == BrakeIntensity.LOW) {<br>             currentSpeed = Math.max(currentSpeed - LOW_INTENSITY_BRAKE, 0);<br>        } else if (intensity == BrakeIntensity.MEDIUM) {<br>              currentSpeed = Math.max(currentSpeed - MEDIUM_INTENSITY_BRAKE, 0);<br>        } else {<br>               currentSpeed = 0;<br>        }<br>        System.out.println(&quot;BMW brake -&gt; now speed &quot; + currentSpeed);<br>    }<br>}<br><br>public class Client {<br><br>     public static void main(String [] args) {<br>          Car carObj = new AudiFactory(Color.BLACK).createCar();<br>          carObj.accelerate(40);<br>          carObj.horn();<br>          carObj.brake(BrakeIntensity.LOW);<br>     }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55059c2b8505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy]]></title>
            <link>https://medium.com/@jhaprincet/proxy-d2603dcf0a82?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2603dcf0a82</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[proxy-design-pattern]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 12:59:23 GMT</pubDate>
            <atom:updated>2023-01-21T12:59:23.656Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 6]]</p><ul><li><a href="#fff5"><strong>Concept of Proxy Design Pattern</strong></a></li><li><a href="#33f2"><strong>Characteristics of Proxy Design Pattern</strong></a></li><li><a href="#aefe"><strong>Class Diagram for Proxy Design Pattern</strong></a></li><li><a href="#53ae"><strong>Collaboration Diagram for Proxy Design Pattern</strong></a></li><li><a href="#11fd"><strong>Example Code to demonstrate the use of Proxy Design Pattern</strong></a></li></ul><h3>Concept of Proxy Design Pattern:</h3><p>The idea of Proxy Design is to make the client use a service through a proxy. The proxy should delegate the operations to the actual concrete service implementation. The proxy should implement policies around what should be done when operations are asked to be performed. The client should be independent of the concrete implementations of the service. The client code does not change irrespective of whether a proxy is used or not. The client is unaware of whether a proxy is being used or not.</p><h3>Characteristics of Proxy Design Pattern</h3><ul><li>Can be used to delay the execution time of an operation.</li><li>Remote Proxy: Creates an <em>illusion</em> that an object on a remote machine is just an object on the same machine.</li><li>Protection Proxy: Control the manner in which the concrete service implementing classes can be accessed through a proxy based on certain policies.</li><li>Virtual Proxy: Creates an illusion that the service providing object is available early when in fact it is just a proxy object. The actual underlying service implementing object could be expensive to create and hence is initialised lazily.</li></ul><h3>Class Design Diagram:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urXWQ-86IQkIVHlZ3zdagQ.png" /></figure><ul><li><em>Client</em>: class in this role wants to use a service. It depends on the <em>ServiceIF</em> interface to obtain the services.</li><li><em>ServiceIF</em>: interface in this role represents the operations that a service should provide.</li><li><em>ServiceA</em>, <em>ServiceB</em>: classes in these roles are concrete service providing classes.</li><li><em>ServiceProxy</em>: class in this role represents a proxy. The proxy class delegates operations to other service providing classes using the serviceIF interface. The ServiceProxy class also implements the ServiceIF interface itself so that clients can access the class as if were some service providing class. The real use of ServiceProxy class is to implement certain policies regarding under what circumstances the operations should be delegated in which manner etc.</li></ul><h3>Collaboration Diagram for Proxy Design Pattern:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5IWSNxpNB1EIqDJvHlp8A.png" /></figure><h3>Example Code to demonstrate the use of Proxy Design Pattern:</h3><p>Let us design a proxy which delays the <em>add</em> method on List by N seconds. We will make the same thread wait for at least N seconds before completing the <em>add</em> operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiCfjIdDxzEMH_JIvDFWcA.png" /></figure><pre>import java.util.*;<br>import java.util.concurrent.TimeUnit;<br><br>class DelayList&lt;E&gt; implements List&lt;E&gt; {<br>    private static int DEFAULT_DELAY_TIME = 2;<br><br>    private List&lt;E&gt; associatedList;<br>    private int delayTimeInSeconds;<br><br>    public DelayList(List&lt;E&gt; theList) {<br>        associatedList = theList;<br>        delayTimeInSeconds = DEFAULT_DELAY_TIME;<br>    }<br>  <br>    public DelayList(List&lt;E&gt; theList, int numberOfSeconds) {<br>        associatedList = theList;<br>        delayTimeInSeconds = numberOfSeconds;<br>    }<br><br>    public List&lt;E&gt; subList(int fromIndex, int toIndex) {<br>        return new DelayList(associatedList.subList(fromIndex, toIndex), delayTimeInSeconds);<br>    }<br>    <br>    public ListIterator&lt;E&gt; listIterator(int index) {<br>        return associatedList.listIterator(index);<br>    }<br>    <br>    public ListIterator&lt;E&gt; listIterator() {<br>        return associatedList.listIterator(0);<br>    }<br>    <br>    public int lastIndexOf(Object targetObj) {<br>        return associatedList.lastIndexOf(targetObj);<br>    }<br>    <br>    public int indexOf(Object targetObj) {<br>        return associatedList.indexOf(targetObj);<br>    }<br>    <br>    public E remove(int index) {<br>        return associatedList.remove(index);<br>    }<br>    <br>    public boolean add(E obj) {<br>        try {<br>            TimeUnit.SECONDS.sleep(delayTimeInSeconds);<br>            return associatedList.add(obj);<br>        } catch(InterruptedException error) {<br>            System.out.println(&quot;Interrupted thread when blocked/waiting &quot; + error.getMessage());<br>            return false;<br>        }<br>        <br>    }<br>    <br>    public void add(int index, E obj) {<br>         associatedList.add(index, obj);<br>    }<br>    <br>    public E set(int index, E obj) {<br>        return associatedList.set(index, obj);<br>    }<br>    <br>    public E get(int index) {<br>        return associatedList.get(index);<br>    }<br>    <br>    public void clear() {<br>        associatedList.clear();<br>    }<br>    <br>    public boolean retainAll(Collection&lt;?&gt; coll) {<br>        return associatedList.retainAll(coll);<br>    }<br>    <br>    public boolean removeAll(Collection&lt;?&gt; coll) {<br>        return associatedList.removeAll(coll);<br>    }<br>    <br>    public boolean addAll(int index, Collection&lt;? extends E&gt; coll) {<br>        return associatedList.addAll(index, coll);<br>    }<br>    <br>    public boolean addAll(Collection&lt;? extends E&gt; coll) {<br>        return associatedList.addAll(coll);<br>    }<br><br>    <br>    public boolean remove(Object obj) {<br>        return associatedList.remove(obj);<br>    }<br>    <br>    public Object[] toArray() {<br>        return associatedList.toArray();<br>    }<br>    <br>    public &lt;T&gt; T[] toArray(T[] obj) {<br>        return associatedList.toArray(obj);<br>    }<br>    <br>    public Iterator iterator() {<br>        return associatedList.iterator();<br>    }<br>    <br>    public boolean contains(Object obj) {<br>        return associatedList.contains(obj);<br>    }<br>    <br>    public boolean isEmpty() {<br>        return associatedList.isEmpty();<br>    }<br>    <br>    public int size() {<br>        return associatedList.size();<br>    }<br>    <br>    public boolean containsAll(Collection&lt;?&gt; coll) {<br>        return associatedList.containsAll(coll);<br>    }<br>}<br><br>public class Client {<br>    public static void main(String args[]) {<br>        List&lt;Integer&gt; arr = new DelayList&lt;&gt;(new ArrayList&lt;&gt;());<br>        System.out.println(&quot;Before a few add operations&quot;);<br>        arr.add(5000);<br>        arr.add(20000);<br>        System.out.println(&quot;After a few add operations&quot;);<br>        return;<br>    }<br>}</pre><p>Of course writing a Wrapper Class and using the delegation technique involves writing lots of code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2603dcf0a82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marker Interface/ Tagging Interface]]></title>
            <link>https://medium.com/@jhaprincet/marker-interface-tagging-interface-9e63581710a5?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e63581710a5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[tagging-interface]]></category>
            <category><![CDATA[marker-interface]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 13:36:25 GMT</pubDate>
            <atom:updated>2023-01-19T13:40:15.726Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns— 5]]</p><ul><li><a href="#f07c"><strong>Concept of Marker Interface</strong></a></li><li><a href="#54ce"><strong>Class Design Diagram of Marker Interface</strong></a></li><li><a href="#764e"><strong>Collaboration Diagram of Marker Interface</strong></a></li><li><a href="#278b"><strong>Code Example to show the use of Marker Interface</strong></a></li></ul><h3>Concept of Marker Interface:</h3><p>Marker interfaces are empty interfaces and usually do not contain anything. It represents certain attribute of the class. Basically a client can get to know if an object is an instance of a class that contains the marker interface in its hierarchy. The Marker interfaces are used to represent answers to simple yes/no questions about the class. Usually if a class is tagged with a marker interface they may support certain functionality.</p><h3>Class Diagram:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bhRCyIpla0GtKtU01Ycbg.png" /></figure><p><em>Client</em>: Classes in this role represent user classes that know about the Marker Interface. These clients usually perform certain logic where they want to know if an object is an instance of the Marker Interface. In other words they usually want to know if the actual type of an object contains the marker interface in its hierarchy. They try to use this knowledge in certain situations.</p><p><em>SpecialClassA</em>, <em>SpecialClassB</em>: Classes in these roles are classes that are tagged with Marker Interface. They are believed to have some special characteristics.</p><p>NormalClassA, NormalClassB: Classes in these roles are classes that are not tagged with Marker Interface. They lack the special characteristic that the Special Classes have.</p><h3><strong>Collaboration Diagram of Marker Interface:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyA8kTLwR9XMUISr6WE28g.png" /></figure><p>Scenario 1: application program calls the <em>someOp</em> method on client object. The <em>markedObj</em> argument represents an object of a special class which is tagged with a tagging interface.</p><p>Scenario 2: application program calls the <em>someOp</em> method on client object.<br>The <em>normalObj</em> argument represents an object of a normal class which is not tagged with a tagging interface.</p><p>The code logic of <em>someOp</em> method tries to treat <em>markedObj</em> differently than the <em>normalObj</em> by using an if condition check to determine if the actual type of the object corresponds to a tagged interface or not.</p><p>In Java, the <em>Cloneable</em> interface represents a marker interface. The implementation of the <em>Object</em>::<em>clone</em> method checks whether the <em>this</em> context object on which the <em>clone</em> method executes represents an object which is tagged with the <em>Cloneable</em> marker interface.</p><pre>protected Object clone() throws CloneNotSupportedException {<br>     // instanceof check executed through dynamic binding<br>     boolean isCloneableThisObj = (this instanceof Cloneable); <br>     if (isCloneableThisObj) {<br>         return VMObject.clone((Cloneable) this);<br>     }<br>       <br>     throw new CloneNotSupportedException(&quot;Object not cloneable&quot;);<br>}</pre><h3>Code Example:</h3><p>The below code example is intended to give you an idea of how the marker interface could be used.</p><p>The Client class only uses the Animal class and Loyal interface. The client wants animals to be treated based on its Loyalty. It knows about the Loyal Marker Interface which is used for tagging different different subtype of Animal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mScqGBglQEl4NBeKArLxLw.png" /></figure><pre>interface Loyal {};<br><br>// Logic common to Animals<br>class Animal {}<br><br>// Logic specific to Cats, Cats Not Loyal<br>class Cat extends Animal {}<br><br>// Logic specific to Dog, Dogs Loyal<br>class Dog extends Animal implements Loyal {}<br><br>public class Client {<br>     public static void main(String [] args) {<br>         Animal [] animals = new Animal[5]; // client uses Animal<br>         animals[0] = new Cat();<br>         animals[1] = new Dog();<br>         animals[2] = new Dog();<br>         animals[3] = new Cat();<br>         animals[4] = new Cat();<br>         for(Animal being: animals) {<br>               boolean isLoyal = being instanceof Loyal; <br>               // client checks if the object corresponds <br>               // to type whose hierarchy contains tagging interface <br>               System.out.println(&quot;animal is loyal &quot; + isLoyal);<br>         }<br>     }<br>}</pre><p>Of course it is common to design classes that rely on complex ideas like dynamic binding to determine at runtime whether the actual type of object is tagged or not. Such checks are performed using the <em>instanceof</em> operator directly and code logic that relies on whether or not objects are tagged or not can be a part of the class.</p><p>Usage 1: The Cloneable interface is used for tagging classes whose objects should support cloning functionality. The <em>Object::clone</em> method relies on dynamic binding to test at runtime whether the object which is maintained as <em>this</em> context at the time of execution is tagged with <em>Cloneable</em> interface.</p><p>The Object::clone method itself is not sufficient for cloning complex nested composite objects. We need to override the <em>clone</em> method to enhance the logic in the sub types.</p><p>Usage 2: The <em>Serializable</em> Marker interface is used for tagging classes whose objects should be considered serializable (converted into a byte stream) as well as deserializable (converted from byte stream to objects).</p><p>The <em>ObjectInputstream</em> and <em>ObjectOutputStream</em> rely on the marker interface check to ensure that the object is serializable, deserializable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e63581710a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutability]]></title>
            <link>https://medium.com/@jhaprincet/immutability-a99bed7570f9?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a99bed7570f9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[immutable-objects]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 20:04:27 GMT</pubDate>
            <atom:updated>2023-01-18T20:04:27.337Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 4]]</p><ul><li><a href="#add1"><strong>Concept of Immutable objects</strong></a></li><li><a href="#5e58"><strong>Characteristics of Immutable Design</strong></a></li><li><a href="#1a5f"><strong>Class Design Diagram for the Immutable Design</strong></a></li><li><a href="#2d82"><strong>Example Code to illustrate the use of Immutable Design</strong></a></li></ul><h3>Concept of Immutable objects:</h3><p>The concept of Immutability in Design is that we only allow objects whose fields are read only. The user of an <strong><em>immutable object</em></strong> should not be able to change any attribute on the object. If the attributes of immutable object are primitive values then they must be <strong><em>final</em></strong> and thus assignment operation should be disallowed preventing modification to the primitive values. If the attributes of immutable object are references to other object then the <strong><em>referent</em></strong> object must be an <strong><em>immutable</em></strong> <strong><em>object</em></strong>. Note the recursive nature of the definition of immutability.</p><h3>Characteristics of Immutable Design:</h3><ul><li>Design objects that never need to change their state</li><li>Allowing several sources of modification to an object’s state which can lead to bugs. In a multi threaded application synchronization may be required to avoid inconsistent state of the object.</li><li>Instead of allowing modification to an object’s state, we can create a new object altogether for the use case. We can ensure each time a different state of object is necessary, a new object will be allocated memory. This may lead to increase in memory utilisation but will ensure that programmer always uses an immutable object.</li><li>Using immutable objects can be beneficial in a multi threaded application since the design guarantees that an object’s state can never be corrupted.</li><li>The Design has a limitation that the size of objects should be small. Creating new objects for large objects causes memory wastage as well as runtime inefficiency.</li></ul><h3><strong>Class Design Diagram for the Immutable Design:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*eEI0Kyb5V30SgCLs0-fu0g.png" /></figure><p><em>ImmutableClass</em>: Class in this role define the design of an immutable object.</p><ul><li>The primitive fields of an immutable object are effectively final</li><li>The associated Java reference is also effectively final.</li><li>The associated referent object is an immutable object.</li><li>Notice the lack of setters and read only nature of the attributes.</li></ul><h3>Example Code to illustrate the use of Immutable Design:</h3><pre>class Complex {<br>    // z = a + ib<br>    private final double a;<br>    private final double b;<br><br>    public Complex(double x, double y) {<br>        this.a = x;<br>        this.b = y;<br>    }<br><br>    public final double getRealPart() {<br>        return a;<br>    }<br><br>    public final double getImaginaryPart() {<br>        return b;<br>    }<br><br>    public final Complex add(Complex other) {<br>        return new Complex(this.a + other.a, this.b + other.b);<br>    }<br><br>    public final Complex subtract(Complex other) {<br>        Complex negativeOneComplex = new Complex(-1, 0); // z = -1 + i(0)<br>        Complex negativeOther = other.multiply(negativeOneComplex);<br>        return this.add(negativeOther);<br>    }<br><br>    public final Complex multiply(Complex other) {<br>         double realPart = (this.a * other.a) - (this.b * other.b);<br>         double complexPart = (this.a * other.b) + (this.b * other.a);<br>         return new Complex(realPart, complexPart);<br>    }<br>}</pre><p>The String Class in Java is a typical example of an immutable class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a99bed7570f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract SuperClass]]></title>
            <link>https://medium.com/@jhaprincet/abstract-superclass-c36fcde08a53?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36fcde08a53</guid>
            <category><![CDATA[abstract-supercases]]></category>
            <category><![CDATA[abstract-base-classes]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[interface-design]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 13:27:36 GMT</pubDate>
            <atom:updated>2023-01-18T19:14:32.627Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 3]]</p><ul><li><a href="#3e86"><strong>Concept of Abstract SuperClass</strong></a></li><li><a href="#11de"><strong>Characteristics of Abstract SuperClass</strong></a></li><li><a href="#7f81"><strong>Abstract SuperClass Design</strong></a></li><li><a href="#1e9a"><strong>Example Code to demonstrate the use of Abstract SuperClass</strong></a></li><li><strong>Interface and Abstract SuperClass Design</strong></li><li><a href="#2e76"><strong>Interface vs Abstract SuperClass</strong></a></li></ul><h3>Concept of Abstract SuperClass:</h3><p>An Abstract SuperClass is an abstract class which encapsulates the fields and methods that its sub types might need. It can also be used to provide default implementations of certain methods that can be overridden by sub types. It can also contain abstract instance methods which must be overridden by the sub types. Hence Abstract SuperClass can be used to write high level abstract logic needed by sub types.</p><h3>Characteristics of Abstract SuperClass:</h3><ul><li>Ensures that logic common to its related classes are implemented consistently in one place.</li><li>Helps maintain the code reused in several classes in one place.</li><li>Helps sub types by implementing most of the required functionalities. Sub types only need to implement the abstract methods. Of course the sub types are always allowed to improve the implementations of non-private instance methods through method overriding.</li></ul><h3>Abstract SuperClass Design:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8TpEeYRY11ouK1QrJLCNw.png" /></figure><p><em>AbstractSuperClass</em>: Class in this role contain the code of the reusable logic of some of the operations that are <em>common</em> across all its subclasses. Class in this role may either declare abstract methods for the subtype specific implementations or provide a default implementation for these <em>variable operations</em>. Class in this role can help define instance fields that the type should contain when subclassing it. Class in this role can also help define static fields and static methods that could be shared by the sub types.</p><p><em>ConcreteClassA</em>: Class in this role need to provide the implementations of the variable operations according to the purpose of the class. They inherit common functionalities from Abstract Super Class.</p><p><em>ConcreteClassB</em>: Class in this role need to provide the implementation of the variable operations according to the purpose of the class. They inherit common functionalities from Abstract Super Class.</p><p>Example: Let us assume that the AbstractShape class contains a logic which mentions the name of the shape and prints the area of the shape. This logic is common to all the shapes and hence can become a part of the common logic in Abstract SuperClass.<br>On the other hand the dimensions of the shape and how the area of the shape is calculated is only known to the respective shape which forms the variable logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8S_Vnp5ellpnV8Z4rvOCTw.png" /></figure><pre>abstract class AbstractShape {<br>    private String nameOfShape;<br><br>    public static final String Square = &quot;Square&quot;;<br>    public static final String Rectangle = &quot;Rectangle&quot;;<br>    public static final String Circle = &quot;Circle&quot;;<br><br>    protected AbstractShape(String name) {<br>       nameOfShape = name;<br>    }<br><br>    abstract public double calculateArea();<br><br>    public void printArea(){<br>       double area = this.calculateArea(); // dynamic binding<br>       System.out.println(&quot;The area of the &quot; + nameOfShape + &quot; = &quot; + area);<br>    }<br>}<br><br>class Rectangle extends AbstractShape {<br>     private double length;<br>     private double breadth;<br><br>     public Rectangle(String name, double length, double breadth) {<br>         super(name);<br>         this.length = length;<br>         this.breadth = breadth;<br>     }<br><br>     public double calculateArea() {<br>         return length * breadth;<br>     }<br>}<br><br>class Circle extends AbstractShape {<br>     private double radius;<br><br>     public Circle(String name, double radius) {<br>          super(name);<br>          this.radius = radius;<br>     }<br><br>     public double calculateArea() {<br>         return Math.PI * radius * radius;<br>     }<br>}<br><br>public class MyClass {<br>     public static void main(String [] args) {<br>         AbstractShape rect = new Rectangle(AbstractShape.Rectangle, 42.1, 13.7);<br>         AbstractShape circ = new Circle(AbstractShape.Circle, 12.5);<br><br>         rect.printArea();<br>         circ.printArea();<br>     }<br>}</pre><p>The <em>AbstractIterator</em> class in Java is an abstract super class that contains common logic used by the <em>Iterator</em> corresponding to various collections.<br>The abstract class throws an <em>UnsupportedOperationException</em> as a default implementation of the <em>remove</em> method.</p><h3><strong>Interface and Abstract SuperClass Design:</strong></h3><p>The idea of interface and abstract superclass design is to allow the users to access the objects only through an interface thus achieving independence between the client and the implementation classes. Clients can only access a service using an interface. The fields that are needed in each of the subtype objects and the common logic can be encapsulated in the abstract super class. The variable logic can be provided by each of the concrete classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*pYT7igbnDusAWkTtTFsBhA.png" /></figure><h3>Interface vs Abstract SuperClass:</h3><p>Since Java interfaces now support default implementations of instance methods, private instance methods, static public methods, static private methods, static fields to be defined on them. They also support inheriting from multiple other interfaces. Can these features be used to replace Abstract SuperClass Design altogether?</p><p>The reason for this line of thinking is that a class can only inherit from one super class so the Abstract SuperClass Design is a compromise. Can we avoid inheriting from a class but instead inherit from an interface which still provides us the functionality and we can continue to inherit from other interfaces, one other class.</p><p>The answer is “Not Always”. Remember that a class is allowed to define instance fields on the object and write code logic that operates on these fields, interfaces cannot do that. Thus Abstract SuperClass do provide extra convenience in terms of defining the objects and encapsulating common logic.</p><p>Although there are scenarios where we do not need an Abstract Super Class but an interface would be sufficient. The <em>compose</em> method in Function functional interface only needs the feature like dynamic binding of <em>apply</em> method but does not need any fields added on the object. It only needs common logic to be encapsulated in a default method. An interface is sufficient to provide the required flexibility.</p><pre>package java.util.function;<br>import java.util.Objects;<br><br>@FunctionalInterface<br>public interface Function&lt;T, R&gt; {<br><br>    R apply(T t); // single abstract method<br><br>    default &lt;V&gt; Function&lt;V, R&gt; compose(Function&lt;? super V, ? extends T&gt; before) {<br>        Objects.requireNonNull(before);<br>        return (V v) -&gt; this.apply(before.apply(v));<br>    }<br><br>    default &lt;V&gt; Function&lt;T, V&gt; andThen(Function&lt;? super R, ? extends V&gt; after) {<br>        Objects.requireNonNull(after);<br>        return (T t) -&gt; after.apply(this.apply(t));<br>    }<br><br>    static &lt;T&gt; Function&lt;T, T&gt; identity() {<br>        return t -&gt; t;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36fcde08a53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restrict the manner in which clients interact with object using Interface]]></title>
            <link>https://medium.com/@jhaprincet/restrict-the-manner-in-which-clients-interact-with-object-using-interface-d75e9014e5f7?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75e9014e5f7</guid>
            <category><![CDATA[interface-design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 10:59:10 GMT</pubDate>
            <atom:updated>2023-01-15T03:31:34.477Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 2]]</p><ul><li><a href="#e2ec"><strong>Considerations in Interface Design</strong></a></li><li><a href="#73ce"><strong>Diagram representing the concept</strong></a></li><li><a href="#0337"><strong>Code Example demonstrating independence between the client class and the actual class of the object used by the client</strong></a></li></ul><h3>Interface Design:</h3><p>Instead of overwhelming the Client with the unnecessary details, force the client to access the object through an interface variable. Ensure that the interface contains all that the knowledge that client will need to use the object.</p><p>Achieve independence between the user and the class that the user uses.</p><p>User should be able to easily switch from using one class to using another class without breaking the client application.</p><p>The idea of interface design is to ensure that the clients will be able to operate on the object only using the limited knowledge that they have. <br>Restricting the manner in which the clients must use the object will lead to code that is easy to change and easy to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*qEvU7W-rzEpgtyObkxpuFQ.png" /></figure><p>Client: class in this role is only concerned about being able to use objects which support the <em>read</em>, <em>write</em> operations. It uses the objects using the <em>Scholar</em> interface. The client does not bother about the actual type of object being used as long as the type (or its hierarchy) implements <em>Scholar</em> interface.</p><p><em>Scholar</em>: interface in this role defines a contract that the <em>read</em>, <em>write</em> operation must be supported by classes that implement the interface.</p><p><em>Student</em>: class in this role define data and behaviour of a student who likes to study, watch movies ...etc. The class also implements the <em>Scholar</em> interface.</p><pre>import java.util.*;<br>import java.util.stream.*;<br><br>interface Scholar {<br>   void read(String content);<br>   void write(String content);<br>}<br><br>class Client {<br>     // can only operate on the object in a restricted manner through the interface<br>     private Scholar scholar;<br><br>     public Client(Scholar scholar) {<br>          this.scholar = scholar;<br>     }<br>   <br>     public void changeScholar(Scholar otherScholar) {<br>            scholar = otherScholar;<br>     }<br><br>     public void improveKnowledge(List&lt;String&gt; books) {<br>          books.<br>          stream().<br>          forEach(scholar::read);<br>     }<br>}<br><br>class Student implements Scholar {<br>    String name;<br>    List&lt;String&gt; materialsRead;<br>    List&lt;String&gt; materialsWritten;<br>  <br>    public Student(String nameOfStudent) {<br>        this.name = nameOfStudent;<br>        materialsRead = new ArrayList&lt;&gt;();<br>        materialsWritten = new ArrayList&lt;&gt;();<br>    }<br><br>    private boolean isPresent(String content, List&lt;String&gt; collection) {<br>         return collection.<br>                stream().<br>                filter(content::equalsIgnoreCase).<br>                count() &gt; 0;<br>    }<br><br>    public void read(String content) {<br>       if(isPresent(content, materialsRead)) {<br>             System.out.println(&quot;This content is already read&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully read the content&quot;);<br>       materialsRead.add(content);<br>    }<br><br>    public void write(String content) {<br>        if(isPresent(content, materialsWritten)) {<br>             System.out.println(&quot;This content is already written&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully written the content&quot;);<br>       materialsWritten.add(content);<br>    }<br><br>    public void eat(String food) {<br>       System.out.println(&quot;Eating &quot; + food);<br>      // .....<br>    }<br>    <br>    public void rest(int numberOfHours) {<br>       System.out.println(&quot;Resting for &quot; + numberOfHours);<br>       // .....<br>    }<br><br>    public void watchMoive(String nameOfMovie) {<br>       System.out.println(&quot;Watching Movie &quot; + nameOfMovie);<br>       // .....<br>    }<br>}<br><br>public class MyClass {<br>    public static void main(String [] args) {<br>        Client clientA;<br>        Client clientB;<br><br>        clientA = new Client(new Student(&quot;Prince Jha&quot;));<br>        clientB = new Client(new Student(&quot;Tushar Kashikar&quot;));<br>        <br>        clientA.improveKnowledge(List.of(&quot;Mark Grand - Patterns in Java&quot;, &quot;Database Systems - Elmasri, Navathe&quot;));<br>        clientB.improveKnowledge(List.of(&quot;Language Theory - Ullman&quot;, &quot;Principia Mathematicia&quot;));<br>    }<br>}</pre><p>Assume that the clients are not happy with the <em>Student</em> class and want to use <em>Scientist</em> instead for the reading and writing. It can be easily achieved if the Scientist class implements <em>Scholar</em> interface. Remember that clients in this case only depend on the <em>Scholar</em> interface but NOT on the <em>Student</em> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pORMQWpwh_mn4Xn25qL6g.png" /></figure><pre>import java.util.*;<br>import java.util.stream.*;<br><br>///// NO CHANGE IN INTERFACE<br>interface Scholar {<br>   void read(String content);<br>   void write(String content);<br>}<br><br>//// NO CHANGE IN STUDENT TYPE, IT IS A KIND OF SCHOLAR<br>class Student implements Scholar {<br>    String name;<br>    List&lt;String&gt; materialsRead;<br>    List&lt;String&gt; materialsWritten;<br>  <br>    public Student(String nameOfStudent) {<br>        this.name = nameOfStudent;<br>        materialsRead = new ArrayList&lt;&gt;();<br>        materialsWritten = new ArrayList&lt;&gt;();<br>    }<br><br>    private boolean isPresent(String content, List&lt;String&gt; collection) {<br>         return collection.<br>                stream().<br>                filter(content::equalsIgnoreCase).<br>                count() &gt; 0;<br>    }<br><br>    public void read(String content) {<br>       if(isPresent(content, materialsRead)) {<br>             System.out.println(&quot;This content is already read&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully read the content&quot;);<br>       materialsRead.add(content);<br>    }<br><br>    public void write(String content) {<br>        if(isPresent(content, materialsWritten)) {<br>             System.out.println(&quot;This content is already written&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully written the content&quot;);<br>       materialsWritten.add(content);<br>    }<br><br>    public void eat(String food) {<br>       System.out.println(&quot;Eating &quot; + food);<br>      // .....<br>    }<br>    <br>    public void rest(int numberOfHours) {<br>       System.out.println(&quot;Resting for &quot; + numberOfHours);<br>       // .....<br>    }<br><br>    public void watchMoive(String nameOfMovie) {<br>       System.out.println(&quot;Watching Movie &quot; + nameOfMovie);<br>       // .....<br>    }<br>}<br><br>//// NO CHANGE IN CLIENT CODE<br>class Client {<br>     // can only operate on the object in a restricted manner through the interface<br>     private Scholar scholar;<br><br>     public Client(Scholar scholar) {<br>          this.scholar = scholar;<br>     }<br>   <br>     public void changeScholar(Scholar otherScholar) {<br>            scholar = otherScholar;<br>     }<br><br>     public void improveKnowledge(List&lt;String&gt; books) {<br>          books.<br>          stream().<br>          forEach(scholar::read);<br>     }<br>}<br><br>///// ANOTHER DIFFERENT KIND OF SCHOLAR DEFINED<br>class Scientist implements Scholar {<br>    String name;<br>    Set&lt;String&gt; materialsRead;<br>    Set&lt;String&gt; materialsWritten;<br>  <br>    public Scientist(String scientist) {<br>        this.name = scientist;<br>        materialsRead = new ArrayList&lt;&gt;();<br>        materialsWritten = new ArrayList&lt;&gt;();<br>    }<br><br>    private boolean isPresent(String content, Set&lt;String&gt; set) {<br>         return set.contains(content);<br>    }<br><br>    public void read(String content) {<br>       if(content == null || content.equals(&quot;&quot;)) {<br>          return;<br>       }<br>       contentLower = content.toLowerCase();<br>       if(isPresent(contentLower, materialsRead)) {<br>             System.out.println(&quot;This content is already read&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully read the content&quot;);<br>       materialsRead.add(contentLower);<br>    }<br><br>    public void write(String content) {<br>       if(content == null || content.equals(&quot;&quot;)) {<br>          return;<br>       }<br>       contentLower = content.toLowerCase();<br>       if(isPresent(contentLower, materialsWritten)) {<br>             System.out.println(&quot;This content is already written&quot;);<br>             return;<br>       }<br>       System.out.println(&quot;Successfully written the content&quot;);<br>       materialsWritten.add(contentLower);<br>    }<br>    <br>    // other things that scientist do .......<br>}<br><br>////// CLIENTS CAN WORK WITH DIFFERENT KINDS OF SCHOLARS<br>public class MyClass {<br>    public static void main(String [] args) {<br>        Client clientA;<br>        Client clientB;<br><br>        clientA = new Client(new Scientist(&quot;Newton&quot;));        <br>        clientA.improveKnowledge(List.of(&quot;Mark Grand - Patterns in Java&quot;, &quot;Database Systems - Elmasri, Navathe&quot;));<br><br>        clientB = new Client();<br>    }<br>}</pre><p>If the <em>Scientist</em> class does not directly implement the <em>Scholar</em> interface but does support similar operations, you might need to define a custom <strong>adapter</strong> type which is a kind of <em>Scholar</em> that delegates to a <em>Scientist</em> object. Then use the client with the adapter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75e9014e5f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegation (Avoiding inheritance when unnecessary)]]></title>
            <link>https://medium.com/@jhaprincet/delegation-avoiding-inheritance-when-unnecessary-8400e53f6e54?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8400e53f6e54</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[composition]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 02:17:50 GMT</pubDate>
            <atom:updated>2023-01-18T19:04:57.248Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Design Patterns — 1]]</p><ul><li><a href="#1b65"><strong>When is inheritance suitable</strong></a></li><li><a href="#89b3"><strong>When is composition suitable</strong></a></li><li><a href="#c4f8"><strong>When not to use inheritance</strong></a></li><li><a href="#0a2b"><strong>Delegator Design</strong></a></li></ul><h3>When is inheritance suitable:</h3><p>Inheritance is a feature used to extend and reuse the existing functionality of a class. Inheritance establishes an “is a” relationship between the inheriting type to the inherited type.</p><p>When using inheritance:</p><ul><li>The contract of subclass should be an extension of the contract of its super class.</li><li>No method of super class should be non-required by the sub class. (<em>Ostrich</em> class cannot inherit from <em>Bird</em> class if <em>Bird</em> class contains <em>fly</em> method which is non-required by <em>Ostrich</em>).</li><li>It is perfectly fine to enhance the functionality of super class method in a sub class.</li><li>The super class should be closed for modifications. Since inheritance allows sub-typing, a super class can be inherited by multiple derived classes. Changing the super class functionality can lead to unexpected results in the derived class. Thus adding a method, removing a method. modifying a method etc in the super class is dangerous and violates a class design principle.</li></ul><pre>class Person{};<br>class Engineer extends Person {};<br>class Doctor extends Person {};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*5dBfLmZ99nkKO5ty53WRDw.png" /></figure><h3>When is composition suitable:</h3><p>To model the “has a” relationship between types, we use composition. Composition is a part-whole relationship. Composition is also suitable when one object wants to delegate a responsibility to another object. Associations, aggregations, compositions are achieved using the idea of delegation (one object can simply ask an associated object for some help).</p><pre>class Bird {};<br>class Ostrich {<br>    private Bird birdObj;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*ZV0Lx6xFwniVPeaUl6rmzA.png" /></figure><h3>When not to use inheritance:</h3><ul><li>The inheritance relationship between types (in OOP) cannot be changed dynamically. If an object needs to be an instance of a different subclass at different different times, then the inheritance relationship is not suitable. In other words if you are forced to create a different object at different times to obtain necessary behaviour, there is no need of inheritance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*FPgfbKYtSOLaMRGd8rAvLg.png" /><figcaption>Wrong Use of Inheritance</figcaption></figure><p>Consider an example where a Person Mahesh acts like a <em>Father</em>, <em>Husband</em>, <em>Son</em> at the same time. The fields that are defined by the <em>Person</em> type need to be inherited by each of its subtype. Distinct copy of the instance fields will be present in the object created using <em>Father</em>, <em>Husband</em>, <em>Son </em>even when these objects are trying to represent the same <em>Person </em>in different roles. There is unnecessary memory consumption. Also if we want to change some attribute in the <em>Person</em> Mahesh, we will have to ensure consistency across various objects that are trying to present Mahesh in various roles.</p><p>instead we should try to reuse the same <em>Person</em> object and all the roles that Mahesh could involve in could try to reuse the <em>Person</em> object through composition. Now changing the Person specific attributes is easy through delegation, same Person is also being represented to fit various roles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*a2jiKqmTyN29m9QvWIuAPg.png" /></figure><ul><li>When a subclass is forced to hide the inherited functionality, then there should not have been an inheritance relationship between those classes.</li></ul><pre>class Bird {<br>   private String name;<br>   private String color;<br>   private String weight;<br><br>   public void fly() {<br>        System.out.println(&quot;Flying with weight &quot; + weight);<br>   }<br> <br>   public void checkColor() {<br>        System.out.println(&quot;My Color is &quot; + color);<br>   }<br>}</pre><pre>// BAD DESIGN, Inheritance and Overriding with do-nothing methods<br>class Ostrich extends Bird {<br>   // do nothing when fly<br>   public void fly() {}<br>}<br><br>// GOOD DESIGN, WHEN DELEGATION IS USED, <br>// NO NEED TO HIDE METHODS, DO NOT INCLUDE THEM WHEN NOT NEEDED<br>class Ostrich {<br>     private Bird bird;<br><br>     public void checkColor() {<br>         bird.checkColor(); // delegate to the bird object<br>     }<br>    <br>}</pre><h3>Delegator Design:</h3><p>The Delegator Design is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*AdvoCGI1yTFM95NjDRc59A.png" /></figure><p><em>Delegator</em>: objects of the <em>Delegator</em> class ask the <em>Delegate</em> object to perform an operation on their behalf. They rely of the <em>Delegate</em> object for the result.<br>Delegate: objects of <em>Delegate</em> class are associated to a <em>Delegator</em> who will ask it for help.</p><p>Example of Delegation Design:<br>Consider an application in which the user of application types search text and expects recommendation list for the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFwaEmgtMWIYX55G9PGvgg.png" /></figure><pre>class AppUser {<br><br>    // ...<br>    private SearchRecommender searchSuggestions;<br><br>    public List&lt;Suggestion&gt; getSuggestion(String userInput) {<br>         // AppUser delegates to SearchRecommender<br>        return searchSuggestions.getSuggestion(userInput);<br>    }<br><br>}<br><br>class SearchRecommender {<br>    // ....<br><br>    private ArrayList&lt;Suggestion&gt; allSuggestions;<br><br>   // SearchRecommender determines the right suggestions<br>   public List&lt;Suggestion&gt; getSuggestion(String userInput) {<br>        return allSuggestions.<br>               stream().<br>               filter((suggestion) -&gt; suggestion.isGoodRecommendation(userInput)).<br>               collect(Collectors.toList());<br>   }     <br>}<br><br>class Suggestion {<br>   // ...<br>   String suggestionText;<br>   <br>  // logic to determine whether a recommendation is suitable for text<br>   public boolean isGoodRecommendation(String userInput) {<br>       return suggestionText.contains(userInput);<br>   }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8400e53f6e54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tasks and Thread Pools]]></title>
            <link>https://medium.com/@jhaprincet/tasks-and-thread-pools-e28c3b00025b?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28c3b00025b</guid>
            <category><![CDATA[completablefuture]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 17:03:21 GMT</pubDate>
            <atom:updated>2023-07-25T09:54:52.178Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Engineer Java Concurrency — 6]]</p><ul><li><a href="#1b60"><strong>Callable</strong></a></li><li><a href="#8d56"><strong>Future</strong></a></li><li><a href="#a4c1"><strong>FutureTask</strong></a></li><li><a href="#05ec"><strong>Executors</strong></a></li><li><a href="#5d1c"><strong>How to use a thread pool</strong></a></li><li><a href="#6d60"><strong>Using Executors to control group of tasks</strong></a></li><li><a href="#13d2"><strong>Fork-Join technique</strong></a></li><li><a href="#4f11"><strong>Asynchronous Computation</strong></a></li><li><a href="#3c4d"><strong>CompletableFuture</strong></a></li><li><a href="#c327"><strong>Pipelining the processing of data in Asynchronous Computation</strong></a></li></ul><h3>Callable:</h3><p><em>Callable</em> interface in Java represents a functional interface whose single abstract method is a method that needs no arguments and returns a value and threatens to throw an Exception.</p><pre>// used to represent an asynchronous task<br>public interface Callable&lt;T&gt; {<br>    T call() throws Exception;<br>}</pre><p>So a lambda object can be created which implements the <em>Callable</em> functional interface that basically encapsulates a task which will return a value or which might end up in an exception.</p><p><em>Callable</em> is used to represent the asynchronous computation/ asynchronous task.</p><h3><strong>Future:</strong></h3><p><em>Future</em> interface in Java represents an interface that is related to an <em>asynchronous</em> computation. <em>Asynchronous</em> computations work on the idea of off-loading which means the thread <em>asker</em> that asks for an asynchronous operation to be performed does not get blocked but instead can continue its execution. The task that was off-loaded will either be handed over to another thread which does it or maintained in a queue ( for later execution). In either case the <em>asker</em> thread can continue to execute. The <em>asker</em> thread can later work with the value once it is ready.</p><pre>// represents the result of an asnychronous computation/task<br>interface Future&lt;T&gt; {<br>    T get() throws InterruptedException, ExecutionException;<br>    T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;<br>    boolean isCacelled();<br>    boolean isDone();<br>    void cancel(boolean mayInterrupt);<br>}</pre><p>So when an asker thread asks for a task to be performed asynchronously. It gets a <em>Future</em> object as a representation of the result of the computation.</p><p>We can see that the <em>Future</em> object must support the above methods.</p><ul><li><em>get</em> method: The <em>asker</em> thread that invokes the get method will wait until the result of the computation is obtained.</li><li><em>get</em> method with timeout: Timed Waiting for the result of the computation. May throw TimeoutException if result is not obtained within the timeout period.</li></ul><p>These methods may throw InterruptedException when the thread is interrupted during in an inactive state.</p><ul><li><em>isCancelled</em> method: checks whether the asynchronous computation was cancelled before during computation.</li><li><em>isDone</em> method: checks whether the asynchronous computation is completed.</li><li><em>cancel</em> method: can be used to cancel the asynchronous computation by passing a boolean indicator.</li></ul><p>JavaScript is a single threaded language and hence the async tasks are maintained in a queue and executed once the ONLY thread is available for executing instructions.</p><h3>FutureTask:</h3><p>A <em>FutureTask</em> interface in Java represents a <em>Future</em> and <em>Runnable</em>. A FutureTask accepts a <em>Callable</em> (an async task definition) as an argument into its constructor. It can be used to submit a task (<em>Runnable</em>) to a thread at the same time it can also be used to work with the result of async operation (<em>Future</em>).</p><pre>Callable&lt;Long&gt; asyncTask = () -&gt; {<br> // define async task<br>}<br><br>FutureTask&lt;Long&gt; asyncResult = new FutureTask&lt;&gt;(asyncTask);<br><br>new Thread(asyncResult).start(); // execute async operation in a separate thread<br><br>// continue working with the asker thread without blocking<br>// .....<br>// ....<br>// Now we really need the result<br>Long result = asyncResult.get(); // asker thread cannot continue execution till result is available</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCw5eY9HR1Wqz0fX0nwKMQ.png" /></figure><pre>import java.util.*;<br>import java.util.stream.*;<br>import java.util.function.*;<br>import java.util.concurrent.*;<br><br>public class MyClass {<br>    private static boolean isFactor(int num, int [] factors) {<br>        return Arrays.<br>        stream(factors).<br>        filter(factor -&gt; ((num % factor) == 0)).<br>        count() &gt;= 1;<br>    }<br>    <br>    public static void main(String args[]) throws Exception {<br>        <br>        // We will try to execute the below task asynchronously <br>        Callable&lt;Long&gt; computeSum = () -&gt; {<br>            System.out.println(&quot;ASYNC OPERATION EXECUTING &quot; + Thread.currentThread().getName());<br>            int start = 0;<br>            int end = 100000;<br>            int incrementAmount = 1;<br>            int [] factors = new int [] { 11, 5, 17 };<br>            <br>            // compute sum of all number below threshold divisible by one of the factors<br>            <br>            Long result = Stream.<br>            iterate(<br>                start,<br>                i -&gt; i &lt; end,<br>                i -&gt; i + incrementAmount<br>            ).filter(i -&gt; isFactor(i, factors)).<br>            reduce(0L, (Long previousResult, Integer currentVal) -&gt; previousResult + currentVal, Long::sum);<br>            return result;<br>        };<br>        <br>        // can be used to check if result is ready, what the result is ...etc of the async operation<br>        FutureTask asyncResult = new FutureTask&lt;&gt;(computeSum);<br>        <br>        Thread threadA = new Thread(asyncResult);<br>        threadA.setName(&quot;PRINCE ASYNC&quot;);<br>        threadA.start();<br>        System.out.println(&quot;MAIN THREAD NOT BLOCKED &quot; + Thread.currentThread().getName());<br>        System.out.println(&quot;Is Result Computed Yet &quot; + asyncResult.isDone());<br>        System.out.println(&quot;Is Result Computed Yet &quot; + asyncResult.isDone());<br>        System.out.println(&quot;Ensure Blocking of MAIN Thread until result is available &quot;);<br>        asyncResult.get(); // main thread waits for result from threadA<br>        System.out.println(&quot;Result &quot; + asyncResult.get());<br>    }<br>}</pre><h3><strong>Executors:</strong></h3><p><em>Executors</em> is a Java class that provides several useful utils which help in the creation of thread pools which manage group of tasks.</p><p>Some of the useful utils provided are:</p><ul><li><em>newCachedThreadPool</em>: Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache.</li><li><em>newFixedThreadPool</em>: Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, these tasks will wait in the queue until a thread is available.</li><li><em>newSingleThreadExecutor</em>: Creates a pool with a single thread which runs the submitted tasks sequentially.</li></ul><p>A thread can ask the thread pool to take care of the submitted task. The <em>asker</em> thread will get a Future object as a representation of the result.</p><pre>ExecutorService:<br><br>Future&lt;T&gt; submit(Callable&lt;T&gt; task);<br><br>instance method can be invoked on (a thread pool) ExecutorService,<br>the submitted async task will be managed by the thread pool.<br>the thread that submits task will get a Future object<br>  representing the result of async operation.<br><br><br>Future&lt;T&gt; submit(Runnable task);<br><br>instance method that can be invoked on ExecutorService, <br>the submitted async task will be managed by thread pool.<br>the thread that submits task will get a Future object<br>representing the result of async operation.<br>Since Runnable do not return anything,<br>the get method called on a Future object will return null.<br><br>Future&lt;T&gt; submit(Runnable task, T result);<br>instance method that can be invoked on ExecutorService, <br>the submitted async task will be managed by thread pool.<br>the thread that submits task will get a Future object<br>representing the result of async operation.<br>the second argument result will be returned by the get method on the Future object.</pre><h3><strong>How to use a thread pool:</strong></h3><ol><li>Create a thread pool using one of the suitable static methods.</li><li>Submit <em>Runnable</em>, <em>Callable</em> tasks to the thread pool.</li><li>Obtain the <em>Future</em> object as a representation of the result.</li><li>Call the <em>shutdown</em> method on the thread pool if no longer needed.</li></ol><h3><strong>Using Executors to control group of tasks:</strong></h3><p>Submitting N number of tasks to an executor service and then looping over the results could cause performance penalty.</p><pre>import java.util.concurrent.*;<br>import java.util.stream.*;<br>import java.util.*;<br><br>public class MyClass {<br>    public static void main(String args[]) throws Exception {<br>      ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        List&lt;Future&lt;Integer&gt;&gt; asyncResults = Stream.of(<br>            (Future&lt;Integer&gt;) executorCompletionService.submit(() -&gt; {<br>                return 10;<br>            }),<br>            (Future&lt;Integer&gt;) executorCompletionService.submit(() -&gt; {<br>                return 20;<br>            })<br>        ).collect(Collectors.toList());<br><br>        // iterator used internally to iterate<br>        for(Future asyncRes : asyncResults) {<br>            System.out.println(asyncRes.get());<br>        }<br>        executor.shutdown();<br>    }<br>}</pre><p>When the <em>asker</em> thread tries to work with the <em>Future</em> object and invokes its <em>get</em> method which is a blocking call, the <em>asker</em> thread cannot continue its execution until the result of task is completely available. This may lead to increased waiting time on the <em>asker</em> thread.</p><p><em>ExecutorCompletionService</em> on the other hand will solve the performance issue that could happen due to sequential blocking on result of async tasks by the <em>asker</em> thread. Instead of retrieving the results of the tasks in the sequential order which increases the waiting time, it retrieves the result of the operations in the order in which the results of the async tasks are available.</p><pre>import java.util.concurrent.*;<br>import java.util.stream.*;<br>import java.util.*;<br><br>public class MyClass {<br>    public static void main(String args[]) throws Exception {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        ExecutorCompletionService executorCompletionService = new ExecutorCompletionService(executorService);<br>        List&lt;Future&lt;Integer&gt;&gt; asyncResults = Stream.of(<br>            (Future&lt;Integer&gt;) executorCompletionService.submit(() -&gt; {<br>                return 10;<br>            }),<br>            (Future&lt;Integer&gt;) executorCompletionService.submit(() -&gt; {<br>                return 20;<br>            })<br>        ).collect(Collectors.toList());<br><br>        // iterator used internally to iterate<br>        for(Future asyncRes : asyncResults) {<br>            System.out.println(asyncRes.get());<br>        }<br>        executorService.shutdown();<br>    }<br>}</pre><p>There are special purpose instance methods available in the ExecutorService</p><ul><li><em>invokeAll</em> method: A blocking call that will only allow the invoking <em>asker</em> thread to continue execution once all the tasks are completed ( either cancelled or fulfilled or terminated due to exception ). The results are available in a <em>List</em> of <em>Future</em> objects.</li></ul><pre>List&lt;Future&lt;T&gt;&gt; invokeAll(Collection&lt;Callable&lt;T&gt;&gt; coll);</pre><pre>import java.util.concurrent.*;<br>import java.util.stream.*;<br>import java.util.*;<br><br>public class MyClass {<br>    public static void main(String args[]) throws Exception {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        List&lt;Callable&lt;Integer&gt;&gt; asyncTasks = Stream.of(<br>            (Callable&lt;Integer&gt;) () -&gt; {<br>                System.out.println(&quot;Hello&quot;);<br>                <br>                return 10;<br>            },<br>            (Callable&lt;Integer&gt;) () -&gt; {<br>                System.out.println(&quot;World&quot;);<br>                return 20;<br>            }<br>        ).collect(Collectors.toList());<br><br>        List&lt;Future&lt;Integer&gt;&gt; results = executorService.invokeAll(asyncTasks);<br>        for(Future&lt;Integer&gt; f: results) {<br>            System.out.println(f.get());<br>        }<br>        executorService.shutdown();<br>    }<br>}</pre><ul><li><em>invokeAny</em> method: A blocking call that will only allow the invoking <em>asker</em> thread to continue execution once one of the tasks has completed. All the tasks are executed but only the result of the earliest completed task is returned.</li></ul><pre>T invokeAny(Collection&lt;Callable&lt;T&gt;&gt; coll);</pre><pre>import java.util.concurrent.*;<br>import java.util.stream.*;<br>import java.util.*;<br><br>public class MyClass {<br>    public static void main(String args[]) throws Exception {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        List&lt;Callable&lt;Integer&gt;&gt; asyncTasks = Stream.of(<br>            (Callable&lt;Integer&gt;) () -&gt; {<br>                System.out.println(&quot;Hello&quot;);<br>                <br>                return 10;<br>            },<br>            (Callable&lt;Integer&gt;) () -&gt; {<br>                System.out.println(&quot;World&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                System.out.println(&quot;WTF&quot;);<br>                return 20;<br>            }<br>        ).collect(Collectors.toList());<br><br>        Integer temp = executorService.invokeAny(asyncTasks);<br>        System.out.println(temp);<br>        executorService.shutdown();<br>    }<br>}</pre><h3>The Fork-Join Technique:</h3><p>The idea of the technique is to divide and conquer the problem into several sub problems and use multiple threads to solve sub problems in parallel. The results can be combined for the sub problems. The divide step and combine step are recursive in nature.</p><p><em>RecursiveTask</em> class in Java represents a recursive task. The <em>compute</em> method is the definition of the recursive task. We can create sub tasks that are sub problems of the recursive task. We can ensure that the sub tasks are completed by calling the <em>invokeAll</em> method. Once the sub problems are solved, we can combine the result of the subtasks by calling the <em>join</em> method and using the result.</p><pre>   if problem size is small<br>       solve the problem // a thread solves the small enough problem<br>   else<br>     let a,b,c,d be the sub problems generated from the problem<br>     invokeAll(a, b, c, d); // recursively solve the sub problems, blocking<br>     return a.join() + b.join() + c.join() + d.join(); // combine the results</pre><p>Example: Perform a function on the numbers in a range [start, end) using the fork-join recursive technique.</p><pre>import java.util.function.*;<br>import java.util.concurrent.*;<br><br>// apply a function f on a range of int indices [s, e), combine the result using the binOp,<br>// the binOp should be a commutative operation since computations are parallel.<br>class MyAccumulator extends RecursiveTask&lt;Long&gt; {<br>    private int start;<br>    private int end;<br>    private Function&lt;Long, Long&gt; fn;<br>    private BiFunction&lt;Long, Long, Long&gt; binOp;<br>    private Supplier&lt;Long&gt; neutralElement;<br>    <br>   // [s, e) start included, end excluded <br>   public MyAccumulator(<br>              int s,<br>              int e,<br>              Function&lt;Long, Long&gt; f,<br>              BiFunction&lt;Long, Long, Long&gt; bOp,<br>              Supplier&lt;Long&gt; neutral<br>              ) {<br>       start = s;<br>       end = e;<br>       fn = f;<br>       binOp = bOp;<br>       neutralElement = neutral;<br>   }<br>    <br>   public Long compute() {<br>        if(start == end) {<br>           return neutralElement.get();<br>        }<br>        else if (start == (end - 1)) {<br>           return fn.apply(Long.valueOf(start));<br>        } else {<br>            int mid = start + ( end - 1 - start) / 2;<br>            MyAccumulator leftHalf = new MyAccumulator(start, mid + 1, fn, binOp, neutralElement); // fork, recursive divide step<br>            MyAccumulator rightHalf = new MyAccumulator(mid + 1, end, fn, binOp, neutralElement);  // fork, recursive divide step<br>            invokeAll(leftHalf, rightHalf);<br>            return binOp.apply(leftHalf.join(), rightHalf.join()); // join, join, recursive combine step<br>        }<br>   }<br>}</pre><pre>public class MyClass {<br>    public static void main(String [] args) {<br>        ForkJoinPool pool = new ForkJoinPool();<br>        <br>        MyAccumulator addSqrtNumbers = new MyAccumulator(1, 1001, (x) -&gt; {<br>            return  Long.valueOf((long) Math.sqrt(x));<br>        }, Long::sum, () -&gt; 0L);<br>        <br>        pool.invoke(addSqrtNumbers);<br>        System.out.println(&quot;addSqrtNumbers &quot; +  addSqrtNumbers.join());<br>        <br>        MyAccumulator addEvenNumbers = new MyAccumulator(1, 1001, (x) -&gt; {<br>            return ((x % 2) == 0) ? x : 0;<br>        }, Long::sum, () -&gt; 0L);<br>        <br>        pool.invoke(addEvenNumbers);<br>        System.out.println(&quot;addEvenNumbers &quot; +  addEvenNumbers.join());<br>        <br>    }<br>}</pre><h3><strong>Asynchronous Computation:</strong></h3><p>Until now, we have seen how to perform a task asynchronously where the asker thread which asks for some async task to be performed can continue its execution without blocking. The asker thread would get a <em>Future</em> object which was a representation of the result of the computation. This technique required that the <em>asker</em> thread needs to determine when an async task is completed and its result is available for use.</p><p>Instead of this, we can simply register callbacks that will execute once the result is available. This way the <em>asker</em> thread can be care free in regards to whether the async computation was successful or not, when will the result of the async task be available. The callbacks encapsulate the logic that should execute once the result becomes available, or when an exception occurs etc.</p><h3>CompletableFuture:</h3><p>A <em>CompletableFuture</em> is used to accomplish this technique of asynchronous programming where we simply register callbacks that will execute once the result of the asynchronous operation is available.</p><p><em>supplyAsync</em> static method can be used to schedule async tasks. It accepts a Supplier lambda and returns a <em>CompletableFuture</em> that represents the result of async task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOWY6DZD8URwjnZH9LEXZQ.png" /></figure><p><em>thenAccept</em> instance method accepts a <em>Consumer&lt;? super T&gt;</em> which consumes the result of asynchronous computation, once the result is available. The <em>Consumer&lt;? super T&gt;</em> lambda object is the callback registered on the <em>CompletableFuture</em>.</p><pre>import java.util.function.*;<br>import java.util.concurrent.*;<br><br>public class MyClass {<br>    public static void main(String [] args) throws Exception {<br>        ExecutorService executor = Executors.newFixedThreadPool(4);<br>        <br>        // create an async task and register callbacks that should run when results are ready!!<br>        CompletableFuture.supplyAsync(() -&gt; {<br>            long res = 0;<br>            for(int i = 0; i &lt; 30000; ++i) {<br>                int x = (int) (i * Math.random());<br>                res = res + x;<br>            }<br>   <br>            return res;<br>        }, executor).thenAccept((Long value) -&gt; {<br>            System.out.println(&quot;Result is ready &quot; + value);<br>        });<br>        <br>        // continue care free about the tasks<br>        System.out.println(&quot;Hello World&quot;);<br>        System.out.println(&quot;Bye World&quot;);<br>        <br>        // make sure all tasks are completed before exiting main thread<br>        executor.shutdown();<br>    }<br>}</pre><p>If you want to execute a callback once the async task has terminated due to completion or exception, use the <em>whenComplete</em> method to register the callback.</p><pre>// register a callback on termination of async task<br>asyncResult.whenComplete((res, error) -&gt; {<br>   if(error != null) {<br>        // execute some logic to process error<br>   } else {<br>        // execute some logic to process res<br>   }<br>});</pre><p>Some useful methods in <em>CompletableFuture</em>:</p><ul><li><em>thenApply</em>: once the result T is available, the callback lambda is used to schedule another async task that will transform T to U. The async result is another <em>Future </em>( CompletableFuture&lt;U&gt;).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sB82dUuyYLLBW2_uO_Ge7A.png" /></figure><ul><li><em>thenAccept</em>: once the result T is available, then callback lambda is used to schedule another async task that will operate on T but not return any value. The async result is another <em>Future</em>. (CompletableFuture&lt;Void&gt;)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xc6FCJKXlxvvNq4wxPzs5g.png" /></figure><ul><li>thenCompose: once the result T is available, the callback lambda is used to execute a logic that consumes result, another async task is scheduled and its <em>CompletableFuture</em> is returned.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGK9dbUkgk9FqOkV5RcUbA.png" /></figure><h3><strong>Pipelining the processing of data in Asynchronous Computation:</strong></h3><p>The technique of pipelining is basically chaining the async results to further create more async tasks with the result once the result is available.</p><pre>CompletableFuture.supplyAsync(lambdaA).<br>.thenApply(lambdaB)<br>.thenApply(lambdaC)<br>.whenComplete(lambdaD);</pre><p>Of course the objects that represent the async tasks are created one after the other in succession but the registered callbacks execute once the required results are available and so on.</p><pre>CompletableFuture.supplyAsync(lambdaA).<br>.thenApply(lambdaB)<br>.thenCompose(lambdaC)<br>.thenCompose(lambdaD)<br>.thenAccept(lambdaD)<br>.whenComplete(lambdaE);</pre><p>There are useful methods that help in working with async tasks.</p><pre>// thenCompose<br>asyncResultB = asyncResultA.thenCompose((result) -&gt; {<br>   // .... use the result<br>   // System.out.println(&quot;Result of async task A &quot; + result);<br>   CompletableFuture&lt;Long&gt; anotherAsyncResult = CompletableFuture.supplyAsync( <br>    () -&gt; {<br>       Long anotherResult = result + 240;<br>       // ....<br>       return anotherResult;<br>    }<br>   );<br>   return anotherAsyncResult;<br>});</pre><pre>// thenCombine<br>CompletableFuture&lt;String&gt; asyncResultC = asyncResultA.thenCombine(asyncResultB,<br>    (resA, resB) -&gt; {<br>      return resA.toString() + &quot;  &quot; + resB.toString();<br> });</pre><pre>// thenAcceptBoth<br>CompletableFuture&lt;Void&gt; asyncResultC = asyncResultA.thenAcceptBoth(asyncResultB, <br>(resA, resB) -&gt; {<br>      System.out.println(resA.toString() + &quot;  &quot; + resB.toString());<br>      return;<br> });</pre><pre>// runAfterBoth<br>CompletableFuture&lt;Void&gt; asyncResultC = asyncResultA.runAfterBoth(asyncResultB, () -&gt; {<br>     // Runnable logic that should execute when both async tasks are completed<br>});</pre><pre>// applyToEither<br>// both asyncResult should evaluated to a result of compatible type<br>CompletableFuture&lt;Long&gt; asyncResultC = asyncResultA.applyToEither(asyncResultB, <br>  (val) -&gt; {<br>     // val could be result of async taskA or async taskB<br>     return val + 500L; // callback returns another value<br>}); // applyToEither returns another async result</pre><pre>// static allOf<br>CompletableFuture&lt;Void&gt; asyncResultAll = CompletableFuture.allOf(<br>asyncResultA, asyncResultB, asyncResultC); //variable number of parameters</pre><pre>// static anyOf<br>CompletableFuture&lt;Void&gt; asyncResultAny = CompletableFuture.anyOf(<br>asyncResultA, asyncResultB, asyncResultC); //variable number of parameters</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28c3b00025b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Safe Collections]]></title>
            <link>https://medium.com/@jhaprincet/thread-safe-collections-811c109de05f?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/811c109de05f</guid>
            <category><![CDATA[copy-on-write]]></category>
            <category><![CDATA[concurrentmodification]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[thread-safety]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 08:51:57 GMT</pubDate>
            <atom:updated>2023-01-11T09:11:28.658Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Engineer Java Concurrency — 5]]</p><ul><li><a href="#d973"><strong>BlockingQueue</strong></a></li><li><a href="#e9ca"><strong>Concurrent Collections</strong></a></li><li><a href="#23b6"><strong>ConcurrentModificationException</strong></a></li><li><a href="#136d"><strong>Thread Safe Data Structure vs Thread Safe Code</strong></a></li><li><a href="#ee2a"><strong>Bulk operation on concurrent hash maps</strong></a></li><li><a href="#b274"><strong>Concurrent Set Views</strong></a></li><li><a href="#93ee"><strong>Copy On Write Collections</strong></a></li><li><a href="#6a08"><strong>Older Thread Safe Collections</strong></a></li></ul><h3><strong>Thread Safe Collections:</strong></h3><p>Operating on objects that contain a collection of values in a consistent fashion requires ensuring that the read-write operations performed on these objects should be thread safe.</p><p>Some of the thread safe collections provided by Java include BlockingQueue, ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentLinkedQueue …etc.</p><h3>BlockingQueue:</h3><p>Most of the problems in multi threading can be represented using the <em>Producer-Consumer</em> problem. The producer thread inserts request into a queue. The consumer thread removes the request from the queue and processes the request.</p><p>The blocking queue is a Java interface used to represent collections that represent a queue which can cause a conditional wait on a thread that tries to insert object into a filled queue, or on a thread that tries to remove object from an empty queue.</p><p>Object pools of fixed sizes are usually implemented using the blocking queue. There can only be a limited number of objects in the pool. <br>The threads that need the object (Consumer thread) can <em>take</em> it from the object pool when an object is available otherwise the threads should wait in a wait set until a notification is received indicating that an object is available in the object pool. Of course the notification should be sent to all the threads that are waiting on the condition variable for the notification whenever a thread does <em>put</em> the object back (Producer thread) to the pool when it is done using it.</p><p>Thread pool executors use the blocking queue in a similar way where the tasks that need to be executed are maintained in a blocking queue. <br>The Producer threads can submit tasks to the thread pool that are maintained in the blocking queue.<br>The (Consumer) worker thread that can <em>take</em>/pick one task from the queue and run the task. <br>The blocking queue is mainly for the Consumers (worker threads in the thread pool). The worker threads can wait in the wait set for new tasks to become available on the queue, they will be automatically woken up.</p><p>Synchronization is needed in the implementation of Blocking Queue and hence the use of <em>Locks</em> and <em>Conditional Variables</em> are obvious in the implementation details of the Blocking Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ropChyM_D_bhcYi3f7ZEGA.png" /></figure><p>There are several methods that can be used on a Blocking Queue grouped logically according to the return values or according to how thread behaves when the method is called.</p><p>The <em>add</em>, <em>remove</em>, <em>element</em> methods of the Blocking Queue interface intend to represent operations that would throw exception when an awkward situation occurs like inserting in a full queue or removing element from an empty queue or accessing the first element in an empty queue.</p><p>The <em>offer</em>, <em>poll</em>, <em>peek</em> methods of the Blocking Queue interface intend to represent methods that return special values in case an awkward situation occurs like like inserting in a full queue or removing element from an empty queue or accessing the first element in an empty queue.</p><p>The <em>put</em>, <em>take</em> methods of the Blocking Queue interface intend to represent methods that represent critical sections of code that are synchronized using a <em>Lock</em> object and contain conditional variables associated with conditions like queue must not be empty when removing from an empty queue or queue must not be full when inserting into a full queue. Note that the conditional variables will ensure that the thread must release the Lock object and must wait in a wait set on the condition variable in such scenarios.</p><p>Note that the Java docs represent these methods under the <em>blocks</em> column, when in fact the threads could be in WAITING state ( waiting for notification on a conditional variable in a wait set) Or in the BLOCKED state ( competing to acquire a lock object ).</p><p><em>LinkedBlockingQueue</em> is a type that implements the BlockingQueue interface. The <em>LinkedBlockingQueue</em> by default does not specify an upper limit on the capacity but it can optionally be specified.</p><p><em>ArrayBlockingQueue</em> is a type that implements the <em>BlockingQueue</em> interface. The <em>ArrayBlockingQueue</em> needs a required argument that specifies the upper limit on the capacity of the <em>BlockingQueue</em>, optionally fairness could be provided (not recommended).</p><p><em>PriorityBlockingQueue</em> is a type that implements the <em>BlockingQueue</em> interface. Elements are removed in the order of priority. There is no upper limit specified on the capacity of the queue.</p><p><em>DelayQueue</em> is a type that implements the <em>BlockingQueue</em> interface. Elements of the <em>DelayQueue</em> belong to a type that implements the <em>Delayed</em> interface, <em>Comparable&lt;Delayed&gt;</em> interface. Basically elements in the <em>DelayQueue</em> are prioritised based on how much time has elapsed since the expiry of the delay on the element. The more the time has elapsed since the expiry of the delay the higher will be the priority.</p><pre>class Element implements Delayed {<br>   //.....<br>    @Override<br>    public long getDelay(TimeUnit unit) {}<br>    @Override<br>    public int compareTo(Delayed other) {}<br>}<br><br>// ...<br>DelayQueue&lt;Element&gt; queue;</pre><p><em>LinkedTransferQueue</em> is a type that implements the <em>BlockingQueue</em> interface. <em>LinkedTransferQueue </em>also implements<em> the TransferQueue </em>interface<em>. </em>A <em>producer</em> thread which tries to transfer data using the queue blocks (<em>BLOCKED OR WAITING </em>thread state) until a <em>consumer</em> thread is ready to receive data.</p><pre>// producer thread that executes this line blocks ( BLOCKED or WAITING state)<br>queue.transfer(value);</pre><h3>Concurrent Collections:</h3><p>The java.util.concurrent package contains concurrent collections such as <em>ConcurrentHashMap</em>, <em>ConcurrentSkipList</em>, <em>ConcurrentSkipListSet, ConcurrentLikedQueue.</em></p><p>These collections are the thread safe equivalent of maps, sorted sets ( elements are ordered based on natural ordering of how elements compare), queues in java.util package.</p><p>We know that a collection can contain several values. Instead of Locking on the entire collection object the Locks are made over code logic that accesses the objects that are finer implementation details of the collection.<br>Example: instead of Locking on an object of map, the lock may be applied using a <em>bucket</em> in the case of a hash-map.</p><p>Locking on finer implementation objects by considering the performance also decreases the contention by allowing multiple threads that do not necessarily obstruct each other to run concurrently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*V0_OLp6dCCTTtL4m40bYOw.png" /><figcaption>Locking on Collection Object: poor performance and high contention for lock on collection object. several threads block for the lock. only one executes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbOrgZzJOgptw64lQiTLMQ.png" /><figcaption>Finer Level of Locking: high performance. multiple threads can continue without blocking if they can operate independently</figcaption></figure><p>Some of these Concurrent Collections use highly researched complex lock-free algorithms as well.</p><p>The Concurrent Collections return <em>Weakly Consistent Iterators</em>. They may not be able to reflect all the changes that were made to the Concurrent Collection after the iterator was created. On the other hand these iterators do NOT throw a <em>ConcurrentModificationException</em> either.</p><h3><strong>ConcurrentModificationException:</strong></h3><p>Iterator objects can be created connected to a collection in java.util package, the iterator object can encapsulate the logic to traverse further/ visiting an element of the collection as well as instance variables that could keep track of the position etc.</p><p>However since collections in the java.util package are not thread safe, any modification to the collection that occurs after an iterator object is initialised in a way invalidates the iterator and hence further use of iterator will throw a <em>ConcurrentModificationException</em> in Java.</p><p>The <em>ConcurrentModificationException</em> is not a <em>checked</em> exception. It is an <em>unchecked</em> exception. In fact is a <em>RuntimeException</em> which indicates that if your program ends up in a <em>ConcurrentModificationException</em>, your program contains bugs which should be fixed in the code. In a well written code the <em>ConcurrentModificationException</em> should not occur in the first place.</p><p>Note that <em>ConcurrentModificationException </em>can also occur in a single threaded application.</p><p>The below program <em>might</em> end up in a <em>ConcurrentModificationException. </em>If the <em>remove</em> method is called on collection after iterator is initialised ( leads to invalidation of the <em>iterator</em>) and the iterator is traversing the container, the <em>next</em>() method will throw <em>ConcurrentModificationException </em>since the<em> next() </em>method is called on an invalidated iterator.</p><pre>import java.util.*;<br>import java.util.stream.*;<br><br><br>public class MyClass {<br>    public static void main(String args[]) {<br>        List&lt;Integer&gt; primes = Arrays.stream(new Integer[] {5, 11, 17, 23, 31, 37, 101}).collect(Collectors.toList());<br>        <br>        Thread threadA = new Thread(() -&gt; {<br>            long total = 0;<br>           // create iterator object at the current state of primes collection<br>           Iterator&lt;Integer&gt; iterator = primes.iterator();<br>           // iterate using iterator<br>           while(iterator.hasNext()) {<br>               total = total + iterator.next();<br>           }<br>           System.out.println(&quot;Total &quot; + total);<br>        });<br>        <br>        Thread threadB = new Thread(() -&gt; {<br>            // keep modifying collection<br>            primes.remove(0);<br>            primes.remove(0);<br>            primes.remove(0);<br>        });<br>        <br>        threadA.start();<br>        threadB.start();<br>    }<br>}</pre><p>The following program will surely end up in a <em>ConcurrentModificationException </em>since we are invalidating the iterator by modifying the collection after the iterator is initialised. Using the iterator after invalidation causes the exception.</p><pre>import java.util.*;<br>import java.util.stream.*;<br><br><br>public class MyClass {<br>    public static void main(String args[]) {<br>        List&lt;Integer&gt; primes = Arrays.stream(new Integer[] {5, 11, 17, 23, 31, 37, 101}).collect(Collectors.toList());<br>        Iterator iterator = primes.iterator();<br>        // modify collection after iterator is created<br>        primes.remove(0);<br>        iterator.next();<br>    }<br>}</pre><h3><strong>Thread Safe Data Structure vs Thread Safe Code:</strong></h3><p>Updating a <em>ConcurrentHashMap</em> is a tricky problem. The below code is incorrect.</p><pre>ConcurrentHashMap&lt;String, Long&gt; frequency = new ConcurrentHashMap&lt;&gt;();<br>String key = &quot;Hello World&quot;;<br><br>Long count = frequency.get(key); // ....(a)<br>Long updatedCount = ((count == null) ? 1 : (1 + count));<br>frequency.put(key, updatedCount); // ....(b)</pre><p>The reason is that even though the <em>ConcurrentHashMap</em> is a thread safe data structure which means that the <em>get</em> method and <em>put</em> method will never corrupt the data structure, it does not provide <em>atomicity</em>. It means that the collection could be modified between the line(a) and line(b) by some other Thread threadB and hence the value updated against the key may not replace <em>count</em> with <em>updatedCount</em> correctly.</p><pre>thread A<br>COUNT = 5<br>UPDATED_COUNT = 6<br><br>thread B<br>updates count to 7<br><br>thread A <br>updates count to 6<br><br>// ... the updates made by thread B are overwritten</pre><p>Thread Safe Data Structures guarantee that the operations allowed on them will not corrupt the state of the data structure like invalid pointers, circular references, missing nodes …etc even when multiple threads try to operate on shared data.</p><p>Thread Safe Code is the code whose execution behaves correctly irrespective of the shared nature of data being operated upon by several threads.</p><p>Note that even though we are using a thread safe data structure the lines of code that we are executing are not really thread safe due to lack of <em>atomicity</em>. The intended behaviour of the above code requires <em>atomicity</em>.</p><p>The <em>replace</em> method in <em>ConcurrentHashMap</em> tries to replace a value by an updatedValue and returns a boolean indication of whether the operation was successful. The method guarantees <em>atomicity</em>. We can repeatedly try to replace the value in a loop until the operation succeeds. Overall the code is thread safe. Even if another thread updates the value during an iteration, the code logic will ensure that in the next iteration the update will be attempted with respect to the latest value.</p><pre>Long value;<br>Long updatedValue;<br><br>do {<br>     value = frequency.get(key);<br>     updatedValue = ((value == null) ? 1 : 1 + value);<br>} while(!frequency.replace(key, value, updatedValue);</pre><pre>thread A<br>COUNT = 5<br>UPDATED_COUNT = 6<br><br>// assume thread B modifies the value<br>thread B<br>updates value to 7<br><br>thread A <br>frequency.replace(key, 5, 6); // fails since current value is 7<br><br>thread A<br>next iteration<br>COUNT = 7<br>UPDATED_COUNT = 8<br><br>// assume no other thread changes count<br><br>frequency.replace(key, 7, 8); // succeeds since current value is indeed 7<br></pre><p>Another approach to solving the problem is to change the type of value. The idea behind the approach is simple, the value corresponding to a key is an AtomicLong and hence we can rely on the atomic update features provided by the Library</p><pre>ConcurrentHashMap&lt;String, AtomicLong&gt; frequency = new ConcurrentHashMap&lt;&gt;();<br>String key = &quot;Hello World&quot;;<br>frequency.putIfAbsent(key, new AtomicLong()); <br>// only added by a thread if no AtomicLong present against key<br>frequency.get(key).incrementAndGet(); <br>// ensures thread safe update of value wrapped inside AtomicLong type</pre><h3><strong>Bulk operation on concurrent hash maps:</strong></h3><p>The concurrent hash maps in Java currently use the parallel <strong>ForkJoin</strong> Framework to recursively divide the bulk operation into several subtasks and combines the result. Even though the bulk operation works in parallel it is possible that the collection could be modified during the execution of bulk operation. ConcurrentHashMaps are unordered hence the element that will be returned is not guaranteed. ConcurrentHashMaps rely on <em>null</em> as a special value hence it is not allowed to store <em>null</em> values in the map.</p><p>The bulk operations also accepts a parallelism threshold. The lower the value of the threshold the higher will be the amount of parallelism.</p><p>The bulk operations that could be performed on the concurrent hash maps consists of:</p><p>1. <em>searchKeys</em>: apply a function F to each key until a key K is found that returns non null result when F is applied to it. The return value of function F is returned.</p><pre>// Lambda object is used for specifiying the function<br>// find a key which is greater than 500.<br>myMap.searchKeys(threshold, (key) -&gt; {<br>     return key.length() &gt; 10 : key : null;<br>});</pre><p>2. <em>searchValues</em>: apply a function F to each value until a value V is found that returns non null result when F is applied on it. The return value of function F is returned.</p><pre>myMap.searchValues(threshold, (value) -&gt; {<br>     return value &lt; 300 ? value : null;<br>});</pre><p>3. <em>search</em>: apply a function F to each key-value until a key-value is found that returns non-null result when F is applied on it. The return value of function F is returned.</p><pre>myMap.search(threshold, (key, value) -&gt; {<br>     if(key.length() &gt; 10 &amp;&amp; value &gt; 20) {<br>         return String.format(&quot;%s-%s&quot;, key, value);<br>     }<br>     return null;<br>});</pre><p>4. <em>searchEntries</em>: apply a function F to each entry (of the type Map.Entry ) of the map until an entry is found that returns non-null result when F is applied on it. The return value of function F is returned.</p><pre>myMap.searchEntries(threshold, (entry) -&gt; {<br>   String key = entry.getKey();<br>   Integer value = entry.getValue();<br>   if(key.length() &gt; 10 &amp;&amp; value &gt; 20) {<br>         return String.format(&quot;%s-%s&quot;, key, value);<br>     }<br>     return null;<br>});</pre><p>5. <em>reduceKeys</em>: apply an accumulator function F that performs a commutative operation on the key.</p><pre>// smallest key<br>myMap.reduceKeys(threshold, (previousResult, currentKey) -&gt; {<br>   return ((previousResult.compareTo(currentKey) &lt; 0) ? previousResult : currentKey);<br>});</pre><p>6. <em>reduceValues</em>: apply an accumulator function F that performs a commutative operation on the value</p><pre>myMap.reduceValues(threshold, (previousResult, currentValue) -&gt; {<br>     return currentValue + previousResult;<br>});</pre><p>7. <em>reduce</em>: applies a transformer lambda to the key-value to obtain a transformed value as its result which is passed as input into another lambda which is an accumulator lambda that performs a commutative operation.</p><pre>myMap.reduce(threshold, (key, value) -&gt; {<br>    // returns a transformed value<br>     if(key.length() &gt; 10) {<br>         return value;<br>     }<br>     return 0;<br>}, (previousResult, transformedInput) -&gt; {<br>        // return the result of accumulation<br>        return previousResult + transformedInput;<br>}); </pre><p>8. <em>reduceEntries</em>: applies an accumulator lambda that performs a commutative operation on entry ( of the type Map.Entry ).</p><pre>// Reduction Operation to accumulate the smallest entry<br>// smallest entry: smallest key, if keys are equal, smallest value.<br>// if values are also equal one of these smallest entries<br>myMap.reduceEntries(threshold, (entryA, entryB) -&gt; {<br>     if(entryA.getKey().length() &lt; entryB.getKey().length()) {<br>         return entryA;<br>     } else if(entryB.getKey().length() &lt; entryA.getKey().length()) {<br>        return entryB;<br>     } else if(entryA.getValue() &lt; entryB.getValue()) {<br>        return entryA;<br>     } else return entryB;<br>});</pre><p>9. <em>forEachKeys</em>: applies a function F on each key of the concurrent hash map.</p><pre>myMap.forEachKeys(threshold, (key) -&gt; {<br>     System.out.println(&quot;Key &quot; + key);<br>});</pre><p>10. <em>forEachValues</em>: applies a function F on each value of the concurrent hash map.</p><pre>myMap.forEachValues(threshold, (value) -&gt; {<br>     System.out.println(&quot;Value &quot;+ value);<br>});</pre><p>11. <em>forEach</em>: applies a function F on each key-value of the collection.</p><pre>myMap.forEach(threshold, (key, value) -&gt; {<br>    System.out.println(&quot;Key &quot; + key + &quot; Value &quot; + value);<br>});</pre><p>12. <em>forEachEntry</em>: applies a function F on each entry of the collection.</p><pre>myMap.forEachEntry(threshold, (entry) -&gt; {<br>     System.out.println(&quot;Key &quot; + entry.getKey() + &quot; Value &quot; + entry.getValue());<br>});</pre><p>Most of these methods also accept a transformer lambda which first transforms to obtain a suitable value ( like pre processing ) which is further passed into the actual accumulator which combines using the intended operation.</p><pre>// assume keys are of type String, find max length of the contained key<br>Integer maxLength = myMap.reduceKeys(threshold, String::length, Integer::maxValue);</pre><h3>Concurrent Set Views:</h3><p>A view can be created using the <em>ConcurrentHashMap</em> Data Structure which returns a type that implements the <em>Set</em> interface. The reason for creating such a view is that there is no direct <em>ConcurrentHashSet</em> Data Structure which supports thread safe set operations. Thus to achieve a concurrent thread safe view of a set we can use a wrapper projection provided by the Java Library.</p><p>The static method <em>newKeySet</em> creates a <em>Set</em> projection from a new <em>ConcurrentHashMap</em> Collection. ConcurrentHashMap&lt;K, Boolean&gt; where K is the key type will be operated upon as if it were some Concurrent <em>Set</em>. The values stored in the map are simply Boolean.TRUE values and these values do not have a major significance.</p><pre>// creates a new ConcurrentHashMap and wraps it as a Set<br>Set&lt;String&gt; words = ConcurrentHashMap.&lt;String&gt;newKeySet();<br>words.add(&quot;Hello&quot;); // concurrently able to use set in a thread safe manner</pre><p>If you want to create a concurrent <em>Set</em> projection from an existing <em>ConcurrentHashMap</em>, this is also supported. Use the <em>keySet</em> instance method to create a <em>Set</em> projection over a map.</p><p>The <em>remove</em> method on the <em>Set</em> projection for a key ends up removing the key, value pair from the map.<br>The <em>add</em> method on the <em>Set</em> projection for a key ends up adding a key with the default value provided.</p><pre>// concurrent hash map wordFrequency<br>Set&lt;String&gt; words = wordFrequency.keySet(1);<br>words.add(&quot;PPPPPWKSMS&quot;); <br>// if it is not already present in the map<br>// add will put(key, 1) into the supporting map<br><br>words.remove(&quot;Prince&quot;);<br>// if key were already present in the map,<br>// remove will remove the key value from the corresponding supporting map<br><br></pre><h3><strong>Copy On Write Collections:</strong></h3><p>A Copy On Write Collection is the one where the internal data structure is copied freshly each time a mutator method is called on it. The newer snapshot will replace the older one overall.</p><p>For example: calling the <em>add</em> method on a <em>CopyOnWriteArrayList</em> Data structure will end up modifying the data structure by reallocating an array of N + 1 number of elements. <br>The reason is simple, when an iterator is created on the Data Structure the iterator object will remember the <em>snapshot</em> array that was available on the <em>CopyOnWriteArrayList</em> at the time of the creation of the iterator.<br>So even if the <em>add</em> method later changes the internal allocated array the iterator will still continue using the older snapshot memory.</p><pre>import java.util.*;<br>import java.util.concurrent.*;<br><br>public class MyClass {<br>    public static void main(String args[]) {<br>        <br>      CopyOnWriteArrayList&lt;Integer&gt; myCowList = new CopyOnWriteArrayList(Arrays.asList(20, 30, 40, 50));<br>      // .... (a)<br>      Iterator&lt;Integer&gt; iterA = myCowList.iterator();<br>      // .... (b)<br>      myCowList.add(200);<br>      // .... (c)<br>      Iterator&lt;Integer&gt; iterB = myCowList.iterator();<br>      // ....(d)<br>      myCowList.set(0, 321);<br>      // ...(e)<br>      <br>      while(iterA.hasNext()) {<br>          System.out.println(iterA.next());<br>      }<br>      System.out.println(&quot;&quot;);<br>      <br>      while(iterB.hasNext()) {<br>          System.out.println(iterB.next());<br>      }<br>      System.out.println(&quot;&quot;);<br>      <br>      for(int x: myCowList) {<br>          System.out.println(x);<br>      }<br>      System.out.println(&quot;&quot;);<br>    }<br>}<br><br>/****<br>OUTPUT:<br> <br>20<br>30<br>40<br>50<br><br>20<br>30<br>40<br>50<br>200<br><br>321<br>30<br>40<br>50<br>200<br><br>**/</pre><p>Let us understand the output of the program</p><p>Line (a), a thread safe <em>CopyOnWrtieArrayList</em> is initialised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHYZiF3zcMwFhvPhkAfSWQ.png" /></figure><p>Line (b), an <em>iterator</em> iterA is created from the <em>CopyOnWrtieArrayList</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ai_8qUsCLhYPRG3BUx8Dyg.png" /></figure><p>Line ( c ), the <em>add</em> method tries to update the snapshot of the <em>CopyOnWrtieArrayList</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6BL9JZAXCwlDtqsI3L7Zw.png" /></figure><p>Line (d), an <em>iterator</em> iterB is created from the <em>CopyOnWrtieArrayList</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6i-PuE87rQGK3jhJ61vZQ.png" /></figure><p>Line (e) , the mutator <em>set</em> method is invoked on the <em>CopyOnWrtieArrayList</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEQ6LcflVFSIYF_NCz0cqQ.png" /></figure><p>Note that there are no concurrent modification exceptions in the Copy On Write Collections due to the fact that the iterator works on a snapshot of the data structure which is available as the current snapshot at the time of creation of the iterator.</p><p>Also note that the collection is thread safe since mutator methods change the internal state of the data structures by locking which ensures <em>mutual exclusion</em>.</p><p><em>CopyOnWriteArrayList</em> and <em>CopyOnWriteArraySet</em> are some of the Copy On Write Collections.</p><h3><strong>Older Thread Safe Collections:</strong></h3><p>Any collection can be wrapped in a <em>synchronized wrapper</em> type which performs the operations on the wrapped typed in a synchronized fashion by providing mutual exclusion with the use of Locks. In order to iterate over the synchronized collection you will still need to perform client side locking to ensure mutual exclusion between the reader thread and any other possible write threads.</p><pre><br>// returns a wrapper type which uses Locks to ensure thread safety<br>List&lt;Integer&gt; syncArrList = Collections.synchronizedList(new ArrayList&lt;&gt;());<br><br>// returns a wrapper type which uses Locks to ensure thread safety<br>Map&lt;String, Integer&gt; syncMap = Collections.synchronizedMap(new HashMap&lt;&gt;());<br><br>// programmer must use the intrinsic lock associated with syncMap object<br>// to ensure thread safety when using iterator object on collection<br>synchronized(syncMap) {<br>    for(String temp: syncMap.keySet()) {<br>      System.out.println(temp);<br>    }<br>}</pre><p>Of course the <em>synchronization wrapper </em>may not be optimal in terms of performance.</p><p>Concurrent Collections could be an improvement over <em>synchronization wrapper</em> if your use case fits either of them.</p><p>The collections like <em>Vector</em> and <em>Hashtable</em> in Java are thread safe collections whose use case is similar to ArrayList and HashMap that are not thread safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811c109de05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronization Continued]]></title>
            <link>https://medium.com/@jhaprincet/synchronization-continued-b6239a2a3c0d?source=rss-bf70386c4fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6239a2a3c0d</guid>
            <category><![CDATA[volatile]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[threadlocal]]></category>
            <category><![CDATA[java-concurrency]]></category>
            <dc:creator><![CDATA[Prince Jha]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 09:23:59 GMT</pubDate>
            <atom:updated>2022-12-16T10:34:25.501Z</atom:updated>
            <content:encoded><![CDATA[<p>[[Engineer Java Concurrency — 4]]</p><ul><li><a href="#0088"><strong>Monitor</strong></a></li><li><a href="#aaec"><strong>volatile keyword</strong></a></li><li><a href="#c8cb"><strong>final keyword</strong></a></li><li><a href="#1811"><strong>atomicity</strong></a></li><li><a href="#6f38"><strong>deadlocks</strong></a></li><li><a href="#928b"><strong>thread local variables</strong></a></li></ul><h3>The Monitor concept:</h3><ul><li>All fields of the object should be marked private.</li><li>Every object should have an associated lock.</li><li>All instance methods of the class should should be locked using the lock associated with the object.</li><li>The lock can have any number of condition variables associated with it.</li></ul><p>Basically the idea of the concept of monitors was to ensure that the state of the object can only be operated upon using the methods and we can ensure synchronization by considering all the methods as critical section of code that needs to protected by the usage of the lock object associated with the object.</p><p>Java did not adapt the monitor concept completely and only adapted it partially. The idea of associating a dedicated lock object to each Java object to help in synchronization is similar to the monitor concept.</p><p>The intrinsic lock associated with Java object can only have one intrinsic condition variable associated to it. The concept of monitors does not limit on the number of condition variables associated with the lock object.</p><p>The concept of monitors expects fields to be private so that synchronized code can manipulate the state of the object. Java does not enforce this rule.</p><p>The concept of monitors expects that all the instance methods should be synchronized using the associated lock object. Java does not enforce this rule.</p><p>In the concept of monitors, the intrinsic lock must be made available to the clients. In Java, the intrinsic lock object is managed internally and not exposed to the user.</p><p>Per Brinch Hansen, the creator of the concept of monitors, was not happy about the insecure parallelism offered by Java.</p><h3>The volatile keyword:</h3><p>Since accessing main memory is slower than accessing the values in registers or cache, it is possible that threads temporarily operate on the cached value before finally writing the value to the main memory. In such cases even when the threadA has changed the value of a field F, the threadB that tries to operate on the field F may not be notice the changes made by threadA since threadB is operating on its own cached copy of the value instead of operating on the main memory.</p><p>Example: Program which does not use a Lock or Volatile field</p><pre>import java.math.BigInteger;<br><br>class InfiniteCounter {<br>    private boolean done = false;<br>    <br>    public void print() {<br>        <br>        BigInteger res = BigInteger.ZERO;<br>        while(!done) {<br>            res = res.add(BigInteger.ONE);<br>        }<br>        System.out.println(&quot;Exiting print&quot;);<br>    }<br>    <br>    public void terminateLoop() {<br>        done = true;<br>    }<br>}<br><br>public class MyClass {<br>  public static void main(String[] args) throws InterruptedException {<br>      InfiniteCounter counter = new InfiniteCounter();<br>      Thread threadA = new Thread(() -&gt; {<br>          counter.print();<br>      });<br>      <br>      Thread threadB = new Thread(() -&gt; {<br>         counter.terminateLoop(); <br>      });<br>      <br>      threadA.start();<br>      Thread.sleep(500); // main thread sleeps for 0.5 second, goes to timed waiting state<br>      threadB.start(); <br>  }<br>}</pre><p>The above example could end up in an infinite loop. The private field done is initialised to false and a threadA is started which enters a while loop, the threadB which tries to change the field done will end up writing to the memory location done but it is not guaranteed that the condition of the while loop will actually load the field from main memory in each iteration. Thus even though one thread changes the field, the other threads could be operating on a cached copy of the field. This is due to compiler optimizations for performance reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMlYQ6F67qvO86KZ-_j83g.png" /></figure><p>The above example needs <em>visibility</em> guarantees. Mark the field as volatile to ensure visibility and turning off compiler optimizations.</p><pre>class InfiniteCounter {<br>    private volatile boolean done = false;<br>    <br>    public void print() {<br>        <br>        BigInteger res = BigInteger.ZERO;<br>        while(!done) {<br>            res = res.add(BigInteger.ONE);<br>        }<br>        System.out.println(&quot;Exiting print&quot;);<br>    }<br>    <br>    public void terminateLoop() {<br>        done = true;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQy1omqv2D2KQK-jkmO0Cg.png" /></figure><p>What is the use of volatile keyword?<br>1. When fields are marked with volatile keyword, all operations on such a field is guaranteed to occur on the main memory.<br>2. If there is a write operation going on a volatile variable, and suddenly a read operation is requested, it is guaranteed that the write operation will be finished prior to the read operation.</p><p>So whenever a thread writes a field and you want the latest value to directly be reflected to other threads that read the field, then use the volatile keyword.</p><p>In summary the compiler optimizations to speed up the main memory access by caching values etc will be disabled for the fields that are marked with volatile keyword and all the operations which access the volatile field will definitely operate on the main memory.</p><p>An important distinction to be made at this point is the difference between the synchronized keyword and the volatile keyword. It is also important at this point to realise that operating on volatile fields is not an <em>atomic</em> operation.</p><p><em>synchronized</em> keyword: To ensure <em>mutual exclusion</em> between threads that try to operate on <em>critical section</em> of code by protecting the execution of lines of code with the use of a Lock object. Locking guarantees <em>visibility</em> ( changes made by one thread is visible to other threads ) and <em>atomicity </em>( either the instruction is completely executed or the instruction is yet to be executed ).</p><p><em>visibility</em> aspect of synchronized keyword: All the changes made to fields inside the critical section protected by a lock L or before the critical section will me visible to any other thread that tries to access the field from a critical section of code protected using the same lock L.</p><p><em>atomicity</em> aspect of synchronized keyword: A statement inside the <em>critical section</em> of a code <em>synchronized</em> by using a Lock L will never leave the memory in an inconsistent state even if a thread suspends to inactive state.</p><pre>x = x + 5;<br><br>step1: load the value of x into register<br>step2: add 5 to the value<br>step3: store the value into memory into variable x<br><br>If the instruction is not atomic,<br>the thread could be preempted in the middle of the assembly instructions<br>at any of the steps.<br><br>which could cause Race Condition <br>when other threads try to operate on the same variable.<br><br>When the above instruction is atomic,<br>either all the 3 steps are executed before a thread suspends<br>or none of the 3 steps are executed before a thread suspends</pre><p><em>volatile</em> keyword: To ensure that changes to the value of a field are directly reflected to other threads that read the field, turn off all the optimizations on the field. Volatile guarantees <em>visibility </em>( changes made by one thread is visible to other threads ).</p><p><em>visibility</em> aspect of <em>volatile</em> keyword: All the compiler optimizations or reordering of instruction etc related to a field marked with volatile is turned off. When we operate on the volatile field we are indeed operating on the main memory.</p><p>Note that atomicity is NOT a feature of volatile keyword.</p><pre>class MyClass {<br>   private volatile int x; // visibility guaranteed<br>   <br>   public void add(int p) {<br>          x = x + p; // atomicity not guaranteed<br>   }<br>}<br><br>public class NonAtomicVolatile {<br>    public static void main(String [] args) {<br>        MyClass obj = new MyClass();<br>        Thread threadA = new Thread(() -&gt; {<br>             obj.add(42);<br>        });<br><br>        Thread threadB = new Thread(() -&gt; {<br>             obj.add(78);<br>        });<br>    }<br>} </pre><p>Since the method MyClass::add is not synchronized with the use of a Lock, thus atomicity is not guaranteed in the above program.</p><pre>intially x = 0<br>threadA loads the value of x into register Ra = 0<br>threadA loads the value of p into register Rb = 42<br>threadA adds the 2 values in register Rc = 42<br><br>threadB loads the value of x into register R1 = 0<br>threadB loads the value of p into register R2 = 78<br><br>threadB adds 2 values in register R3 = 78<br>thradB writes R3 into the memory x = 78<br>thradA writes Rc into the memory x = 42</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90Ukn6UyVIN_fuQjVbGX5A.png" /></figure><p>So even after two threads added 42, 78 respectively the result is still 78. The reason is that the memory location could not be changed before it was read by another thread, so even with volatile<em> Race Condition</em> ensued.</p><p>To fix the issue use Locks.</p><pre>class MyClass {<br>   private int x; // no need of volatile <br>   <br>   // locks ensure visibility, atomicity<br>   public synchronized void add(int p) {<br>          x = x + p;<br>   }<br>}</pre><p>There are other language specific situations where the compiler may reorder instructions which could lead to unexpected situation, the use of volatile keyword would be appropriate in such places.</p><p>Example: The way in which objects are created in Java is that an object is allocated with default values of the fields followed by instructions to executed the constructor definition. The compiler can inline those instructions that change the fields of the Java object.</p><pre>class Singleton {<br>   private static Singleton instance; // no volatile, bug<br>   <br>   public static Singleton getInstance() {<br>         if(instance == null) {<br>             synchronized(Singleton.class) {<br>                  if(instance == null) {<br>                       instance = new Singleton(10, 20);<br>                  }<br>             }<br>         }<br>         return instance;<br>   }<br><br>   private int x, y;<br>   <br>   private Singleton(int a, int b) {<br>         this.x = a;<br>         this.y = b;<br>   }<br> <br>   public int getX() {<br>       return x;<br>   }<br><br>}<br><br>public class MyClass {<br>     public static void main(String [] args) {<br>          Thread threadA = new Thread(() -&gt; {<br>             int val = Singleton.getInstance().getX();<br>             System.out.println(&quot;value &quot; + val);<br>          });<br><br>          Thread threadB = new Thread(() -&gt; {<br>             int val = Singleton.getInstance().getX();<br>          });<br>          threadA.start();<br>          threadB.start();<br>     }<br>}</pre><p>Assume a scenario where threadA and threadB both execute the <em>getInstance</em>(). The instance is null. threadA gets the lock, it creates the instance by allocating memory to an object with default initialised fields and releases the lock but the instructions of the constructor definition that change the fields are not yet executed due to compiler reordering instructions. <br>threadB acquires the Lock. Although lock objects are supposed to support visibility and atomicity, in this case the atomicity is in a way not fully achieved due to compiler reordering the instructions. threadB does see the memory allocation but the fields are not fully initialised, threadB feels that the instance is initialised although some of the instructions are yet to be executed. The threadB does not create a new instance but simply returns the object allocated by the threadA. So the problem that could happen is that the field of the object could be read other threads even before it was properly initialised by the instance creator thread.</p><p>The <em>visibility</em> aspect of Locks worked well in the scenario.<br>The <em>atomicity</em> aspect of Locks did not work well due to compiler reordering the instructions.</p><p>Again in such case, turn off all the compiler optimizations by using the <em>volatile</em> keyword. The volatile keyword ensure that no reordering will be performed by the compiler and hence object will be allocated memory as well as initialised completely before the lock is released by the instance creator thread.</p><pre>class Singleton {<br>   private volatile static Singleton instance; // volatile, <br>   <br>   public static Singleton getInstance() {<br>         if(instance == null) {<br>             synchronized(Singleton.class) {<br>                  if(instance == null) {<br>                       instance = new Singleton(10, 20);<br>                  }<br>             }<br>         }<br>         return instance;<br>   }<br><br>   private int x, y;<br>   <br>   private Singleton(int a, int b) {<br>         this.x = a;<br>         this.y = b;<br>   }<br> <br>   public int getX() {<br>       return x;<br>   }<br><br>}</pre><p>Of course these are language specific issues that require knowledge of the programming language specifications.</p><h3>The final keyword:</h3><p>When a field is marked with the <em>final</em> modifier it is thread safe to access the field since its value is read only. Accessing fields that are of primitive type is directly possible since these are non-changing values. Multiple threads can use the field with no fear of corruption.<br>In the case of pointer type fields that are declared final, we still need to worry about the pointee object’s thread safely.</p><h3>Atomicity:</h3><p>Atomicity is the ability of an instruction to execute completely or remain completely unexecuted.<br>Java library provides a number of types that guarantee the atomicity of certain instructions. These types define methods that execute atomically without the use of locks. These packages use machine level instruction to achieve atomicity without the use of Locks.<br>Of course we will still need to understand whether the amount of atomicity guaranteed by these packages are sufficient for our purpose.</p><p>The <em>AtomicInteger</em> class has <em>incrementAndGet</em> and <em>decrementAndGet</em> method that atomically increments or decrements an integer. It also contains <em>getAndAdd</em> and <em>addAndGet</em> methods that are <em>atomic</em>.</p><p>Example: Even though we have used Locks to achieve <em>mutual exclusion</em> between threadA and threadB, we can still be assured that when the two threads complete executing the <em>addValue</em> method, the count AtomicInteger will be updated to 700 with no synchronization needed. The reason is that updates to count are <em>atomic</em> in nature.</p><p>Note that the variable count itself is not volatile but the integer that is wrapped inside the AtomicInteger type is a <em>volatile</em> int and hence updates to the underlying int value will be <em>visible</em> to other threads that operate on the count.</p><p>So without using Locks we have achieved atomicity and visibility in the case of package java.util.concurrent.atomic;</p><pre>import java.util.concurrent.atomic.*;<br><br>class Counter {<br>    private AtomicInteger count = new AtomicInteger();<br><br>    public void addValue(int x) {<br>         count.addAndGet(x); // either performed fully or not performed at all<br>    }<br>}<br><br>public class MyClass {<br>   public static void main(String [] args) {<br>       Counter obj = new Counter();<br>       Thread threadA = new Thread(() -&gt; {<br>            obj.addValue(500);<br>       });<br>  <br>       Thread threadB = new Thread(() -&gt; {<br>            obj.addValue(200);<br>       });<br><br>       threadA.setName(&quot;Prince Thread&quot;);<br>       threadB.setName(&quot;Taher Thread&quot;);<br><br>       threadA.start();<br>       threadB.start();<br>   }<br>}</pre><p>Consider the following example:</p><pre>AtomicInteger maximum = new AtomicInteger();<br><br>maximum.set(Math.max(element, maximum.get())); // not atomic</pre><p>The above line is NOT <em>atomic </em>since it executes in a non-atomic manner. <br>To find the maximum of values and set it on an AtomicInteger use the <em>updateAndGet</em> method.</p><pre>maximum.updateAndGet((currentMax) -&gt; Math.max(currentMax, element));</pre><p>Or use the <em>accumulateAndGet</em> method with a suitable accumulator lambda</p><pre>maximum.accumulateAndGet(element, Math::max); // max of currentMax and element</pre><p>Some of the interesting types in the atomic package includes AtomicInteger, AtomicLong, AtomicReference and so on.</p><p><strong>Performance Issues with Atomicity:<br></strong>Updating the Atomic type values requires retrying in a loop until the update is achieved. Since can become a performance issue. The following is the source code of the <em>addAndGet</em> method of <em>AtomicInteger</em> class in the JDK.</p><pre>public final int addAndGet(int delta) {<br>        for (;;) {<br>            int current = get();<br>            int next = current + delta;<br>            if (compareAndSet(current, next))<br>                return next;<br>        }<br>    }</pre><p><em>LongAdder</em> and <em>LongAccumulator</em> classes are designed in a way to avoid performance issues with Atomic Types when some commutative operation needs to be performed.<br>Consider the commutative operation of addition in <em>LongAdder</em>. Internally it maintains several variables and not all of them need to be operated at the same time. Hence the contention for accessing the variable is low in general. Making the operation faster.</p><p>Let the maintained variables be A1, A2, A3, … An.</p><pre>LongAdder longAdder = new LongAdder();<br><br>// in threadA<br>longAdder.increment(); // atomically operates on one of the Ai<br><br>// in threadB<br>longAdder.increment(); // atomically operates on one of the Ai<br><br>// ... so on<br><br>// finally<br>longAdder.sum(); // now collects the result by adding</pre><p>The increment method will operate on one of the maintained variable Ai.<br>When the <em>sum</em> method is called only then we need to sum up all the values to obtain the result. Below is the JDK implementation of the sum method, which does the hard work of collecting result.</p><pre>public long sum() {<br>        Cell[] as = cells; Cell a;<br>        long sum = base;<br>        if (as != null) {<br>            for (int i = 0; i &lt; as.length; ++i) {<br>                if ((a = as[i]) != null)<br>                    sum += a.value;<br>            }<br>        }<br>        return sum;<br>    }</pre><p>The same idea can be generalised to <em>LongAccumulator</em> where some commutative operation op needs to be performed and we could use an accumulator to collect partial results and finally do the hard work of collecting the result on demand.</p><p>Again the idea is to maintain several variables so that the contention is low when performing the accumulation at the time of forming the partial results by operating on one of the maintained variables Ai. The result is obtained by computing A1 op A2 op A3 op … op An when asked to.</p><pre>LongAccumulator longAccumulator = new LongAccumulator(Long::sum, 0);<br><br>// in threadA<br>longAccumulator.accumulate(50); // atomically operates on one of the Ai<br><br>// in threadB<br>longAccumulator.accumulate(100); // atomically operates on one of the Ai<br><br>// ... so on<br><br>// finally<br>longAccumulator.get(); // perform A1 op A2 op A3 op .... op An</pre><h3>Deadlocks:</h3><p>Each thread in the process is waiting for a situation that can be caused by another thread which itself is waiting and thus none of the threads can continue execution. Such a situation is called Deadlock.</p><p>Example: when all the threads wait on a condition variable in the wait set and none of them can continue execution, deadlock is reached.</p><p>Consider a situation :</p><p>Shankar has 1000 Rupees in his Bank Account.<br>Vikas has 500 Rupees in his Bank Account.<br>Prince has 100 Rupees in his Bank Account.</p><p>Prince asks Vikas for 1000 Rupees.<br>Vikas asks Shankar for 1500 Rupees.<br>Shankar asks Prince for 2500 Rupees.</p><p>Since none of these people have enough money in their Bank Account none of them can actually complete the money transfer.</p><pre>class Bank {<br>   public static final int SHANKAR_ACCOUNT_NUMBER = 0;<br>   public static final int VIKAS_ACCOUNT_NUMBER = 1;<br>   public static final int PRINCE_ACCOUNT_NUMBER = 2;<br><br>   private int [] accountBalance = {1000, 500, 100};<br>  <br>   public synchronized void transferAmount(int amount, int from, int to)  throws InterruptedException {<br>        while( accountBalance[from] &lt; amount) {<br>             System.out.println(&quot;Waiting for sufficient fund &quot; + <br>                  Thread.currentThread().getName());<br>             wait();<br>        }<br>        accountBalance[from] -= amount;<br>        accountBalance[to] += amount;<br>        notifyAll();<br>        System.out.println(&quot;Transfer Complete from &quot; +<br>               from + &quot; to &quot; + to + &quot; amount &quot; + amount);<br>   }<br><br>}<br><br>public class MyClass {<br>     public static void main(String [] args) {<br>          Bank bank = new Bank();<br>          // Prince asking Vikas for 1000<br>          Thread threadA = new Thread(() -&gt; {<br>              try {<br>                  bank.transferAmount(1000, Bank.VIKAS_ACCOUNT_NUMBER, Bank.PRINCE_ACCOUNT_NUMBER);<br>              } catch(InterruptedException exception) {<br>                  System.out.println(&quot;Interrupted threadA&quot;);<br>              }<br> <br>          });<br><br>         // Vikas asking Shankar for 1500<br>          Thread threadB = new Thread(() -&gt; {<br>              try {<br>                bank.transferAmount(1500, Bank.SHANKAR_ACCOUNT_NUMBER, Bank.VIKAS_ACCOUNT_NUMBER);<br>              }  catch(InterruptedException exception) {<br>                  System.out.println(&quot;Interrupted threadB&quot;);<br>              }<br>          });<br><br>           // Shankar asking Prince for 2500<br>          Thread threadC = new Thread(() -&gt; {<br>              try {<br>                  bank.transferAmount(2500, Bank.PRINCE_ACCOUNT_NUMBER, Bank.SHANKAR_ACCOUNT_NUMBER);<br>              } catch(InterruptedException exception) {<br>                  System.out.println(&quot;Interrupted threadC&quot;);<br>              }<br>              <br>          });<br><br>           threadA.setName(&quot;Prince asks Vikas&quot;);<br>           threadB.setName(&quot;Vikas asks Shankar&quot;);<br>           threadC.setName(&quot;Shankar asks Prince&quot;);<br><br>           threadA.start();<br>           threadB.start();<br>           threadC.start();<br>     }<br>}</pre><p>Unfortunately Java does not provide any inbuilt support for handling or detecting deadlocks. The only thing Java programmers can do this to design the code so that they do not occur.</p><h3>Thread Local Variables:</h3><p>The <em>ThreadLocal </em>helper class is designed for use cases where instead of synchronizing the access to shared variables which could be a penalty on runtime, we instead provide each thread its own copy of data so there is no need of synchronizing access between threads. Of course the use of thread local variables increases the memory consumption but it ensures runtime efficiency when compared to the shared data approach. This is true in general in Computer Science wherein the time complexity of solving a problem can be improved by sacrificing on the space complexity of the solution by increasing the space complexity. This is called space-time tradeoff.</p><p>The <em>get() </em>instance method on the <em>ThreadLocal</em> object will either return the thread local wrapped value if already allocated to the requesting thread or it will allocate the value for the requesting thread and then return it.<br>Either way it ensures each requesting thread will obtain its own copy of the wrapped value on which it can operate.</p><p>The <em>withInitial</em> static method of the <em>ThreadLocal</em> class accepts a lambda object that implements the <em>Supplier&lt;T&gt; </em>Functional Interface<em>. </em>The logic that will be used to create the wrapped value is encapsulated in the <em>Supplier&lt;T&gt;</em> lambda provided using the static <em>withInitial</em> method. The lambda is executed when allocating the thread local value.<br>In simple words, the <em>ThreadLocal</em> object remembers the lambda which contains the logic that should be executed when allocating the thread local wrapped value.</p><pre>class DateFormatter {<br>    public static final ThreadLocal&lt;SimpleDateFormat&gt; <br>       threadLocalTimeStamp = ThreadLocal.withInitial(() -&gt; new SimpleDateFormat(&quot;yyyy-MM-dd&quot;));<br>       // other things<br>}<br><br>class MyClass {<br>    <br>    Thread threadA = new Thread(() -&gt; {<br>       <br>       // get method either allocates a SimpleDateFormat and then uses it<br>       // or uses the SimpleDateFormat directly created for threadA<br>       DateFormatter.threadLocalTimeStamp.get().format(new Date());<br>       <br>       // ... remaining code<br>    });<br>    Thread threadB = new Thread(() -&gt; { <br>       // get method either allocates a SimpleDateFormat and then uses it<br>       // or uses the SimpleDateFormat directly created for threadB<br>       DateFormatter.threadLocalTimeStamp.get().format(new Date());<br>       <br>       // ... remaining code<br>   });<br>    <br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6239a2a3c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>