<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>java &amp;mdash; StealthyCoder</title>
    <link>https://stealthycoder.writeas.com/tag:java</link>
    <description>Making code ninjas out of everyone</description>
    <pubDate>Wed, 29 Apr 2026 01:45:36 +0000</pubDate>
    <item>
      <title>Flow like water</title>
      <link>https://stealthycoder.writeas.com/flow-like-water?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post will have a lot of code and Java at that, so warning has been given. I happened on this little gem in the Java standard library that allows you to make a nice asynchronous model of execution with some guidance. Only the thing missing from the documentation of the Java standard library, in contrast to the one provided by Python, are examples on how to use this one. There is an example on the main page of the package. So this is my attempt at creating the implementation of these interfaces and hooking them up together based on the wordings in the documentation. !--more--&#xA;&#xA;The gem I found is in the java.util.concurrent.Flow package and consists of Producer, Subscriber and a Subscription with an optional Processor. &#xA;&#xA;The end goal&#xA;&#xA;We will make a machine that will find prime numbers for us using the Sieve of Eratosthenes. The method in its simplicity is the fact that once you found a prime number, any multiple of that prime cannot be prime. &#xA;&#xA;This will utilize the above components and I will explain the concepts as I also show the code. &#xA;&#xA;Overview&#xA;&#xA;The root directory structure and files will be as follows:&#xA;&#xA;processors&#xA;publishers&#xA;subscribers&#xA;subscriptions&#xA;util&#xA;CyclicRingBuffer.java&#xA;Main.java&#xA;&#xA;Of course the CyclicRingBuffer stands out, we will get back to that one shortly. &#xA;&#xA;First will be the util ones as they are small and concise and easy to explain. &#xA;&#xA;util&#xA;&#xA;In util there are three files:&#xA;&#xA;ConcurrentUtil.java&#xA;PrimeUtil.java&#xA;StatisticsUtil.java &#xA;&#xA;ConcurrentUtil.java&#xA;&#xA;import java.util.concurrent.ExecutorService;&#xA;import java.util.concurrent.Executors;&#xA;&#xA;public class ConcurrentUtil {&#xA;&#xA;    public static ExecutorService executorService =   Executors.newWorkStealingPool();&#xA;}&#xA;&#xA;This particular static method will just get us a ExecutorService so we can schedule work to be done in the background. You put tasks on a queue of sorts and the jobs will get executed for you in the background.&#xA;&#xA;PrimeUtil.java&#xA;&#xA;import java.util.List;&#xA;import java.util.concurrent.CopyOnWriteArrayList;&#xA;import java.util.concurrent.atomic.AtomicInteger;&#xA;&#xA;public class PrimeUtil {&#xA;&#xA;    public static ListInteger primes = new CopyOnWriteArrayList();&#xA;    public static AtomicInteger demand = new AtomicInteger(Integer.parseInt(System.getenv().getOrDefault(&#34;PRIMEFINDERDEMAND&#34;, &#34;100&#34;)));&#xA;&#xA;    static {&#xA;        primes.add(2);&#xA;    }&#xA;}&#xA;&#xA;So this class exists to hold the primes found so far with a concurrent thread safe CopyOnWriteArrayList so that simultaneous operations do not matter. Then we have an AtomicInteger that gets made by an environment variable or a default of 100. This demand is our end goal of how many primes to find. &#xA;&#xA;Then we need to prime, pun intended (always own your puns), the list by putting in 2 as that will make our lives way easier down the line. &#xA;&#xA;StatisticsUtil.java&#xA;&#xA;import java.util.Map;&#xA;import java.util.concurrent.ConcurrentHashMap;&#xA;&#xA;public class StatisticsUtil {&#xA;&#xA;    public static MapString, Integer stats = new ConcurrentHashMap();&#xA;}&#xA;&#xA;So this class is there to keep a simple ConcurrentHashMap filled with the name of the class and how many primes they found. &#xA;&#xA;That is all for the util . Let&#39;s dive into the more fun parts. &#xA;&#xA;Subscription&#xA;&#xA;First we will start with the subscription. Inside the subscriptions package there is one file named IntegerSubscription.java . What a subscription is, is a class that produces some output on one of the method calls you have to implement, namely request(long l) and can be cancelled by calling cancel(). This cancelling means no more messages can flow further into the subscribers. &#xA;&#xA;If l is smaller than 0 in the request function then an error needs to be produced. &#xA;&#xA;So the subscription has a method called request and it gets called by a subscriber . &#xA;&#xA;public class IntegerSubscription implements Flow.Subscription  {&#xA;&#xA;    private IntegerPublisher integerPublisher;&#xA;    private IteratorInteger integerStream;&#xA;    private boolean isCanceled = false;&#xA;&#xA;    public IntegerSubscription(IntegerPublisher integerPublisher) {&#xA;        this.integerPublisher = integerPublisher;&#xA;        this.integerStream = Stream.iterate(2, i -  i + 1).iterator();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void request(long l) {&#xA;        if ( l &lt; 0) {&#xA;            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));&#xA;        }&#xA;        for(long i = 0; i &lt; l; i++) {&#xA;            if(isCanceled) {&#xA;                break;&#xA;            }&#xA;            executorService.submit(() -  integerPublisher.publish(integerStream.next()));&#xA;        }&#xA;    }&#xA;&#xA;    @Override&#xA;    public void cancel() {&#xA;        isCanceled = true;&#xA;    }&#xA;}&#xA;&#xA;There are a few parts, so first in the constructor we see a Publisher more on that later. Then we see a way to produce an infinite stream of Integers. Then in request we see the actual work by giving the publisher the next integer in the stream to publish. This gets given to the ExecutorService we saw earlier in order to put this on the backlog of things to execute. &#xA;&#xA;Publisher&#xA;&#xA;So the publisher is the part that actually glues the subscriptions and the subscribers. There is a little more logic in here, but not a whole lot more. Inside the publishers package there are two files:&#xA;&#xA;IntegerPublisher.java&#xA;IntegerPublisherImpl.java&#xA;&#xA;import java.util.concurrent.Flow;&#xA;&#xA;public interface IntegerPublisher extends Flow.PublisherInteger {&#xA;&#xA;    void publish(int i);&#xA;&#xA;    void publish(IllegalArgumentException e);&#xA;}&#xA;&#xA;This first file is just an interface with two methods that are not needed by the Flow framework but exist for my convenience and to make it easier to follow everything. &#xA;&#xA;import CyclicRingBuffer;&#xA;import subscriptions.IntegerSubscription;&#xA;&#xA;import java.util.Objects;&#xA;import java.util.concurrent.*;&#xA;import static util.ConcurrentUtil.executorService;&#xA;&#xA;public class IntegerPublisherImpl implements IntegerPublisher  {&#xA;&#xA;    private final IntegerSubscription subscription;&#xA;    private final CyclicRingBufferFlow.Subscriber&lt;? super Integer  subscribers;&#xA;&#xA;    public IntegerPublisherImpl() {&#xA;        this.subscription = new IntegerSubscription(this);&#xA;        subscribers = new CyclicRingBuffer();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void subscribe(Flow.Subscriber? super Integer subscriber) {&#xA;        subscribers.push(subscriber);&#xA;        executorService.submit(() -  subscriber.onSubscribe(this.subscription));&#xA;    }&#xA;&#xA;    private void shutdown(boolean cancel) {&#xA;        if (cancel) {&#xA;            this.subscription.cancel();&#xA;        } else {&#xA;            for (Flow.Subscriber? super Integer subscriber : subscribers) {&#xA;                subscriber.onComplete();&#xA;            }&#xA;        }&#xA;&#xA;        executorService.shutdown();&#xA;&#xA;    }&#xA;&#xA;    public void publish(int i) {&#xA;        executorService.submit(() -  Objects.requireNonNull(subscribers.poll()).onNext(i));&#xA;    }&#xA;&#xA;    public void publish(IllegalArgumentException e) {&#xA;        executorService.submit(() -  Objects.requireNonNull(subscribers.poll()).onError(e));&#xA;    }&#xA;&#xA;    public void sendShutdown(boolean cancel) {&#xA;        this.shutdown(cancel);&#xA;    }&#xA;}&#xA;&#xA;So this class binds Subscriptions and Subscribers together. Well a subscription will produce an output and call the publish function to publish it to the subscribers of this subscription. The CyclicRingBuffer here will be explained later. Furthermore we have an actual method called subscribe that takes in a Subscriber with a certain bounded type, in my case Integer. We give the subscriber in question the subscription to subscribe to and then the circle is complete and things can get moving. &#xA;&#xA;In the publish method the onNext gets called of the subscriber. That will be the actual processing logic of what we want to do with our Integers. So far we only saw who produces them (Subscription) and who syndicates them (Publisher) and now we see who processes them.&#xA;&#xA;Subscriber&#xA;&#xA;The subscriber requests data from the subscription in question. So the onSubscribe initialises the requesting of data from the subscription. Then the onNext will hold the main logic and at the end always call more request of the subscription if you want to keep things in motion. There is also onComplete when all is said and done and onError which should be called anytime an error occurs in the chain and needs to be propagated to the actual subscriber.  &#xA;&#xA;import util.StatisticsUtil;&#xA;import java.util.UUID;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;import static util.PrimeUtil.demand;&#xA;import static util.PrimeUtil.primes;&#xA;import static util.ConcurrentUtil.executorService;&#xA;&#xA;public class PrimeFinder implements Flow.SubscriberInteger {&#xA;&#xA;    private final String name;&#xA;    private Flow.Subscription subscription;&#xA;    private static Logger LOGGER;&#xA;&#xA;    public PrimeFinder() {&#xA;        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());&#xA;        LOGGER = Logger.getLogger(this.name);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onSubscribe(Flow.Subscription subscription) {&#xA;        subscription.request(1);&#xA;        this.subscription = subscription;&#xA;        StatisticsUtil.stats.putIfAbsent(this.name, 0);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onNext(Integer integer) {&#xA;        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));&#xA;&#xA;        if (primes.parallelStream().noneMatch(p -  integer % p == 0)) {&#xA;            if(demand.getAndDecrement()   0) {&#xA;                primes.add(integer);&#xA;                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));&#xA;                int newCount = StatisticsUtil.stats.get(this.name) + 1;&#xA;                StatisticsUtil.stats.put(this.name, newCount);&#xA;            }&#xA;        }&#xA;        if(demand.get()   0) {&#xA;            executorService.submit(() -  subscription.request(1));&#xA;        }&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onError(Throwable throwable) {&#xA;        LOGGER.log(Level.SEVERE, throwable.getMessage());&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onComplete() {&#xA;        LOGGER.log(Level.INFO, name + &#34; is done&#34;);&#xA;    }&#xA;}&#xA;&#xA;So the onError and onComplete methods are just logging methods. The onSubscribe kickstarts the whole operation. The first thing that happens is request from the subscription in question and then setting that subscription locally to this instance so we can request more from it later on. Then finally register this instance in the StatisticsUtil so the score can be kept on who got how many primes. &#xA;&#xA;Then onNext gets an integer, via the subscription through the publisher, and first checks if it does not occur in the Sieve. This line does all the work:&#xA;&#xA;primes.parallelStream().noneMatch(p -  integer % p == 0)&#xA;&#xA;The explanation is turn the primes list into a parallel stream. Then check if none match the expression given afterwards. The expression will check if the number to be worked on modulo the prime will give 0. This means that the integer given can be divided exactly by the prime and therefore it is not a prime. If the integer cannot be divided by any of the primes found so far then we have a new prime!!&#xA;&#xA; Then it gets and decrements the demand in order to see if we still have to find more primes. If so then add it to the stats and the list of found primes.  &#xA;&#xA;Then a new check to demand is made, some other subscriber could have found the last one in the mean time, and then requests more from the subscription if more need to be found. &#xA;&#xA;CyclicRingBuffer&#xA;&#xA;The CyclicRingBuffer is a data structure that lets you cycle through a list endlessly and so it makes perfect sense in this case as I want to infinitely round robin the subscribers to publish the new data to them. How to implement it is by extending a well known class in Java and then overriding a few key methods. &#xA;&#xA;import java.util.concurrent.ConcurrentLinkedDeque;&#xA;&#xA;public class CyclicRingBufferE extends ConcurrentLinkedDequeE {&#xA;&#xA;    public E poll() {&#xA;        E e = super.pollFirst();&#xA;&#xA;        assert e != null;&#xA;&#xA;        this.offerLast(e);&#xA;        return e;&#xA;    }&#xA;&#xA;    public E pollFirst() {&#xA;        E e = super.pollFirst();&#xA;&#xA;        assert e != null;&#xA;&#xA;        this.offerLast(e);&#xA;        return e;&#xA;    }&#xA;&#xA;    public E pollLast() {&#xA;        E e = super.pollLast();&#xA;&#xA;        assert e != null;&#xA;&#xA;        this.offerFirst(e);&#xA;        return e;&#xA;    }&#xA;&#xA;}&#xA;&#xA;So the Deque is a queue where you can add both at the front and the back and take from both sides. It is a Double Ended Queue (Deque). So these three methods just implement that logic. If you take from the front you add the element to the back again and also if you take from the rear add it to the front. &#xA;&#xA;Main&#xA;&#xA;The main file puts everything together by hooking up all the necessary parts. Just remember, the flow is Subscriber requests data from a Subscription that should ask the Publisher to publish to all who are subscribed to that particular Subscription. &#xA;&#xA;import publishers.IntegerPublisherImpl;&#xA;import subscribers.PrimeFinder;&#xA;import util.PrimeUtil;&#xA;import util.StatisticsUtil;&#xA;&#xA;import java.util.ArrayList;&#xA;import java.util.List;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.concurrent.TimeUnit;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;public class Main {&#xA;    final static int totalSubscribers = Runtime.getRuntime().availableProcessors();&#xA;    private static final Logger LOGGER = Logger.getAnonymousLogger();&#xA;&#xA;    public static void main(String[] args) throws InterruptedException {&#xA;        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();&#xA;        ListFlow.Subscriber&lt;Integer  subscribers = new ArrayList();&#xA;&#xA;        for (int i = 0; i &lt; totalSubscribers; i++) {&#xA;            subscribers.add(new PrimeFinder());&#xA;        }&#xA;        subscribers.forEach(integerPublisher::subscribe);&#xA;&#xA;        while (PrimeUtil.demand.get()   0 ) {&#xA;            TimeUnit.MILLISECONDS.sleep(100);&#xA;        }&#xA;        integerPublisher.sendShutdown(false);&#xA;        StatisticsUtil.stats.forEach((name, count) -  LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));&#xA;        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());&#xA;    }&#xA;}&#xA;&#xA;This code gets the available processors and creates that many subscribers. Then each of those subscribers get the same subscription to the Integer stream. Then there is a sleep moment until all is found and they are then being nicely shutdown and the statistics of who found what is then printed out. &#xA;&#xA;Why not both&#xA;&#xA;So in order to chain things you can create Processors. They are subscribers and publishers at the same time, but of potential different types. For example a Publisher of Strings but a Subscriber of Integers. In other words you put String things in and out should come Integers to the next Subscriber or Processor . &#xA;&#xA;The main benefit is you can transmute things but also have one Processor start off many other chains with the same data. For example one word can be counted for in length, how many vowels, what kind of word it is, what language and so on. As this processor is just a hub to kick off many other flows, it makes more sense maybe to think of our Prime finder example and then just extend it by operating on the primes found.&#xA;&#xA;Seeing if we found sexy primes or cousin primes for example. &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>This post will have a lot of code and Java at that, so warning has been given. I happened on this little gem in the Java standard library that allows you to make a nice asynchronous model of execution with some guidance. <del>Only the thing missing from the documentation of the Java standard library, in contrast to the one provided by Python, are examples on how to use this one</del>. There is an example on the <a href="https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Flow.html" rel="nofollow">main page of the package</a>. So this is my attempt at creating the implementation of these interfaces and hooking them up together based on the wordings in the documentation. </p>

<p>The gem I found is in the <code>java.util.concurrent.Flow</code> package and consists of <strong>Producer</strong>, <strong>Subscriber</strong> and a <strong>Subscription</strong> with an optional <strong>Processor</strong>.</p>

<h2 id="the-end-goal" id="the-end-goal">The end goal</h2>

<p>We will make a machine that will find prime numbers for us using the <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a>. The method in its simplicity is the fact that once you found a prime number, any multiple of that prime cannot be prime.</p>

<p>This will utilize the above components and I will explain the concepts as I also show the code.</p>

<h2 id="overview" id="overview">Overview</h2>

<p>The root directory structure and files will be as follows:</p>

<pre><code>processors
publishers
subscribers
subscriptions
util
CyclicRingBuffer.java
Main.java
</code></pre>

<p>Of course the <code>CyclicRingBuffer</code> stands out, we will get back to that one shortly.</p>

<p>First will be the util ones as they are small and concise and easy to explain.</p>

<h2 id="util" id="util">util</h2>

<p>In util there are three files:</p>
<ul><li>ConcurrentUtil.java</li>
<li>PrimeUtil.java</li>
<li>StatisticsUtil.java</li></ul>

<h3 id="concurrentutil-java" id="concurrentutil-java">ConcurrentUtil.java</h3>

<pre><code class="language-java">import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentUtil {

    public static ExecutorService executorService =   Executors.newWorkStealingPool();
}
</code></pre>

<p>This particular static method will just get us a <code>ExecutorService</code> so we can schedule work to be done in the background. You put tasks on a queue of sorts and the jobs will get executed for you in the background.</p>

<h3 id="primeutil-java" id="primeutil-java">PrimeUtil.java</h3>

<pre><code class="language-java">import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class PrimeUtil {

    public static List&lt;Integer&gt; primes = new CopyOnWriteArrayList&lt;&gt;();
    public static AtomicInteger demand = new AtomicInteger(Integer.parseInt(System.getenv().getOrDefault(&#34;PRIMEFINDER_DEMAND&#34;, &#34;100&#34;)));

    static {
        primes.add(2);
    }
}
</code></pre>

<p>So this class exists to hold the <code>primes</code> found so far with a concurrent thread safe <code>CopyOnWriteArrayList</code> so that simultaneous operations do not matter. Then we have an <code>AtomicInteger</code> that gets made by an environment variable or a default of 100. This <code>demand</code> is our end goal of how many primes to find.</p>

<p>Then we need to <strong>prime</strong>, pun intended (always own your puns), the list by putting in <code>2</code> as that will make our lives way easier down the line.</p>

<h3 id="statisticsutil-java" id="statisticsutil-java">StatisticsUtil.java</h3>

<pre><code class="language-java">import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StatisticsUtil {

    public static Map&lt;String, Integer&gt; stats = new ConcurrentHashMap&lt;&gt;();
}
</code></pre>

<p>So this class is there to keep a simple <code>ConcurrentHashMap</code> filled with the name of the class and how many primes they found.</p>

<p>That is all for the <em>util</em> . Let&#39;s dive into the more fun parts.</p>

<h3 id="subscription" id="subscription">Subscription</h3>

<p>First we will start with the subscription. Inside the <strong>subscriptions</strong> package there is one file named <code>IntegerSubscription.java</code> . What a subscription is, is a class that produces some output on one of the method calls you have to implement, namely <code>request(long l)</code> and can be cancelled by calling <code>cancel()</code>. This cancelling means no more messages can flow further into the subscribers.</p>

<p>If <code>l</code> is smaller than <strong>0</strong> in the <code>request</code> function then an error needs to be produced.</p>

<p>So the subscription has a method called <code>request</code> and it gets called by a <em>subscriber</em> .</p>

<pre><code class="language-java">public class IntegerSubscription implements Flow.Subscription  {

    private IntegerPublisher integerPublisher;
    private Iterator&lt;Integer&gt; integerStream;
    private boolean isCanceled = false;

    public IntegerSubscription(IntegerPublisher integerPublisher) {
        this.integerPublisher = integerPublisher;
        this.integerStream = Stream.iterate(2, i -&gt; i + 1).iterator();
    }

    @Override
    public void request(long l) {
        if ( l &lt; 0) {
            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));
        }
        for(long i = 0; i &lt; l; i++) {
            if(isCanceled) {
                break;
            }
            executorService.submit(() -&gt; integerPublisher.publish(integerStream.next()));
        }
    }

    @Override
    public void cancel() {
        isCanceled = true;
    }
}
</code></pre>

<p>There are a few parts, so first in the constructor we see a <strong>Publisher</strong> more on that later. Then we see a way to produce an infinite stream of Integers. Then in <code>request</code> we see the actual work by giving the publisher the next integer in the stream to publish. This gets given to the ExecutorService we saw earlier in order to put this on the backlog of things to execute.</p>

<h3 id="publisher" id="publisher">Publisher</h3>

<p>So the publisher is the part that actually glues the subscriptions and the subscribers. There is a little more logic in here, but not a whole lot more. Inside the <strong>publishers</strong> package there are two files:</p>
<ul><li>IntegerPublisher.java</li>
<li>IntegerPublisherImpl.java</li></ul>

<pre><code class="language-java">import java.util.concurrent.Flow;

public interface IntegerPublisher extends Flow.Publisher&lt;Integer&gt; {

    void publish(int i);

    void publish(IllegalArgumentException e);
}
</code></pre>

<p>This first file is just an interface with two methods that are not needed by the Flow framework but exist for my convenience and to make it easier to follow everything.</p>

<pre><code class="language-java">import CyclicRingBuffer;
import subscriptions.IntegerSubscription;

import java.util.Objects;
import java.util.concurrent.*;
import static util.ConcurrentUtil.executorService;

public class IntegerPublisherImpl implements IntegerPublisher  {

    private final IntegerSubscription subscription;
    private final CyclicRingBuffer&lt;Flow.Subscriber&lt;? super Integer&gt;&gt; subscribers;

    public IntegerPublisherImpl() {
        this.subscription = new IntegerSubscription(this);
        subscribers = new CyclicRingBuffer&lt;&gt;();
    }

    @Override
    public void subscribe(Flow.Subscriber&lt;? super Integer&gt; subscriber) {
        subscribers.push(subscriber);
        executorService.submit(() -&gt; subscriber.onSubscribe(this.subscription));
    }

    private void shutdown(boolean cancel) {
        if (cancel) {
            this.subscription.cancel();
        } else {
            for (Flow.Subscriber&lt;? super Integer&gt; subscriber : subscribers) {
                subscriber.onComplete();
            }
        }

        executorService.shutdown();

    }

    public void publish(int i) {
        executorService.submit(() -&gt; Objects.requireNonNull(subscribers.poll()).onNext(i));
    }

    public void publish(IllegalArgumentException e) {
        executorService.submit(() -&gt; Objects.requireNonNull(subscribers.poll()).onError(e));
    }

    public void sendShutdown(boolean cancel) {
        this.shutdown(cancel);
    }
}
</code></pre>

<p>So this class binds <strong>Subscriptions</strong> and <strong>Subscribers</strong> together. Well a subscription will produce an output and call the publish function to publish it to the subscribers of this subscription. The <code>CyclicRingBuffer</code> here will be explained later. Furthermore we have an actual method called <code>subscribe</code> that takes in a <code>Subscriber</code> with a certain bounded type, in my case Integer. We give the subscriber in question the subscription to subscribe to and then the circle is complete and things can get moving.</p>

<p>In the <code>publish</code> method the <code>onNext</code> gets called of the subscriber. That will be the actual processing logic of what we want to do with our <code>Integers</code>. So far we only saw who produces them (Subscription) and who syndicates them (Publisher) and now we see who processes them.</p>

<h3 id="subscriber" id="subscriber">Subscriber</h3>

<p>The subscriber requests data from the subscription in question. So the <code>onSubscribe</code> initialises the requesting of data from the subscription. Then the <code>onNext</code> will hold the main logic and at the end always call more request of the subscription if you want to keep things in motion. There is also <code>onComplete</code> when all is said and done and <code>onError</code> which should be called anytime an error occurs in the chain and needs to be propagated to the actual subscriber.</p>

<pre><code class="language-java">import util.StatisticsUtil;
import java.util.UUID;
import java.util.concurrent.Flow;
import java.util.logging.Level;
import java.util.logging.Logger;

import static util.PrimeUtil.demand;
import static util.PrimeUtil.primes;
import static util.ConcurrentUtil.executorService;

public class PrimeFinder implements Flow.Subscriber&lt;Integer&gt; {

    private final String name;
    private Flow.Subscription subscription;
    private static Logger LOGGER;

    public PrimeFinder() {
        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());
        LOGGER = Logger.getLogger(this.name);
    }

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        subscription.request(1);
        this.subscription = subscription;
        StatisticsUtil.stats.putIfAbsent(this.name, 0);
    }

    @Override
    public void onNext(Integer integer) {
        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));

        if (primes.parallelStream().noneMatch(p -&gt; integer % p == 0)) {
            if(demand.getAndDecrement() &gt; 0) {
                primes.add(integer);
                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));
                int newCount = StatisticsUtil.stats.get(this.name) + 1;
                StatisticsUtil.stats.put(this.name, newCount);
            }
        }
        if(demand.get() &gt; 0) {
            executorService.submit(() -&gt; subscription.request(1));
        }
    }

    @Override
    public void onError(Throwable throwable) {
        LOGGER.log(Level.SEVERE, throwable.getMessage());
    }

    @Override
    public void onComplete() {
        LOGGER.log(Level.INFO, name + &#34; is done&#34;);
    }
}
</code></pre>

<p>So the <code>onError</code> and <code>onComplete</code> methods are just logging methods. The <code>onSubscribe</code> kickstarts the whole operation. The first thing that happens is request from the subscription in question and then setting that subscription locally to this instance so we can request more from it later on. Then finally register this instance in the StatisticsUtil so the score can be kept on who got how many primes.</p>

<p>Then <code>onNext</code> gets an integer, via the subscription through the publisher, and first checks if it does not occur in the Sieve. This line does all the work:</p>

<p><code>primes.parallelStream().noneMatch(p -&gt; integer % p == 0)</code></p>

<p>The explanation is turn the <em>primes</em> list into a parallel stream. Then check if none match the expression given afterwards. The expression will check if the number to be worked on modulo the prime will give 0. This means that the <strong>integer</strong> given can be divided exactly by the prime and therefore it is not a prime. If the <strong>integer</strong> cannot be divided by any of the primes found so far then we have a new prime!!</p>

<p> Then it gets and decrements the <code>demand</code> in order to see if we still have to find more <strong>primes</strong>. If so then add it to the <em>stats</em> and the list of found primes.</p>

<p>Then a new check to <code>demand</code> is made, some other subscriber could have found the last one in the mean time, and then requests more from the subscription if more need to be found.</p>

<h3 id="cyclicringbuffer" id="cyclicringbuffer">CyclicRingBuffer</h3>

<p>The <code>CyclicRingBuffer</code> is a data structure that lets you cycle through a list endlessly and so it makes perfect sense in this case as I want to infinitely round robin the subscribers to publish the new data to them. How to implement it is by extending a well known class in Java and then overriding a few key methods.</p>

<pre><code class="language-java">import java.util.concurrent.ConcurrentLinkedDeque;

public class CyclicRingBuffer&lt;E&gt; extends ConcurrentLinkedDeque&lt;E&gt; {

    public E poll() {
        E e = super.pollFirst();

        assert e != null;

        this.offerLast(e);
        return e;
    }

    public E pollFirst() {
        E e = super.pollFirst();

        assert e != null;

        this.offerLast(e);
        return e;
    }

    public E pollLast() {
        E e = super.pollLast();

        assert e != null;

        this.offerFirst(e);
        return e;
    }

}
</code></pre>

<p>So the <code>Deque</code> is a queue where you can add both at the front and the back and take from both sides. It is a Double Ended Queue (Deque). So these three methods just implement that logic. If you take from the front you add the element to the back again and also if you take from the rear add it to the front.</p>

<h3 id="main" id="main">Main</h3>

<p>The main file puts everything together by hooking up all the necessary parts. Just remember, the flow is Subscriber requests data from a Subscription that should ask the Publisher to publish to all who are subscribed to that particular Subscription.</p>

<pre><code class="language-java">import publishers.IntegerPublisherImpl;
import subscribers.PrimeFinder;
import util.PrimeUtil;
import util.StatisticsUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {
    final static int totalSubscribers = Runtime.getRuntime().availableProcessors();
    private static final Logger LOGGER = Logger.getAnonymousLogger();

    public static void main(String[] args) throws InterruptedException {
        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();
        List&lt;Flow.Subscriber&lt;Integer&gt;&gt; subscribers = new ArrayList&lt;&gt;();

        for (int i = 0; i &lt; totalSubscribers; i++) {
            subscribers.add(new PrimeFinder());
        }
        subscribers.forEach(integerPublisher::subscribe);

        while (PrimeUtil.demand.get() &gt; 0 ) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
        integerPublisher.sendShutdown(false);
        StatisticsUtil.stats.forEach((name, count) -&gt; LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));
        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());
    }
}
</code></pre>

<p>This code gets the available processors and creates that many subscribers. Then each of those subscribers get the same subscription to the Integer stream. Then there is a sleep moment until all is found and they are then being nicely shutdown and the statistics of who found what is then printed out.</p>

<h2 id="why-not-both" id="why-not-both">Why not both</h2>

<p>So in order to chain things you can create <code>Processors</code>. They are subscribers and publishers at the same time, but of potential different types. For example a <code>Publisher</code> of <code>Strings</code> but a <code>Subscriber</code> of <code>Integers</code>. In other words you put <code>String</code> things in and out should come <code>Integers</code> to the next <code>Subscriber</code> or <code>Processor</code> .</p>

<p>The main benefit is you can transmute things but also have one <code>Processor</code> start off many other chains with the same data. For example one word can be counted for in length, how many vowels, what kind of word it is, what language and so on. As this processor is just a hub to kick off many other flows, it makes more sense maybe to think of our Prime finder example and then just extend it by operating on the primes found.</p>

<p>Seeing if we found <a href="https://en.wikipedia.org/wiki/Sexy_prime" rel="nofollow">sexy primes</a> or <a href="https://en.wikipedia.org/wiki/Cousin_prime" rel="nofollow">cousin primes</a> for example.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/flow-like-water</guid>
      <pubDate>Mon, 09 Mar 2020 22:37:33 +0000</pubDate>
    </item>
    <item>
      <title>Truths in Java</title>
      <link>https://stealthycoder.writeas.com/truths-in-java?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is about why you want immutable objects and how to achieve that in various ways. I specify the language as Java this time because I want to showcase the Quarkus framework. This pattern can be used in any language and framework combination using the tools available in that language of course. !--more--&#xA;&#xA;Oracles&#xA;&#xA;Why do objects need to be immutable and what does it even mean? Well to be immutable mean you are not allowed to change a property of the object but you are allowed to assign a whole new reference to the variable for example. Like with String in Java, and with strings in most other languages. You cannot change a part of the String in the middle but you are allowed to assign a new String to a variable declared. &#xA;&#xA;String s = &#34;StealthyCoder&#34;;&#xA;s = &#34;Coding Ninjas&#34;; &#xA;What you want is the fact that s, in this case, will hold a truth and that truth will not easily be changed halfway true except very explicitly. &#xA;&#xA;In this case you want s to be a so called oracle. It needs to be able to tell you what the source of truth is at this specific moment in time. &#xA;&#xA;DTOs&#xA;&#xA;In the REST API world, there is a pattern that consists of DTOs, Entities, Services and Controllers. In which a Controller is responsible for making sure a route has a method associated with it. The Entities are responsible for modeling the Database tables. The Services are responsible for handling Entities and making business logic decisions. The DTOs are responsible for being the truthful state of the world. &#xA;&#xA;This leads to stating that DTOs, and also to an extent Entities, should be immutable as it was just stated that oracles are there to provide truths. In the REST API we will be making, the fact is that whatever the frontend will be sending as an input should be immutable once it is in the backend as we do not want any code to be able to accidentally change something. Also the generation of a response should be once only. &#xA;&#xA;The following project outline and code will provide some examples on how to achieve this using the Quarkus framework.&#xA;&#xA;Outline&#xA;&#xA;├── build.gradle&#xA;├── docker-compose.yml&#xA;├── Dockerfile&#xA;├── gradle.properties&#xA;├── settings.gradle&#xA;└── src&#xA;    └── main&#xA;        ├── java&#xA;        │   └── com&#xA;        │       └── stealthycoder&#xA;        │           └── dto&#xA;        │               ├── models&#xA;        │               │   ├── dto&#xA;        │               │   │   ├── GiftRequestDTO.java&#xA;        │               │   │   └── GiftResponseDTO.java&#xA;        │               │   └── entity&#xA;        │               │       └── Gift.java&#xA;        │               ├── routes&#xA;        │               │   └── gifts&#xA;        │               │       └── GiftResource.java&#xA;        │               └── services&#xA;        │                   └── SantaClausService.java&#xA;        └── resources&#xA;            └── application.properties&#xA;&#xA;build.gradle&#xA;&#xA;The contents of the build.gradle file are as follows:&#xA;plugins {&#xA;    id &#39;java&#39;&#xA;    id &#39;io.quarkus&#39; version &#34;${quarkusVersion}&#34;&#xA;}&#xA;&#xA;repositories {&#xA;     mavenCentral()&#xA;}&#xA;&#xA;test {&#xA;  useJUnitPlatform()&#xA;}&#xA;&#xA;dependencies {&#xA;    implementation &#39;io.quarkus:quarkus-resteasy-jackson&#39;&#xA;    implementation &#39;io.quarkus:quarkus-hibernate-orm&#39;&#xA;    implementation &#39;io.quarkus:quarkus-jdbc-postgresql&#39;&#xA;    implementation enforcedPlatform(&#34;io.quarkus:quarkus-bom:${quarkusVersion}&#34;)&#xA;&#xA;    testImplementation &#39;io.quarkus:quarkus-junit5&#39;&#xA;    testImplementation &#39;io.rest-assured:rest-assured&#39;&#xA;}&#xA;group &#39;com.stealthycoder&#39;&#xA;version &#39;0.0.1-SNAPSHOT&#39;&#xA;&#xA;sourceCompatibility = 14&#xA;This just sets up the necessary dependencies for our project and the extensions for Quarkus in order to handle JSON serialization (quarkus-resteasy-jackson) and connect to Postgres (quarkus-jdbc-postgresql) for example. &#xA;&#xA;docker-compose.yml&#xA;&#xA;The contents of the docker-compose.yml file are as follows:&#xA;version: &#39;3.6&#39;&#xA;&#xA;networks:&#xA;  quarkus:&#xA;    name: quarkus&#xA;&#xA;services:&#xA;  api:&#xA;    containername: api.dto.local&#xA;    build:&#xA;      context: .&#xA;      dockerfile: &#39;Dockerfile&#39;&#xA;    environment:&#xA;      PGHOST: database&#xA;      PGUSER: dto&#xA;      PGPASS: dto&#xA;      PGDATABASE: dto&#xA;    ports:&#xA;      &#34;8080:8080&#34;&#xA;    networks:&#xA;      quarkus&#xA;  database:&#xA;    image: postgres:13-alpine&#xA;    containername: db.dto.local&#xA;    environment:&#xA;      POSTGRESPASSWORD: dto&#xA;      POSTGRESUSER: dto&#xA;      POSTGRESDB: dto&#xA;    stdinopen: true&#xA;    tty: true&#xA;    networks:&#xA;      quarkus&#xA;This sets us up so we have a running container and database we can use locally for our development purposes. I chose to build the image for the API because I was reluctant this time to install Gradle on the docker image or indeed use a ready made Gradle image to run the tooling in there. &#xA;&#xA;Dockerfile&#xA;&#xA;The contents of the Dockerfile are as follows:&#xA;FROM adoptopenjdk/openjdk14:alpine-slim&#xA;&#xA;COPY build/com.stealthycoder.dto-0.0.1-SNAPSHOT-runner.jar /srv/http/quarkus.jar&#xA;COPY build/lib /srv/http/lib&#xA;&#xA;CMD [&#34;/opt/java/openjdk/bin/java&#34;, &#34;-jar&#34;, &#34;/srv/http/quarkus.jar&#34; ]&#xA;Very straightforward, copy a jar into a named other jar and copy the lib folder as well as it needs that to be able to load the dependencies and start it. &#xA;The name of the jar depends on the group name and the structure of the package and of a setting in the settings.gradle file.&#xA;&#xA;gradle.properties&#xA;&#xA;The contents of the gradle.properties file is as follows:&#xA;quarkusVersion=1.8.1.Final&#xA;&#xA;settings.gradle&#xA;&#xA;The contents of the settings.gradle file are as follows:&#xA;&#xA;pluginManagement {&#xA;    repositories {&#xA;        mavenLocal()&#xA;        mavenCentral()&#xA;        gradlePluginPortal()&#xA;    }&#xA;}&#xA;rootProject.name = &#39;com.stealthycoder.dto&#39;&#xA;&#xA;That rootProject.name will mostly determine the naming together with the version of build.gradle. &#xA;&#xA;application.properties&#xA;&#xA;The contents of the application.properties file are as follows:&#xA;quarkus.datasource.db-kind = pg&#xA;quarkus.datasource.jdbc.url = jdbc:postgresql://${PGHOST:localhost}/${PGDATABASE:database}&#xA;quarkus.datasource.username=${PGUSER:user}&#xA;quarkus.datasource.password=${PGPASS:password}&#xA;quarkus.hibernate-orm.database.generation=${HIBERNATEGENERATION:drop-and-create}&#xA;quarkus.http.access-log.enabled=true&#xA;quarkus.http.access-log.pattern=&#34;%h &#34;%r&#34; %s&#34;&#xA;quarkus.resteasy.gzip.enabled=true&#xA;quarkus.resteasy.gzip.max-input=10M&#xA;This will set the connection to the database based on Environment variables with some defaults. The HIBERNATEGENERATION should only be set to drop-and-create the very first time you run the application as it will otherwise consistently delete your previous data. &#xA;&#xA;GiftResource.java&#xA;&#xA;The contents of the GiftResource.java are as follows:&#xA;package com.stealthycoder.dto.routes.gifts;&#xA;&#xA;import com.stealthycoder.dto.models.dto.GiftRequestDTO;&#xA;import com.stealthycoder.dto.models.dto.GiftResponseDTO;&#xA;import com.stealthycoder.dto.services.SantaClausService;&#xA;&#xA;import javax.inject.Inject;&#xA;import javax.ws.rs.Consumes;&#xA;import javax.ws.rs.GET;&#xA;import javax.ws.rs.PATCH;&#xA;import javax.ws.rs.POST;&#xA;import javax.ws.rs.Path;&#xA;import javax.ws.rs.PathParam;&#xA;import javax.ws.rs.Produces;&#xA;import javax.ws.rs.core.MediaType;&#xA;import javax.ws.rs.core.Response;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@Path(&#34;/gift&#34;)&#xA;public final class GiftResource {&#xA;&#xA;    @Inject&#xA;    SantaClausService service;&#xA;&#xA;    @GET&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Path(&#34;{id}&#34;)&#xA;    public Response get(@PathParam(&#34;id&#34;) UUID uuid) {&#xA;        GiftResponseDTO gift = service.getGift(uuid);&#xA;        if (Objects.isNull(gift)) {&#xA;            return Response.status(Response.Status.NOTFOUND).build();&#xA;        }&#xA;        return Response.ok(gift).build();&#xA;    }&#xA;&#xA;    @POST&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Consumes(MediaType.APPLICATIONJSON)&#xA;    public Response add(GiftRequestDTO giftRequestDTO) {&#xA;        return Response.ok(service.createGift(giftRequestDTO)).build();&#xA;    }&#xA;&#xA;    @PATCH&#xA;    @Produces(MediaType.APPLICATIONJSON)&#xA;    @Consumes(MediaType.APPLICATIONJSON)&#xA;    @Path(&#34;{id}&#34;)&#xA;    public Response update(@PathParam(&#34;id&#34;) UUID uuid, GiftRequestDTO giftRequestDTO) {&#xA;        GiftResponseDTO responseDTO = service.updateGift(uuid, giftRequestDTO);&#xA;        if (Objects.isNull(responseDTO)) {&#xA;            return Response.status(Response.Status.NOTFOUND).build();&#xA;        }&#xA;        return Response.ok(responseDTO).build();&#xA;    }&#xA;&#xA;}&#xA;This file will create routes for GET, POST and PATCH on the path /gift. From this we can also determine that the service SantaClausService returns DTOs and also accepts DTOs. The Produces and Consumes annotations help with making sure the serialization will work alright. So in this case the fact is the method will get an instance of the GiftRequestDTO class to be able to use for further processing.&#xA;&#xA;GiftRequestDTO.java&#xA;&#xA;The contents of the GiftRequestDTO.java file are as follows:&#xA;package com.stealthycoder.dto.models.dto;&#xA;&#xA;import com.fasterxml.jackson.annotation.JsonAutoDetect;&#xA;&#xA;@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)&#xA;public final class GiftRequestDTO {&#xA;    private String name;&#xA;    private String wrapper;&#xA;    private boolean expensive;&#xA;    private boolean fragile;&#xA;&#xA;    public String getName(){&#xA;        return name;&#xA;    }&#xA;&#xA;    public String getWrapper() {&#xA;        return wrapper;&#xA;    }&#xA;&#xA;    public boolean isExpensive() {&#xA;        return expensive;&#xA;    }&#xA;&#xA;    public boolean isFragile() {&#xA;        return fragile;&#xA;    }&#xA;}&#xA;The important bits to note are the fields are all private. Another is that there are only so called getters . The thing that ties it all together is to tell Jackson to allow to use reflection on all fields so it can set even private fields to values. This is what will make the DTO immutable for further processing. Of course there are ways around this as it was just stated that even Jackson can do mutations to private fields. Also the class is marked as final meaning you cannot extend it in some way and therefore cast it and still make changes. &#xA;&#xA;GiftResponseDTO.java &#xA;&#xA;The contents of the GiftResponseDTO.java are as follows:&#xA;package com.stealthycoder.dto.models.dto;&#xA;&#xA;import com.fasterxml.jackson.annotation.JsonAutoDetect;&#xA;&#xA;import java.util.UUID;&#xA;&#xA;@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PROTECTEDANDPUBLIC)&#xA;public final class GiftResponseDTO {&#xA;    protected UUID id;&#xA;    protected String name;&#xA;    protected String wrapper;&#xA;    protected boolean expensive;&#xA;    protected boolean fragile;&#xA;&#xA;    public final static class Builder {&#xA;        private String name;&#xA;        private String wrapper;&#xA;        private boolean expensive;&#xA;        private boolean fragile;&#xA;        private UUID id;&#xA;&#xA;        public Builder withName(String name) {&#xA;            this.name = name;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder withWrapper(String wrapper) {&#xA;            this.wrapper = wrapper;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder isExpensive(boolean expensive) {&#xA;            this.expensive = expensive;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder isFragile(boolean fragile) {&#xA;            this.fragile = fragile;&#xA;            return this;&#xA;        }&#xA;&#xA;        public Builder withId(UUID id) {&#xA;            this.id = id;&#xA;            return this;&#xA;        }&#xA;&#xA;        public GiftResponseDTO build() {&#xA;            GiftResponseDTO responseDTO = new GiftResponseDTO();&#xA;            responseDTO.name = this.name;&#xA;            responseDTO.wrapper = this.wrapper;&#xA;            responseDTO.expensive = this.expensive;&#xA;            responseDTO.fragile = this.fragile;&#xA;            responseDTO.id = this.id;&#xA;            return responseDTO;&#xA;        }&#xA;    }&#xA;}&#xA;Here there is a bit more going on. First off Jackson is instructed to allow protected fields as well. This time there are no getters or so called setters_. There is a Builder class in there though. This is the so named Builder pattern. The gist is to have a static Builder class that you instantiate and all methods except build() will return the instance itself. This causes a Fluent API to emerge where you can in a declarative way set the properties that you need and then even pass around the Builder instance if you wanted to produce carbon copies but separate instances each time by subsequently calling the build() method. The reason for the protected one is because then the Builder can instantiate a new instance of the class GiftResponseDTO and then be allowed to set the properties. &#xA;&#xA;Gift.java&#xA;&#xA;The contents of the Gift.java file are as follows:&#xA;package com.stealthycoder.dto.models.entity;&#xA;&#xA;import org.hibernate.annotations.Type;&#xA;&#xA;import javax.persistence.Entity;&#xA;import javax.persistence.GeneratedValue;&#xA;import javax.persistence.Id;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@Entity&#xA;public class Gift {&#xA;    private UUID id;&#xA;    private String name;&#xA;    private String wrappingPaper;&#xA;    private Boolean expensive;&#xA;    private Boolean fragile;&#xA;&#xA;    @Id&#xA;    @GeneratedValue&#xA;    @Type(type = &#34;uuid-char&#34;)&#xA;    public UUID getId() {&#xA;        return id;&#xA;    }&#xA;&#xA;    public void setId(UUID id) {&#xA;        this.id = id;&#xA;    }&#xA;&#xA;    public String getName() {&#xA;        return name;&#xA;    }&#xA;&#xA;    public void setName(String name) {&#xA;        if (Objects.isNull(this.name) &amp;&amp; Objects.nonNull(name)) {&#xA;            this.name = name;&#xA;        }&#xA;    }&#xA;&#xA;    public String getWrappingPaper() {&#xA;        return wrappingPaper;&#xA;    }&#xA;&#xA;    public void setWrappingPaper(String wrappingPaper) {&#xA;        if (Objects.isNull(this.wrappingPaper) &amp;&amp; Objects.nonNull(wrappingPaper)) {&#xA;            this.wrappingPaper = wrappingPaper;&#xA;        }&#xA;    }&#xA;&#xA;    public boolean isExpensive() {&#xA;        return expensive;&#xA;    }&#xA;&#xA;    public void setExpensive(Boolean expensive) {&#xA;        if (Objects.isNull(this.expensive) &amp;&amp; Objects.nonNull(expensive)) {&#xA;            this.expensive = expensive;&#xA;        }&#xA;    }&#xA;&#xA;    public boolean isFragile() {&#xA;        return fragile;&#xA;    }&#xA;&#xA;    public void setFragile(Boolean fragile) {&#xA;        if (Objects.isNull(this.fragile) &amp;&amp; Objects.nonNull(fragile)) {&#xA;            this.fragile = fragile;&#xA;        }&#xA;    }&#xA;}&#xA;So this class has the Entity annotation to mark it as an entity for the Hibernate framework to do it&#39;s magic. There is a novel approach here by having a sort of immutability by allowing the properties to be only set once. This is because the Entity should reflect the database values and it should be explicit when you want to do updates, not just willy-nilly throughout the services. This is the reason for the usage of the Boolean boxing instead of using boolean. A primitive like boolean will automatically become false in the checking for isNull. &#xA;&#xA;SantaClausService.java&#xA;&#xA;The contents of the SantaClausService.java are as follows:&#xA;package com.stealthycoder.dto.services;&#xA;&#xA;import com.stealthycoder.dto.models.dto.GiftRequestDTO;&#xA;import com.stealthycoder.dto.models.dto.GiftResponseDTO;&#xA;import com.stealthycoder.dto.models.entity.Gift;&#xA;&#xA;import javax.enterprise.context.ApplicationScoped;&#xA;import javax.inject.Inject;&#xA;import javax.persistence.EntityManager;&#xA;import javax.persistence.PersistenceContext;&#xA;import javax.transaction.Transactional;&#xA;import java.util.Objects;&#xA;import java.util.UUID;&#xA;&#xA;@ApplicationScoped&#xA;public final class SantaClausService {&#xA;&#xA;    @PersistenceContext&#xA;    EntityManager em;&#xA;&#xA;    @Transactional&#xA;    public GiftResponseDTO createGift(GiftRequestDTO newGift){&#xA;        Gift gift = fromDTO(newGift);&#xA;        em.persist(gift);&#xA;        return toDTO(gift);&#xA;    }&#xA;&#xA;    @Transactional&#xA;    public GiftResponseDTO updateGift(UUID uuid, GiftRequestDTO updatedGiftDto) {&#xA;        Gift originalGift = em.find(Gift.class, uuid);&#xA;        if (Objects.isNull(originalGift)) {&#xA;            return null;&#xA;        }&#xA;&#xA;        Gift updatedGift = fromDTO(updatedGiftDto);&#xA;        updatedGift.setId(uuid);&#xA;        updatedGift.setWrappingPaper(originalGift.getWrappingPaper());&#xA;        updatedGift.setFragile(originalGift.isFragile());&#xA;        updatedGift.setExpensive(originalGift.isExpensive());&#xA;        updatedGift.setName(originalGift.getName());&#xA;&#xA;        updatedGift = em.merge(updatedGift);&#xA;        em.flush();&#xA;&#xA;        return toDTO(updatedGift);&#xA;    }&#xA;&#xA;    public GiftResponseDTO getGift(UUID uuid) {&#xA;        return toDTO(em.find(Gift.class, uuid));&#xA;    }&#xA;&#xA;    private GiftResponseDTO toDTO(Gift gift) {&#xA;        if (Objects.isNull(gift)) {&#xA;            return null;&#xA;        }&#xA;        return new GiftResponseDTO.Builder()&#xA;                .withName(gift.getName())&#xA;                .withWrapper(gift.getWrappingPaper())&#xA;                .isExpensive(gift.isExpensive())&#xA;                .isFragile(gift.isFragile())&#xA;                .withId(gift.getId())&#xA;                .build();&#xA;    }&#xA;&#xA;    private Gift fromDTO(GiftRequestDTO requestDTO) {&#xA;        Gift gift = new Gift();&#xA;        gift.setName(requestDTO.getName());&#xA;        gift.setExpensive(requestDTO.isExpensive());&#xA;        gift.setFragile(requestDTO.isFragile());&#xA;        gift.setWrappingPaper(requestDTO.getWrapper());&#xA;        return gift;&#xA;    }&#xA;}&#xA;So here is the meat of the whole application basically. There are two helper methods that either take in an Entity and transmogrify it into a DTO or the other way around. Here is where we use the Builder to build the DTO. There is only one place now in the application where GiftResponseDTO classes can be instantiated and therefore after this service nobody can change it. The Gift that comes back from the helper method fromDTO might have properties that still can be set. Namely they can be still null. &#xA;&#xA;The create and get methods are quite self explanatory. The update one might require some more explanation. So we get a DTO and we turn it into a Gift entity. Then we get the one that is currently in the database. That will set the Persistence Context to that object. Then we update the Gift from the DTO to set the properties that were not set yet (i.e. are still null), meaning the properties that were set override the ones in the database. Then the em.merge happens which will give back the representation in the database of the newly updated Gift with the correct properties. Then the em.flush call will make sure this is actually persisted/synchronised with the database. &#xA;&#xA;The Transactional annotations make sure the methods will be transactional and that means if something fails at all, it will not be persisted and rolled back. &#xA;&#xA;Getting started&#xA;&#xA;After you copied all the content and setup the project exactly as is and have Gradle installed, run the following command in the root of the project: gradle quarkusBuild . Then run docker-compose up . Next use your favourite API exploration tool to POST something to http://localhost:8080/gift and see what happens. &#xA;&#xA;Conclusion&#xA;&#xA;I hope that the patterns above can be useful for you when you want to have immutability in Java and in general. I think this pattern is quite powerful as it also makes you think about what you are doing and what you want to change and where and why. This makes it transparent who generates the instances, who mutates them and what is being changed. Also I quite like the novel approach of only allowing to set the properties once. &#xA;&#xA;Also I really like Quarkus. It gives you enough control but still allows for very fast development. It has some cool patterns like Event driven design out of the box as well as Reactive programming. Check out their guides. &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is about why you want immutable objects and how to achieve that in various ways. I specify the language as Java this time because I want to showcase the <a href="https://quarkus.io/" rel="nofollow">Quarkus framework</a>. This pattern can be used in any language and framework combination using the tools available in that language of course. </p>

<h1 id="oracles" id="oracles">Oracles</h1>

<p>Why do objects need to be immutable and what does it even mean? Well to be immutable mean you are not allowed to change a property of the object but you are allowed to assign a whole new reference to the variable for example. Like with <code>String</code> in Java, and with strings in most other languages. You cannot change a part of the String in the middle but you are allowed to assign a new <code>String</code> to a variable declared.</p>

<pre><code class="language-Java">String s = &#34;StealthyCoder&#34;;
s = &#34;Coding Ninjas&#34;; 
</code></pre>

<p>What you want is the fact that <code>s</code>, in this case, will hold a truth and that truth will not easily be changed halfway true except very explicitly.</p>

<p>In this case you want <code>s</code> to be a so called oracle. It needs to be able to tell you what the source of truth is at this specific moment in time.</p>

<h1 id="dtos" id="dtos">DTOs</h1>

<p>In the REST API world, there is a pattern that consists of <strong>DTOs</strong>, <strong>Entities</strong>, <strong>Services</strong> and <strong>Controllers</strong>. In which a <strong>Controller</strong> is responsible for making sure a route has a method associated with it. The <strong>Entities</strong> are responsible for modeling the Database tables. The <strong>Services</strong> are responsible for handling <strong>Entities</strong> and making business logic decisions. The <strong>DTOs</strong> are responsible for being the truthful state of the world.</p>

<p>This leads to stating that <strong>DTOs</strong>, and also to an extent <strong>Entities</strong>, should be immutable as it was just stated that oracles are there to provide truths. In the REST API we will be making, the fact is that whatever the frontend will be sending as an input should be immutable once it is in the backend as we do not want any code to be able to accidentally change something. Also the generation of a response should be once only.</p>

<p>The following project outline and code will provide some examples on how to achieve this using the Quarkus framework.</p>

<h1 id="outline" id="outline">Outline</h1>

<pre><code>├── build.gradle
├── docker-compose.yml
├── Dockerfile
├── gradle.properties
├── settings.gradle
└── src
    └── main
        ├── java
        │   └── com
        │       └── stealthycoder
        │           └── dto
        │               ├── models
        │               │   ├── dto
        │               │   │   ├── GiftRequestDTO.java
        │               │   │   └── GiftResponseDTO.java
        │               │   └── entity
        │               │       └── Gift.java
        │               ├── routes
        │               │   └── gifts
        │               │       └── GiftResource.java
        │               └── services
        │                   └── SantaClausService.java
        └── resources
            └── application.properties
</code></pre>

<h2 id="build-gradle" id="build-gradle">build.gradle</h2>

<p>The contents of the <code>build.gradle</code> file are as follows:</p>

<pre><code class="language-gradle">plugins {
    id &#39;java&#39;
    id &#39;io.quarkus&#39; version &#34;${quarkusVersion}&#34;
}

repositories {
     mavenCentral()
}

test {
  useJUnitPlatform()
}

dependencies {
    implementation &#39;io.quarkus:quarkus-resteasy-jackson&#39;
    implementation &#39;io.quarkus:quarkus-hibernate-orm&#39;
    implementation &#39;io.quarkus:quarkus-jdbc-postgresql&#39;
    implementation enforcedPlatform(&#34;io.quarkus:quarkus-bom:${quarkusVersion}&#34;)

    testImplementation &#39;io.quarkus:quarkus-junit5&#39;
    testImplementation &#39;io.rest-assured:rest-assured&#39;
}
group &#39;com.stealthycoder&#39;
version &#39;0.0.1-SNAPSHOT&#39;

sourceCompatibility = 14
</code></pre>

<p>This just sets up the necessary dependencies for our project and the extensions for Quarkus in order to handle JSON serialization (<em>quarkus-resteasy-jackson</em>) and connect to Postgres (<em>quarkus-jdbc-postgresql</em>) for example.</p>

<h2 id="docker-compose-yml" id="docker-compose-yml">docker-compose.yml</h2>

<p>The contents of the <code>docker-compose.yml</code> file are as follows:</p>

<pre><code class="language-yaml">version: &#39;3.6&#39;

networks:
  quarkus:
    name: quarkus

services:
  api:
    container_name: api.dto.local
    build:
      context: .
      dockerfile: &#39;Dockerfile&#39;
    environment:
      PG_HOST: database
      PG_USER: dto
      PG_PASS: dto
      PG_DATABASE: dto
    ports:
      - &#34;8080:8080&#34;
    networks:
      - quarkus
  database:
    image: postgres:13-alpine
    container_name: db.dto.local
    environment:
      POSTGRES_PASSWORD: dto
      POSTGRES_USER: dto
      POSTGRES_DB: dto
    stdin_open: true
    tty: true
    networks:
      - quarkus
</code></pre>

<p>This sets us up so we have a running container and database we can use locally for our development purposes. I chose to build the image for the API because I was reluctant this time to install Gradle on the docker image or indeed use a ready made Gradle image to run the tooling in there.</p>

<h2 id="dockerfile" id="dockerfile">Dockerfile</h2>

<p>The contents of the <code>Dockerfile</code> are as follows:</p>

<pre><code class="language-dockerfile">FROM adoptopenjdk/openjdk14:alpine-slim

COPY build/com.stealthycoder.dto-0.0.1-SNAPSHOT-runner.jar /srv/http/quarkus.jar
COPY build/lib /srv/http/lib

CMD [&#34;/opt/java/openjdk/bin/java&#34;, &#34;-jar&#34;, &#34;/srv/http/quarkus.jar&#34; ]
</code></pre>

<p>Very straightforward, copy a jar into a named other jar and copy the <code>lib</code> folder as well as it needs that to be able to load the dependencies and start it.
The name of the jar depends on the group name and the structure of the package and of a setting in the <code>settings.gradle</code> file.</p>

<h2 id="gradle-properties" id="gradle-properties">gradle.properties</h2>

<p>The contents of the <code>gradle.properties</code> file is as follows:</p>

<pre><code class="language-ini">quarkusVersion=1.8.1.Final
</code></pre>

<h2 id="settings-gradle" id="settings-gradle">settings.gradle</h2>

<p>The contents of the <code>settings.gradle</code> file are as follows:</p>

<pre><code class="language-gradle">pluginManagement {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
    }
}
rootProject.name = &#39;com.stealthycoder.dto&#39;
</code></pre>

<p>That <em>rootProject.name</em> will mostly determine the naming together with the version of <code>build.gradle</code>.</p>

<h2 id="application-properties" id="application-properties">application.properties</h2>

<p>The contents of the <code>application.properties</code> file are as follows:</p>

<pre><code class="language-ini">quarkus.datasource.db-kind = pg
quarkus.datasource.jdbc.url = jdbc:postgresql://${PG_HOST:localhost}/${PG_DATABASE:database}
quarkus.datasource.username=${PG_USER:user}
quarkus.datasource.password=${PG_PASS:password}
quarkus.hibernate-orm.database.generation=${HIBERNATE_GENERATION:drop-and-create}
quarkus.http.access-log.enabled=true
quarkus.http.access-log.pattern=&#34;%h &#34;%r&#34; %s&#34;
quarkus.resteasy.gzip.enabled=true
quarkus.resteasy.gzip.max-input=10M
</code></pre>

<p>This will set the connection to the database based on <em>Environment</em> variables with some defaults. The <code>HIBERNATE_GENERATION</code> should only be set to <strong>drop-and-create</strong> the very first time you run the application as it will otherwise consistently delete your previous data.</p>

<h2 id="giftresource-java" id="giftresource-java">GiftResource.java</h2>

<p>The contents of the <code>GiftResource.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.routes.gifts;

import com.stealthycoder.dto.models.dto.GiftRequestDTO;
import com.stealthycoder.dto.models.dto.GiftResponseDTO;
import com.stealthycoder.dto.services.SantaClausService;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Objects;
import java.util.UUID;

@Path(&#34;/gift&#34;)
public final class GiftResource {

    @Inject
    SantaClausService service;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path(&#34;{id}&#34;)
    public Response get(@PathParam(&#34;id&#34;) UUID uuid) {
        GiftResponseDTO gift = service.getGift(uuid);
        if (Objects.isNull(gift)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(gift).build();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response add(GiftRequestDTO giftRequestDTO) {
        return Response.ok(service.createGift(giftRequestDTO)).build();
    }

    @PATCH
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path(&#34;{id}&#34;)
    public Response update(@PathParam(&#34;id&#34;) UUID uuid, GiftRequestDTO giftRequestDTO) {
        GiftResponseDTO responseDTO = service.updateGift(uuid, giftRequestDTO);
        if (Objects.isNull(responseDTO)) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(responseDTO).build();
    }

}
</code></pre>

<p>This file will create routes for <em>GET</em>, <em>POST</em> and <em>PATCH</em> on the path <code>/gift</code>. From this we can also determine that the service <code>SantaClausService</code> returns <strong>DTOs</strong> and also accepts <strong>DTOs</strong>. The <code>Produces</code> and <code>Consumes</code> annotations help with making sure the serialization will work alright. So in this case the fact is the method will get an instance of the <code>GiftRequestDTO</code> class to be able to use for further processing.</p>

<h2 id="giftrequestdto-java" id="giftrequestdto-java">GiftRequestDTO.java</h2>

<p>The contents of the <code>GiftRequestDTO.java</code> file are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.dto;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public final class GiftRequestDTO {
    private String name;
    private String wrapper;
    private boolean expensive;
    private boolean fragile;

    public String getName(){
        return name;
    }

    public String getWrapper() {
        return wrapper;
    }

    public boolean isExpensive() {
        return expensive;
    }

    public boolean isFragile() {
        return fragile;
    }
}
</code></pre>

<p>The important bits to note are the fields are all <strong><code>private</code></strong>. Another is that there are only so called <em><strong>getters</strong></em> . The thing that ties it all together is to tell Jackson to <em>allow</em> to use reflection on all fields so it can set even private fields to values. This is what will make the DTO immutable for further processing. Of course there are ways around this as it was just stated that even Jackson can do mutations to private fields. Also the class is marked as <code>final</code> meaning you cannot extend it in some way and therefore cast it and still make changes.</p>

<h2 id="giftresponsedto-java" id="giftresponsedto-java">GiftResponseDTO.java</h2>

<p>The contents of the <code>GiftResponseDTO.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.dto;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import java.util.UUID;

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)
public final class GiftResponseDTO {
    protected UUID id;
    protected String name;
    protected String wrapper;
    protected boolean expensive;
    protected boolean fragile;

    public final static class Builder {
        private String name;
        private String wrapper;
        private boolean expensive;
        private boolean fragile;
        private UUID id;

        public Builder withName(String name) {
            this.name = name;
            return this;
        }

        public Builder withWrapper(String wrapper) {
            this.wrapper = wrapper;
            return this;
        }

        public Builder isExpensive(boolean expensive) {
            this.expensive = expensive;
            return this;
        }

        public Builder isFragile(boolean fragile) {
            this.fragile = fragile;
            return this;
        }

        public Builder withId(UUID id) {
            this.id = id;
            return this;
        }

        public GiftResponseDTO build() {
            GiftResponseDTO responseDTO = new GiftResponseDTO();
            responseDTO.name = this.name;
            responseDTO.wrapper = this.wrapper;
            responseDTO.expensive = this.expensive;
            responseDTO.fragile = this.fragile;
            responseDTO.id = this.id;
            return responseDTO;
        }
    }
}
</code></pre>

<p>Here there is a bit more going on. First off Jackson is instructed to allow protected fields as well. This time there are no <em><strong>getters</strong></em> or so called <em><strong>setters</strong></em>. There is a Builder class in there though. This is the so named Builder pattern. The gist is to have a static Builder class that you instantiate and all methods except <code>build()</code> will return the instance itself. This causes a Fluent API to emerge where you can in a declarative way set the properties that you need and then even pass around the Builder instance if you wanted to produce carbon copies but separate instances each time by subsequently calling the <code>build()</code> method. The reason for the protected one is because then the Builder can instantiate a new instance of the class <code>GiftResponseDTO</code> and then be allowed to set the properties.</p>

<h2 id="gift-java" id="gift-java">Gift.java</h2>

<p>The contents of the <code>Gift.java</code> file are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.models.entity;

import org.hibernate.annotations.Type;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Objects;
import java.util.UUID;

@Entity
public class Gift {
    private UUID id;
    private String name;
    private String wrappingPaper;
    private Boolean expensive;
    private Boolean fragile;


    @Id
    @GeneratedValue
    @Type(type = &#34;uuid-char&#34;)
    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (Objects.isNull(this.name) &amp;&amp; Objects.nonNull(name)) {
            this.name = name;
        }
    }

    public String getWrappingPaper() {
        return wrappingPaper;
    }

    public void setWrappingPaper(String wrappingPaper) {
        if (Objects.isNull(this.wrappingPaper) &amp;&amp; Objects.nonNull(wrappingPaper)) {
            this.wrappingPaper = wrappingPaper;
        }
    }

    public boolean isExpensive() {
        return expensive;
    }

    public void setExpensive(Boolean expensive) {
        if (Objects.isNull(this.expensive) &amp;&amp; Objects.nonNull(expensive)) {
            this.expensive = expensive;
        }
    }

    public boolean isFragile() {
        return fragile;
    }

    public void setFragile(Boolean fragile) {
        if (Objects.isNull(this.fragile) &amp;&amp; Objects.nonNull(fragile)) {
            this.fragile = fragile;
        }
    }
}
</code></pre>

<p>So this class has the <code>Entity</code> annotation to mark it as an entity for the Hibernate framework to do it&#39;s magic. There is a novel approach here by having a sort of immutability by allowing the properties to be only set once. This is because the <strong>Entity</strong> should reflect the database values and it should be explicit when you want to do updates, not just willy-nilly throughout the services. This is the reason for the usage of the <code>Boolean</code> boxing instead of using <code>boolean</code>. A primitive like <code>boolean</code> will automatically become <code>false</code> in the checking for <code>isNull</code>.</p>

<h2 id="santaclausservice-java" id="santaclausservice-java">SantaClausService.java</h2>

<p>The contents of the <code>SantaClausService.java</code> are as follows:</p>

<pre><code class="language-Java">package com.stealthycoder.dto.services;

import com.stealthycoder.dto.models.dto.GiftRequestDTO;
import com.stealthycoder.dto.models.dto.GiftResponseDTO;
import com.stealthycoder.dto.models.entity.Gift;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.Objects;
import java.util.UUID;

@ApplicationScoped
public final class SantaClausService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public GiftResponseDTO createGift(GiftRequestDTO newGift){
        Gift gift = fromDTO(newGift);
        em.persist(gift);
        return toDTO(gift);
    }

    @Transactional
    public GiftResponseDTO updateGift(UUID uuid, GiftRequestDTO updatedGiftDto) {
        Gift originalGift = em.find(Gift.class, uuid);
        if (Objects.isNull(originalGift)) {
            return null;
        }

        Gift updatedGift = fromDTO(updatedGiftDto);
        updatedGift.setId(uuid);
        updatedGift.setWrappingPaper(originalGift.getWrappingPaper());
        updatedGift.setFragile(originalGift.isFragile());
        updatedGift.setExpensive(originalGift.isExpensive());
        updatedGift.setName(originalGift.getName());

        updatedGift = em.merge(updatedGift);
        em.flush();

        return toDTO(updatedGift);
    }

    public GiftResponseDTO getGift(UUID uuid) {
        return toDTO(em.find(Gift.class, uuid));
    }

    private GiftResponseDTO toDTO(Gift gift) {
        if (Objects.isNull(gift)) {
            return null;
        }
        return new GiftResponseDTO.Builder()
                .withName(gift.getName())
                .withWrapper(gift.getWrappingPaper())
                .isExpensive(gift.isExpensive())
                .isFragile(gift.isFragile())
                .withId(gift.getId())
                .build();
    }

    private Gift fromDTO(GiftRequestDTO requestDTO) {
        Gift gift = new Gift();
        gift.setName(requestDTO.getName());
        gift.setExpensive(requestDTO.isExpensive());
        gift.setFragile(requestDTO.isFragile());
        gift.setWrappingPaper(requestDTO.getWrapper());
        return gift;
    }
}
</code></pre>

<p>So here is the meat of the whole application basically. There are two helper methods that either take in an Entity and transmogrify it into a DTO or the other way around. Here is where we use the Builder to build the DTO. There is only one place now in the application where <code>GiftResponseDTO</code> classes can be instantiated and therefore after this service nobody can change it. The Gift that comes back from the helper method <code>fromDTO</code> might have properties that still can be set. Namely they can be still <code>null</code>.</p>

<p>The <strong>create</strong> and <strong>get</strong> methods are quite self explanatory. The <strong>update</strong> one might require some more explanation. So we get a DTO and we turn it into a Gift entity. Then we get the one that is currently in the database. That will set the Persistence Context to that object. Then we update the Gift from the DTO to set the properties that were not set yet (i.e. are still <code>null</code>), meaning the properties that were set override the ones in the database. Then the <code>em.merge</code> happens which will give back the representation in the database of the newly updated Gift with the correct properties. Then the <code>em.flush</code> call will make sure this is actually persisted/synchronised with the database.</p>

<p>The <code>Transactional</code> annotations make sure the methods will be transactional and that means if something fails at all, it will not be persisted and rolled back.</p>

<h1 id="getting-started" id="getting-started">Getting started</h1>

<p>After you copied all the content and setup the project exactly as is and have <a href="https://gradle.org/" rel="nofollow">Gradle</a> installed, run the following command in the root of the project: <code>gradle quarkusBuild</code> . Then run <code>docker-compose up</code> . Next use your favourite API exploration tool to <code>POST</code> something to <code>http://localhost:8080/gift</code> and see what happens.</p>

<h1 id="conclusion" id="conclusion">Conclusion</h1>

<p>I hope that the patterns above can be useful for you when you want to have immutability in Java and in general. I think this pattern is quite powerful as it also makes you think about what you are doing and what you want to change and where and why. This makes it transparent who generates the instances, who mutates them and what is being changed. Also I quite like the novel approach of only allowing to set the properties once.</p>

<p>Also I really like Quarkus. It gives you enough control but still allows for very fast development. It has some cool patterns like Event driven design out of the box as well as Reactive programming. Check out their <a href="https://quarkus.io/guides/" rel="nofollow">guides</a>.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/truths-in-java</guid>
      <pubDate>Tue, 06 Oct 2020 14:14:20 +0000</pubDate>
    </item>
    <item>
      <title>Quirky, weird and fun pattern for Java</title>
      <link>https://stealthycoder.writeas.com/quirky-weird-and-fun-pattern-for-java?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[To be honest I have no idea what you can do with the following pattern and if it is good at all. It just a thought I had and it felt like there was something there, so I decided to write it down. Hopefully you can use the following pattern for something. !--more--&#xA;&#xA;import java.util.function.Supplier;&#xA;import java.util.UUID;&#xA;&#xA;public class Quirky {&#xA;  private SupplierUUID id;&#xA;  private SupplierString name;&#xA;&#xA;  public SupplierUUID getId() {&#xA;    return this.id;&#xA;  }&#xA;&#xA;  public SupplierString getName() {&#xA;    return this.name;&#xA;  }&#xA;&#xA;  public void setId(UUID id) {&#xA;    this.id = () -  { return id; };&#xA;  }&#xA;&#xA;  public void setId(SupplierUUID id) {&#xA;    this.id = id;&#xA;  }&#xA;&#xA;  public void setName(String name) {&#xA;    this.name = () -  { return name; };&#xA;  }&#xA;&#xA;  public void setName(SupplierString name) {&#xA;    this.name = name;&#xA;  }&#xA;&#xA;}&#xA;&#xA;The idea was to turn the properties into Suppliers and therefore you would get to do some functional style flows. I am not sure yet how it will fit in with other patterns. For example to set the id you would do :&#xA;Quirky q = new Quirky();&#xA;q.setId(UUID.randomUUID());&#xA;&#xA;Then to retrieve the id you would do :&#xA;&#xA;q.getId().get();&#xA;&#xA;There is the fact you have to do double gets that feel weird. If you wanted to make a random Quirky you could do the following:&#xA;&#xA;Quirky q = new Quirky();&#xA;q.setId(() -  { return UUID.randomUUID();});&#xA;Then every following call to getId().get() will return a new UUID. &#xA;&#xA;One thing I did want to implement were the double setters . One will wrap a value into a simple supplier but you could also augment that. &#xA;&#xA;public void setName(String name) {&#xA;    this.name = () -  { return name.toUpperCase(); };&#xA;  }&#xA;Now the normal method will always return all caps. There can also be logging and other side effects. &#xA;&#xA;Hopefully you will read this and think of something somewhere to use it. Also I have the feeling somewhere functional programmers woke up and are going to bombard me with Monads, Functors and similar corrigenda.  &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>To be honest I have no idea what you can do with the following pattern and if it is good at all. It just a thought I had and it felt like there was something there, so I decided to write it down. Hopefully you can use the following pattern for something. </p>

<pre><code class="language-Java">import java.util.function.Supplier;
import java.util.UUID;


public class Quirky {
  private Supplier&lt;UUID&gt; id;
  private Supplier&lt;String&gt; name;


  public Supplier&lt;UUID&gt; getId() {
    return this.id;
  }

  public Supplier&lt;String&gt; getName() {
    return this.name;
  }

  public void setId(UUID id) {
    this.id = () -&gt; { return id; };
  }

  public void setId(Supplier&lt;UUID&gt; id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = () -&gt; { return name; };
  }

  public void setName(Supplier&lt;String&gt; name) {
    this.name = name;
  }

}

</code></pre>

<p>The idea was to turn the properties into <code>Supplier</code>s and therefore you would get to do some functional style flows. I am not sure yet how it will fit in with other patterns. For example to set the id you would do :</p>

<pre><code class="language-Java">Quirky q = new Quirky();
q.setId(UUID.randomUUID());
</code></pre>

<p>Then to retrieve the id you would do :</p>

<pre><code class="language-Java">q.getId().get();
</code></pre>

<p>There is the fact you have to do double <strong>get</strong>s that feel weird. If you wanted to make a random Quirky you could do the following:</p>

<pre><code class="language-Java">Quirky q = new Quirky();
q.setId(() -&gt; { return UUID.randomUUID();});
</code></pre>

<p>Then every following call to <code>getId().get()</code> will return a new UUID.</p>

<p>One thing I did want to implement were the double <em>setters</em> . One will wrap a value into a simple supplier but you could also augment that.</p>

<pre><code class="language-Java">public void setName(String name) {
    this.name = () -&gt; { return name.toUpperCase(); };
  }
</code></pre>

<p>Now the normal method will always return all caps. There can also be logging and other side effects.</p>

<p>Hopefully you will read this and think of something somewhere to use it. Also I have the feeling somewhere functional programmers woke up and are going to bombard me with Monads, Functors and similar corrigenda.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/quirky-weird-and-fun-pattern-for-java</guid>
      <pubDate>Tue, 06 Oct 2020 22:01:43 +0000</pubDate>
    </item>
    <item>
      <title>Powerful concept: FunctionMap</title>
      <link>https://stealthycoder.writeas.com/powerful-concept-functionmap?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This idea comes from JavaScript when there were no classes yet as there are now in ES6. You would write something like this: !--more--&#xA;&#xA;var greetings = {&#xA; hello: function() { console.info(&#34;Hello&#34;); }&#xA;};&#xA;greetings.hello();&#xA;greetings&#34;hello&#34;;&#xA;This is how functions could be shipped around. So the idea is simple, especially the second one. I started to wonder if we can have a Map of String -  Function in other languages like Java, Python, PHP and more?&#xA;&#xA;Java&#xA;&#xA;We sure can. I was working on a JSON-RPC project where you don&#39;t send entity bodies but you send what method to invoke and with what arguments. In the backend we made it so internally a consistent object was shipped around (RPCServiceResult) and we had Enum for the methods that were allowed. So I set up an EnumMap of Enum -  Function. This made it so the entrypoint of each service was the same. See if the method key exists, if so execute the corresponding function with the given input otherwise throw a MethodNotFound error. This meant we could extend the Enum and EnumMap and the Function mapping but never had to change how the services called each other. &#xA;&#xA;Python&#xA;&#xA;In Python I was working on a silly hacking simulation game in the Console. I wanted to have a list of commands and execute the corresponding function that was that command in game terms. At this point I just came from PHP and there it is completely normal to execute the string itself. I will come back to this in a bit. This is more difficult to do in Python and so I came up with a dict where command name was the key and function references were the values. This made it super simple to maintain. &#xA;&#xA;PHP&#xA;&#xA;So in PHP this is normal:&#xA;function a(){ echo &#34;A&#34;; };&#xA;$a = &#34;a&#34;;&#xA;$a();&#xA;However it is really difficult to maintain and see what is going on, let alone insecure to do this if the input to $a is user input. The following makes more sense and is easier to maintain.&#xA;&#xA;function a() { echo &#34;A&#34;; };&#xA;$commands = [&#34;a&#34; =  function() { calluserfunc(&#34;a&#34;); }];&#xA;if ( arraykeyexists(&#34;a&#34;, $commands) ) { $commands&#34;a&#34;; }&#xA;&#xA;Granted this is a contrived example but I hope it gets the point across. &#xA;&#xA;Scala&#xA;&#xA;I was working on the Advent of Code 2020 and one of the puzzles had a lot of validation rules. Immediately the structure came to mind of having a Map of Functions, for each field to validate the corresponding function. This worked like a charm and it is very easy to see what each rule does. &#xA;&#xA;Java&#xA;&#xA;Another example was that in a particular flow there was a need to either create a User of type A or type B and then continue the flow. It was first like the following:&#xA;if ( type == &#34;UserA&#34; ) {&#xA;    return new UserA();&#xA;} else {&#xA;    return new UserB();&#xA;}&#xA;Now never mind the bug of always returning type B, I suggested the following:&#xA;MapString, Supplier&lt;User  userSupplier = new HashMap(){{ put(&#34;UserA&#34;, UserA::new); put(&#34;UserB&#34;, UserB::new); }};&#xA;Now you could replace it with one entrypoint:&#xA;return userSupplier.getOrDefault(type, UserB::new).get();&#xA;You still have the bug, but it became a feature. So we leave it in.&#xA;The colleague immediately said, this happens in way more places in the code and I can change all of them. &#xA;&#xA;The nice thing again is, we can extend the map to support more types but it does not change the logic of calling the service.&#xA;&#xA;Conclusion&#xA;&#xA;I hope this concept proves useful to you, I find it quite powerful and easy to construct and it gives lots of nice patterns. &#xA;&#xA;#code #javascript #java #python]]&gt;</description>
      <content:encoded><![CDATA[<p>This idea comes from JavaScript when there were no classes yet as there are now in ES6. You would write something like this: </p>

<pre><code class="language-javascript">var greetings = {
 hello: function() { console.info(&#34;Hello&#34;); }
};
greetings.hello();
greetings[&#34;hello&#34;]();
</code></pre>

<p>This is how functions could be shipped around. So the idea is simple, especially the second one. I started to wonder if we can have a <code>Map</code> of <code>String -&gt; Function</code> in other languages like Java, Python, PHP and more?</p>

<h1 id="java" id="java">Java</h1>

<p>We sure can. I was working on a JSON-RPC project where you don&#39;t send entity bodies but you send what method to invoke and with what arguments. In the backend we made it so internally a consistent object was shipped around (<code>RPCServiceResult</code>) and we had <code>Enum</code> for the methods that were allowed. So I set up an <code>EnumMap</code> of <code>Enum -&gt; Function</code>. This made it so the entrypoint of each service was the same. See if the method key exists, if so execute the corresponding function with the given input otherwise throw a <code>MethodNotFound</code> error. This meant we could extend the Enum and EnumMap and the Function mapping but never had to change how the services called each other.</p>

<h1 id="python" id="python">Python</h1>

<p>In Python I was working on a silly hacking simulation game in the Console. I wanted to have a list of commands and execute the corresponding function that was that command in game terms. At this point I just came from PHP and there it is completely normal to execute the string itself. I will come back to this in a bit. This is more difficult to do in Python and so I came up with a dict where command name was the key and function references were the values. This made it super simple to maintain.</p>

<h1 id="php" id="php">PHP</h1>

<p>So in PHP this is normal:</p>

<pre><code class="language-php">function a(){ echo &#34;A&#34;; };
$a = &#34;a&#34;;
$a();
</code></pre>

<p>However it is really difficult to maintain and see what is going on, let alone insecure to do this if the input to <code>$a</code> is user input. The following makes more sense and is easier to maintain.</p>

<pre><code class="language-php">function a() { echo &#34;A&#34;; };
$commands = [&#34;a&#34; =&gt; function() { call_user_func(&#34;a&#34;); }];
if ( array_key_exists(&#34;a&#34;, $commands) ) { $commands[&#34;a&#34;](); }
</code></pre>

<p>Granted this is a contrived example but I hope it gets the point across.</p>

<h1 id="scala" id="scala">Scala</h1>

<p>I was working on the Advent of Code 2020 and one of the puzzles had a lot of validation rules. Immediately the structure came to mind of having a Map of Functions, for each field to validate the corresponding function. This worked like a charm and it is very easy to see what each rule does.</p>

<h1 id="java-1" id="java-1">Java</h1>

<p>Another example was that in a particular flow there was a need to either create a User of type A or type B and then continue the flow. It was first like the following:</p>

<pre><code class="language-java">if ( type == &#34;UserA&#34; ) {
    return new UserA();
} else {
    return new UserB();
}
</code></pre>

<p>Now never mind the bug of always returning type B, I suggested the following:</p>

<pre><code class="language-java">Map&lt;String, Supplier&lt;User&gt;&gt; userSupplier = new HashMap&lt;&gt;(){{ put(&#34;UserA&#34;, UserA::new); put(&#34;UserB&#34;, UserB::new); }};
</code></pre>

<p>Now you could replace it with one entrypoint:</p>

<pre><code class="language-java">return userSupplier.getOrDefault(type, UserB::new).get();
</code></pre>

<p>You still have the bug, but it became a feature. So we leave it in.
The colleague immediately said, this happens in way more places in the code and I can change all of them.</p>

<p>The nice thing again is, we can extend the map to support more types but it does not change the logic of calling the service.</p>

<h1 id="conclusion" id="conclusion">Conclusion</h1>

<p>I hope this concept proves useful to you, I find it quite powerful and easy to construct and it gives lots of nice patterns.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:javascript" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">javascript</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a> <a href="https://stealthycoder.writeas.com/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/powerful-concept-functionmap</guid>
      <pubDate>Mon, 07 Dec 2020 23:10:38 +0000</pubDate>
    </item>
    <item>
      <title>Powerful Concept: Let others do the work</title>
      <link>https://stealthycoder.writeas.com/powerful-concept-let-others-do-the-work?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[So this will hopefully convey the message on how to model your code in order to have things done in a nicer way. !--more--&#xA;&#xA;Let&#39;s say you are building an object, you have the materials ready to build it and at some step you have to ask another party for some information. Based on that information you will either add a piece or not to your build. &#xA;&#xA;This means you have to also know the domain knowledge of what that third party knows and also how to attach it to your build. For every one of these kind of steps. &#xA;&#xA;Would it not be nicer to just hand off the build sign an agreement that party is responsible the time it is in their care and have them give it back with or without modifications depending on the same information you had before. &#xA;&#xA;Of course it would be nice to understand what is going on at the party in order to maintain it yourself, but let us just say that it is free forever to have the party maintain your build.&#xA;&#xA;Now in code&#xA;&#xA;Now in code we can do the same, even in Java where everything is passed by value. Just make sure to wrap it in something, a POJO for example or basically anything that is a class instance.&#xA;&#xA;First the normal way of doing things:&#xA;var l = new ArrayListString();&#xA;&#xA;if (l.isEmpty()) {  &#xA;   l.add(&#34;s&#34;);&#xA;}&#xA;if (l.contains(&#34;s&#34;)) {&#xA;     l.removeAll(&#34;s&#34;);&#xA;     l.add(&#34;x&#34;);&#xA;}&#xA;&#xA;Is this a contrived example of course it is. &#xA;&#xA;So we ask first if it is empty then add something. Then otherwise we remove and add elements if it does contain something. What if we did something like the following:&#xA;var l = new ArrayListString();&#xA;&#xA;ConsumerList&lt;String  ifEmptyAddS = (l) -  { var b = l.isEmpty() &amp;&amp; l.add(&#34;s&#34;); };&#xA;ConsumerList&lt;String  removeAllSAddX = (l) -  { l.removeAll(l.stream().filter(s -  s.equalsIgnoreCase(&#34;s&#34;)).collect(Collectors.toList())); l.add(&#34;x&#34;);};&#xA;&#xA;ifEmptyAddS.andThen(removeAllSAddX).accept(l);&#xA;&#xA;Now we just hand over the whole list over to the party and have them operate on it. The flow is very easily managed and if the naming is chosen a bit nicely you can read it out and just see what is going on. Like for example, why is removeAllSAddX doing it in such a complicated way? You can change that if needed, but it works and it might be better for future proofing the process according to them.&#xA;&#xA;It also makes it so you are responsible for making sure the right persons in the right order get your build but they are all responsible for what they do to it. That is a nice separation of concerns. &#xA;&#xA;#devlife #code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>So this will hopefully convey the message on how to model your code in order to have things done in a nicer way. </p>

<p>Let&#39;s say you are building an object, you have the materials ready to build it and at some step you have to ask another party for some information. Based on that information you will either add a piece or not to your build.</p>

<p>This means you have to also know the domain knowledge of what that third party knows and also how to attach it to your build. For every one of these kind of steps.</p>

<p>Would it not be nicer to just hand off the build sign an agreement that party is responsible the time it is in their care and have them give it back with or without modifications depending on the same information you had before.</p>

<p>Of course it would be nice to understand what is going on at the party in order to maintain it yourself, but let us just say that it is free forever to have the party maintain your build.</p>

<h1 id="now-in-code" id="now-in-code">Now in code</h1>

<p>Now in code we can do the same, even in Java where everything is passed by value. Just make sure to wrap it in something, a POJO for example or basically anything that is a class instance.</p>

<p>First the normal way of doing things:</p>

<pre><code class="language-Java">var l = new ArrayList&lt;String&gt;();

if (l.isEmpty()) {  
   l.add(&#34;s&#34;);
}
if (l.contains(&#34;s&#34;)) {
     l.removeAll(&#34;s&#34;);
     l.add(&#34;x&#34;);
}

</code></pre>

<p>Is this a contrived example of course it is.</p>

<p>So we ask first if it is empty then add something. Then otherwise we remove and add elements if it does contain something. What if we did something like the following:</p>

<pre><code class="language-Java">var l = new ArrayList&lt;String&gt;();

Consumer&lt;List&lt;String&gt;&gt; ifEmptyAddS = (l) -&gt; { var b = l.isEmpty() &amp;&amp; l.add(&#34;s&#34;); };
Consumer&lt;List&lt;String&gt;&gt; removeAllSAddX = (l) -&gt; { l.removeAll(l.stream().filter(s -&gt; s.equalsIgnoreCase(&#34;s&#34;)).collect(Collectors.toList())); l.add(&#34;x&#34;);};

ifEmptyAddS.andThen(removeAllSAddX).accept(l);
</code></pre>

<p>Now we just hand over the whole list over to the party and have them operate on it. The flow is very easily managed and if the naming is chosen a bit nicely you can read it out and just see what is going on. Like for example, why is <code>removeAllSAddX</code> doing it in such a complicated way? You can change that if needed, but it works and it might be better for future proofing the process according to them.</p>

<p>It also makes it so you are responsible for making sure the right persons in the right order get your build but they are all responsible for what they do to it. That is a nice separation of concerns.</p>

<p><a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/powerful-concept-let-others-do-the-work</guid>
      <pubDate>Thu, 10 Dec 2020 22:26:43 +0000</pubDate>
    </item>
    <item>
      <title>WebFlux is not for the faint of heart</title>
      <link>https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I started a project recently using Spring WebFlux which is based upon Project Reactor. I chose this one because it was new and I thought for the client it would suit the best as a lot of data was involved. !--more--&#xA;&#xA;Reactive Programming&#xA;&#xA;The concept this framework is based on is reactive programming. This means you effectively set up conveyor belts on which data will sit and be passed around a factory as part of a chain of operations that will make the raw material into the end product you want. &#xA;&#xA;You get the record from the database, pass it along to the service to transform it into a DTO and then pass it to the controller that transforms it into a HTTPResponse for example. &#xA;&#xA;All of this is non blocking I/O. From the database to the response to the user. This means the CPU is always doing something to progress one process or another. I quite liked this feature. The problem is building these conveyor belts.&#xA;&#xA;Data flow&#xA;&#xA;The flow is sometimes difficult to visualise. It does not help that you can only start flows buy so called subscribing. Then sometimes you want to do two things with the data at two different places but you cannot easily do that. In normal non reactive programming you would for example create a variable that holds some data and send that data to two functions. You could do that asynchronous with CompletableFuture or just regular old synchronous. &#xA;&#xA;I had a hard time grasping every thing and sometimes when things did not work it was because of the flow being wrong or incorrect. Especially when handling errors and stopping the flow. I learned you should handle errors and then send along nulls for example as the next one will not get the null. Optionals might also work but provides more work checking it later in the flow, downstream. &#xA;&#xA;Keep it small&#xA;&#xA;If you keep the functions themselves as small as possible and named correctly you can at least read the flow in a understandable way. It is also important to make it simple at the top and more and more complex the deeper you go. This means if you understand abstractly what needs to happen and then it does not happen you go one layer deeper. Usually the lowest level is fine, i.e. getting the data from some resource. The top level is usually also fine, i.e. sending the response to the user. &#xA;&#xA;It is that middle bit where you do the transformations and business logic where it seems to often go awry. &#xA;&#xA;Adding new functionality to an existing flow is simple and complex at the same time. You have to make sure you give back the same output as before or make sure the input of the next step gets adjusted. It makes it quite finicky to correctly in one try insert new steps. &#xA;&#xA;I would recommend it to at least try out. It might not suit your style, but it does give some great concepts in structuring your application and data flows.&#xA;&#xA;#devlife #code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>I started a project recently using <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux" rel="nofollow">Spring WebFlux</a> which is based upon <a href="https://projectreactor.io/" rel="nofollow">Project Reactor</a>. I chose this one because it was new and I thought for the client it would suit the best as a lot of data was involved. </p>

<h1 id="reactive-programming" id="reactive-programming">Reactive Programming</h1>

<p>The concept this framework is based on is reactive programming. This means you effectively set up conveyor belts on which data will sit and be passed around a factory as part of a chain of operations that will make the raw material into the end product you want.</p>

<p>You get the record from the database, pass it along to the service to transform it into a <code>DTO</code> and then pass it to the controller that transforms it into a <code>HTTPResponse</code> for example.</p>

<p>All of this is non blocking I/O. From the database to the response to the user. This means the CPU is always doing something to progress one process or another. I quite liked this feature. The problem is building these conveyor belts.</p>

<h1 id="data-flow" id="data-flow">Data flow</h1>

<p>The flow is sometimes difficult to visualise. It does not help that you can only start flows buy so called subscribing. Then sometimes you want to do two things with the data at two different places but you cannot easily do that. In normal non reactive programming you would for example create a variable that holds some data and send that data to two functions. You could do that asynchronous with <code>CompletableFuture</code> or just regular old synchronous.</p>

<p>I had a hard time grasping every thing and sometimes when things did not work it was because of the flow being wrong or incorrect. Especially when handling errors and stopping the flow. I learned you should handle errors and then send along <code>null</code>s for example as the next one will not get the <code>null</code>. <code>Optional</code>s might also work but provides more work checking it later in the flow, downstream.</p>

<h1 id="keep-it-small" id="keep-it-small">Keep it small</h1>

<p>If you keep the functions themselves as small as possible and named correctly you can at least read the flow in a understandable way. It is also important to make it simple at the top and more and more complex the deeper you go. This means if you understand abstractly what needs to happen and then it does not happen you go one layer deeper. Usually the lowest level is fine, i.e. getting the data from some resource. The top level is usually also fine, i.e. sending the response to the user.</p>

<p>It is that middle bit where you do the transformations and business logic where it seems to often go awry.</p>

<p>Adding new functionality to an existing flow is simple and complex at the same time. You have to make sure you give back the same output as before or make sure the input of the next step gets adjusted. It makes it quite finicky to correctly in one try insert new steps.</p>

<p>I would recommend it to at least try out. It might not suit your style, but it does give some great concepts in structuring your application and data flows.</p>

<p><a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart</guid>
      <pubDate>Thu, 14 Jan 2021 09:48:01 +0000</pubDate>
    </item>
    <item>
      <title>Spring WebFlux Hidden thoughts</title>
      <link>https://stealthycoder.writeas.com/spring-webflux-hidden-thoughts?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[So I recently started using Spring WebFlux and Project Reactor as stated in this post. One more thing I came across as I was debugging why a certain job was not running was that if you do not catch all exceptions and do not have a doOnError statement it will just keep that thought hidden from you and all to itself.  !--more--&#xA;&#xA;Then I sprinkled some log() statements around and it surfaced that the data import/export I was doing had some unfortunate data that Long.parseLong() did not agree with and threw a NumberFormatException. That however was nowhere in my code to catch and so it failed silently. &#xA;&#xA;This meant I could see the job starting and for all intents and purposes see it do nothing afterwards. &#xA;&#xA;Lesson learned, always have a doOnError on each of your flows. &#xA;&#xA;#code #devops #java]]&gt;</description>
      <content:encoded><![CDATA[<p>So I recently started using Spring WebFlux and Project Reactor as stated in <a href="https://stealthycoder.writeas.com/webflux-is-not-for-the-faint-of-heart" rel="nofollow">this</a> post. One more thing I came across as I was debugging why a certain job was not running was that if you do not catch all exceptions and do not have a <code>doOnError</code> statement it will just keep that thought hidden from you and all to itself.  </p>

<p>Then I sprinkled some <code>log()</code> statements around and it surfaced that the data import/export I was doing had some unfortunate data that <code>Long.parseLong()</code> did not agree with and threw a <code>NumberFormatException</code>. That however was nowhere in my code to catch and so it failed silently.</p>

<p>This meant I could see the job starting and for all intents and purposes see it do nothing afterwards.</p>

<p>Lesson learned, always have a <code>doOnError</code> on each of your flows.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:devops" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devops</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/spring-webflux-hidden-thoughts</guid>
      <pubDate>Tue, 19 Jan 2021 22:35:10 +0000</pubDate>
    </item>
    <item>
      <title>Flow like water diverted</title>
      <link>https://stealthycoder.writeas.com/flow-like-water-diverted?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I have gotten some experience using the Flow constructs in a real scenario and learned some lessons. Therefore I wanted to make some code changes to my original design. !--more--&#xA;&#xA;Integer Subscription&#xA;&#xA;In the subscription we will use a internal ExecutorService to handle the input.&#xA;&#xA;import publishers.IntegerPublisher;&#xA;import java.util.Iterator;&#xA;import java.util.concurrent.ExecutorService;&#xA;import java.util.concurrent.Executors;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.concurrent.TimeUnit;&#xA;import java.util.stream.Stream;&#xA;&#xA;public class IntegerSubscription implements Flow.Subscription  {&#xA;&#xA;    private IntegerPublisher integerPublisher;&#xA;    private IteratorInteger integerStream;&#xA;    private final AtomicBoolean isCanceled = new AtomicBoolean();&#xA;    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());&#xA;&#xA;    public IntegerSubscription(IntegerPublisher integerPublisher) {&#xA;        this.integerPublisher = integerPublisher;&#xA;        this.integerStream = Stream.iterate(2, i -  i + 1).iterator();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void request(long l) {&#xA;        if ( l &lt; 0) {&#xA;            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));&#xA;        }&#xA;        executorService.submit(this.handleRequests(l));&#xA;        &#xA;    }&#xA;&#xA;    private Runnable handleRequests(long l) {&#xA;        return () -  {&#xA;            for (long i = 0; i &lt; l; i++) {&#xA;                if (isCanceled.get()) {&#xA;                    break;&#xA;                }&#xA;                integerPublisher.publish(integerStream.next());&#xA;            }&#xA;        };&#xA;    }&#xA;&#xA;    @Override&#xA;    public void cancel() {&#xA;        isCanceled.set(true);&#xA;        executorService.shutdown();&#xA;        try {&#xA;            executorService.awaitTermination(5L, TimeUnit.SECONDS);&#xA;        } catch (InterruptedException e) {&#xA;            e.printStackTrace();&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;Publisher&#xA;&#xA;In the publisher take out the executorService parts. One of the major problems was actually that the publisher itself was on the executorService somewhere and so it would never shutdown. Also I did not call the onComplete and therefore the executorService would not shutdown correctly either.&#xA;&#xA;import CyclicRingBuffer;&#xA;import subscriptions.IntegerSubscription;&#xA;&#xA;import java.util.Objects;&#xA;import java.util.concurrent.;&#xA;&#xA;public class IntegerPublisherImpl implements IntegerPublisher  {&#xA;&#xA;    private final IntegerSubscription subscription;&#xA;    private final CyclicRingBufferFlow.Subscriber&lt;? super Integer  subscribers;&#xA;&#xA;    public IntegerPublisherImpl() {&#xA;        this.subscription = new IntegerSubscription(this);&#xA;        subscribers = new CyclicRingBuffer();&#xA;    }&#xA;&#xA;    @Override&#xA;    public void subscribe(Flow.Subscriber? super Integer subscriber) {&#xA;        subscribers.push(subscriber);&#xA;        subscriber.onSubscribe(this.subscription);&#xA;    }&#xA;&#xA;    private void shutdown(boolean cancel) {&#xA;        if (cancel) {&#xA;            this.subscription.cancel();&#xA;        } &#xA;        for (Flow.Subscriber? super Integer subscriber : subscribers) {&#xA;           subscriber.onComplete();&#xA;        }&#xA;&#xA;        executorService.shutdown();&#xA;&#xA;    }&#xA;&#xA;    public void publish(int i) {&#xA;        Flow.Subscriber? super Integer subscriber = subscribers.poll();&#xA;        if (Objects.nonNull(subscriber)) {&#xA;            subscriber.onNext(i);&#xA;        }&#xA;    }&#xA;&#xA;    public void publish(IllegalArgumentException e) {&#xA;        Flow.Subscriber? super Integer subscriber = subscribers.poll();&#xA;        if (Objects.nonNull(subscriber)) {&#xA;            subscriber.onError(e);&#xA;        }&#xA;    }&#xA;&#xA;    public void sendShutdown(boolean cancel) {&#xA;        this.shutdown(cancel);&#xA;    }&#xA;}&#xA;&#xA;I learned that having everything on the ForkJoinPool with work stealing ethics causes a lot, but a lot, context switching and threads. So in my case the CPU just flared 100% on thread switching whilst not much was going on. &#xA;&#xA;Subscriber&#xA;&#xA;The subscriber will ask for Long.MAXVALUE so it is essentially unbounded. Which is also in the documentation, so I should have just read that more carefully and think about it.&#xA;&#xA;import util.StatisticsUtil;&#xA;import java.util.UUID;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;import static util.PrimeUtil.demand;&#xA;import static util.PrimeUtil.primes;&#xA;&#xA;public class PrimeFinder implements Flow.SubscriberInteger {&#xA;&#xA;    private final String name;&#xA;    private static Logger LOGGER;&#xA;&#xA;    public PrimeFinder() {&#xA;        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());&#xA;        LOGGER = Logger.getLogger(this.name);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onSubscribe(Flow.Subscription subscription) {&#xA;        StatisticsUtil.stats.putIfAbsent(this.name, 0);&#xA;        subscription.request(Long.MAXVALUE);&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onNext(Integer integer) {&#xA;        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));&#xA;&#xA;        if (primes.parallelStream().noneMatch(p -  integer % p == 0)) {&#xA;            if(demand.getAndDecrement()   0) {&#xA;                primes.add(integer);&#xA;                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));&#xA;                int newCount = StatisticsUtil.stats.get(this.name) + 1;&#xA;                StatisticsUtil.stats.put(this.name, newCount);&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onError(Throwable throwable) {&#xA;        LOGGER.log(Level.SEVERE, throwable.getMessage());&#xA;    }&#xA;&#xA;    @Override&#xA;    public void onComplete() {&#xA;        LOGGER.log(Level.INFO, name + &#34; is done&#34;);&#xA;    }&#xA;}&#xA;&#xA;Main&#xA;&#xA;In the main not a lot gets changed. Number of totalSubscribers gets doubled and sending a true to sendShutdown to make sure the executorServices in question are shutdown and waited for until done. &#xA;&#xA;import publishers.IntegerPublisherImpl;&#xA;import subscribers.PrimeFinder;&#xA;import util.PrimeUtil;&#xA;import util.StatisticsUtil;&#xA;&#xA;import java.util.ArrayList;&#xA;import java.util.List;&#xA;import java.util.concurrent.Flow;&#xA;import java.util.concurrent.TimeUnit;&#xA;import java.util.logging.Level;&#xA;import java.util.logging.Logger;&#xA;&#xA;public class Main {&#xA;    final static int totalSubscribers = Runtime.getRuntime().availableProcessors()  2;&#xA;    private static final Logger LOGGER = Logger.getAnonymousLogger();&#xA;&#xA;    public static void main(String[] args) throws InterruptedException {&#xA;        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();&#xA;        ListFlow.Subscriber&lt;Integer  subscribers = new ArrayList();&#xA;&#xA;        for (int i = 0; i &lt; totalSubscribers; i++) {&#xA;            subscribers.add(new PrimeFinder());&#xA;        }&#xA;        subscribers.forEach(integerPublisher::subscribe);&#xA;&#xA;        while (PrimeUtil.demand.get()   0 ) {&#xA;            TimeUnit.MILLISECONDS.sleep(100);&#xA;        }&#xA;        integerPublisher.sendShutdown(true);&#xA;        StatisticsUtil.stats.forEach((name, count) -  LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));&#xA;        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());&#xA;    }&#xA;}&#xA;&#xA;This should flow way nicer and smoother. It should also provide a more even distribution amongst the subscribers. I have 8 subscribers and put in 1000 primes and it did it in close to 1 second. Which I find a nice result. It did not put a strain on my CPU as all other applications happily chugged along.  &#xA;&#xA;Final thoughts&#xA;&#xA;I think about extending this into an example that has an error queue and so the publisher can also publish errors and log them. The nice thing is that in this case the publishing will still happen regardless of errors. The previous one would drop the subscriber as it would not request a new one, and therefore it had to wait a whole cycle until it was next to process a request and then it would request a new one. Let&#39;s say all errors happen in a row and all subscribers have to handle errors. Could happen, it is not unfathomable to know multiple errors happen in a row. Then the chain would die due to starvation of no new requests being made. &#xA;&#xA;#code #java]]&gt;</description>
      <content:encoded><![CDATA[<p>I have gotten some experience using the Flow constructs in a real scenario and learned some lessons. Therefore I wanted to make some code changes to my <a href="https://stealthycoder.writeas.com/flow-like-water" rel="nofollow">original design</a>. </p>

<h1 id="integer-subscription" id="integer-subscription">Integer Subscription</h1>

<p>In the subscription we will use a internal ExecutorService to handle the input.</p>

<pre><code class="language-Java">import publishers.IntegerPublisher;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class IntegerSubscription implements Flow.Subscription  {

    private IntegerPublisher integerPublisher;
    private Iterator&lt;Integer&gt; integerStream;
    private final AtomicBoolean isCanceled = new AtomicBoolean();
    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public IntegerSubscription(IntegerPublisher integerPublisher) {
        this.integerPublisher = integerPublisher;
        this.integerStream = Stream.iterate(2, i -&gt; i + 1).iterator();
    }

    @Override
    public void request(long l) {
        if ( l &lt; 0) {
            integerPublisher.publish(new IllegalArgumentException(&#34;Have to request a positive number of elements&#34;));
        }
        executorService.submit(this.handleRequests(l));
        
    }

    private Runnable handleRequests(long l) {
        return () -&gt; {
            for (long i = 0; i &lt; l; i++) {
                if (isCanceled.get()) {
                    break;
                }
                integerPublisher.publish(integerStream.next());
            }
        };
    }

    @Override
    public void cancel() {
        isCanceled.set(true);
        executorService.shutdown();
        try {
            executorService.awaitTermination(5L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre>

<h1 id="publisher" id="publisher">Publisher</h1>

<p>In the publisher take out the executorService parts. One of the major problems was actually that the publisher itself was on the executorService somewhere and so it would never shutdown. Also I did not call the <code>onComplete</code> and therefore the <code>executorService</code> would not shutdown correctly either.</p>

<pre><code class="language-Java">import CyclicRingBuffer;
import subscriptions.IntegerSubscription;

import java.util.Objects;
import java.util.concurrent.*;

public class IntegerPublisherImpl implements IntegerPublisher  {

    private final IntegerSubscription subscription;
    private final CyclicRingBuffer&lt;Flow.Subscriber&lt;? super Integer&gt;&gt; subscribers;

    public IntegerPublisherImpl() {
        this.subscription = new IntegerSubscription(this);
        subscribers = new CyclicRingBuffer&lt;&gt;();
    }

    @Override
    public void subscribe(Flow.Subscriber&lt;? super Integer&gt; subscriber) {
        subscribers.push(subscriber);
        subscriber.onSubscribe(this.subscription);
    }

    private void shutdown(boolean cancel) {
        if (cancel) {
            this.subscription.cancel();
        } 
        for (Flow.Subscriber&lt;? super Integer&gt; subscriber : subscribers) {
           subscriber.onComplete();
        }

        executorService.shutdown();

    }

    public void publish(int i) {
        Flow.Subscriber&lt;? super Integer&gt; subscriber = subscribers.poll();
        if (Objects.nonNull(subscriber)) {
            subscriber.onNext(i);
        }
    }

    public void publish(IllegalArgumentException e) {
        Flow.Subscriber&lt;? super Integer&gt; subscriber = subscribers.poll();
        if (Objects.nonNull(subscriber)) {
            subscriber.onError(e);
        }
    }

    public void sendShutdown(boolean cancel) {
        this.shutdown(cancel);
    }
}
</code></pre>

<p>I learned that having everything on the ForkJoinPool with work stealing ethics causes a lot, but <strong>a lot</strong>, context switching and threads. So in my case the CPU just flared 100% on thread switching whilst not much was going on.</p>

<h1 id="subscriber" id="subscriber">Subscriber</h1>

<p>The subscriber will ask for <code>Long.MAX_VALUE</code> so it is essentially unbounded. Which is also in the documentation, so I should have just read that more carefully and think about it.</p>

<pre><code class="language-Java">import util.StatisticsUtil;
import java.util.UUID;
import java.util.concurrent.Flow;
import java.util.logging.Level;
import java.util.logging.Logger;

import static util.PrimeUtil.demand;
import static util.PrimeUtil.primes;

public class PrimeFinder implements Flow.Subscriber&lt;Integer&gt; {

    private final String name;
    private static Logger LOGGER;

    public PrimeFinder() {
        this.name = String.format(&#34;%s-%s&#34;, this.getClass().getName(), UUID.randomUUID());
        LOGGER = Logger.getLogger(this.name);
    }

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        StatisticsUtil.stats.putIfAbsent(this.name, 0);
        subscription.request(Long.MAX_VALUE);
    }

    @Override
    public void onNext(Integer integer) {
        LOGGER.log(Level.FINE, String.format(&#34;I&#39;m %s working on %d&#34;, name, integer));

        if (primes.parallelStream().noneMatch(p -&gt; integer % p == 0)) {
            if(demand.getAndDecrement() &gt; 0) {
                primes.add(integer);
                LOGGER.log(Level.INFO, String.format(&#34;%d found by me: %s&#34;, integer, name));
                int newCount = StatisticsUtil.stats.get(this.name) + 1;
                StatisticsUtil.stats.put(this.name, newCount);
            }
        }
    }

    @Override
    public void onError(Throwable throwable) {
        LOGGER.log(Level.SEVERE, throwable.getMessage());
    }

    @Override
    public void onComplete() {
        LOGGER.log(Level.INFO, name + &#34; is done&#34;);
    }
}
</code></pre>

<h1 id="main" id="main">Main</h1>

<p>In the main not a lot gets changed. Number of <code>totalSubscribers</code> gets doubled and sending a <code>true</code> to <code>sendShutdown</code> to make sure the <code>executorServices</code> in question are shutdown and waited for until done.</p>

<pre><code class="language-Java">import publishers.IntegerPublisherImpl;
import subscribers.PrimeFinder;
import util.PrimeUtil;
import util.StatisticsUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {
    final static int totalSubscribers = Runtime.getRuntime().availableProcessors() * 2;
    private static final Logger LOGGER = Logger.getAnonymousLogger();

    public static void main(String[] args) throws InterruptedException {
        IntegerPublisherImpl integerPublisher = new IntegerPublisherImpl();
        List&lt;Flow.Subscriber&lt;Integer&gt;&gt; subscribers = new ArrayList&lt;&gt;();

        for (int i = 0; i &lt; totalSubscribers; i++) {
            subscribers.add(new PrimeFinder());
        }
        subscribers.forEach(integerPublisher::subscribe);

        while (PrimeUtil.demand.get() &gt; 0 ) {
            TimeUnit.MILLISECONDS.sleep(100);
        }
        integerPublisher.sendShutdown(true);
        StatisticsUtil.stats.forEach((name, count) -&gt; LOGGER.log(Level.INFO, String.format(&#34;%s found %d&#34;, name, count)));
        LOGGER.log(Level.INFO, PrimeUtil.primes.toString());
    }
}
</code></pre>

<p>This should flow way nicer and smoother. It should also provide a more even distribution amongst the subscribers. I have 8 subscribers and put in 1000 primes and it did it in close to 1 second. Which I find a nice result. It did not put a strain on my CPU as all other applications happily chugged along.</p>

<h1 id="final-thoughts" id="final-thoughts">Final thoughts</h1>

<p>I think about extending this into an example that has an error queue and so the publisher can also publish errors and log them. The nice thing is that in this case the publishing will still happen regardless of errors. The previous one would drop the subscriber as it would not request a new one, and therefore it had to wait a whole cycle until it was next to process a request and then it would request a new one. Let&#39;s say all errors happen in a row and all subscribers have to handle errors. Could happen, it is not unfathomable to know multiple errors happen in a row. Then the chain would die due to starvation of no new requests being made.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/flow-like-water-diverted</guid>
      <pubDate>Wed, 20 Jan 2021 10:43:15 +0000</pubDate>
    </item>
    <item>
      <title>Stay clear of the void</title>
      <link>https://stealthycoder.writeas.com/stay-clear-of-the-void?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[So I learned this the hard way, but in reactive programming, aka my WebFlux project. Do not ever use Void as a type. Just wrap it in something you can propagate like Object, String or Boolean or something else. !--more--&#xA;&#xA;It gets really difficult, like impossible, do to things like return a MonoVoid that actually is returning some object. You cannot return null as that will internally by construed to be an empty Mono and won&#39;t trigger downstream. So that goes out the window, how about instantiating one via Void.TYPE.newInstance() ? Well that is not without it&#39;s own problems. It is deprecated and most likely can fail in any number of reasons plus make your code really unmanageable. &#xA;&#xA;Never ever ever ever use it ?&#xA;&#xA;Well you can if you know it is the end of the line, but for instance doing a .onErrorResume(FunctionThrowable, ? extends Void) is not a cool thing to do. Even if a Mono.then() will fix the problem it just makes everything so unnecessarily complex.&#xA;&#xA;#java #reactive]]&gt;</description>
      <content:encoded><![CDATA[<p>So I learned this the hard way, but in reactive programming, aka my WebFlux project. Do not ever use Void as a type. Just wrap it in something you can propagate like Object, String or Boolean or something else. </p>

<p>It gets really difficult, like impossible, do to things like return a <code>Mono&lt;Void&gt;</code> that actually is returning some object. You cannot return <code>null</code> as that will internally by construed to be an empty Mono and won&#39;t trigger downstream. So that goes out the window, how about instantiating one via <code>Void.TYPE.newInstance()</code> ? Well that is not without it&#39;s own problems. It is deprecated and most likely can fail in any number of reasons plus make your code really unmanageable.</p>

<h1 id="never-ever-ever-ever-use-it" id="never-ever-ever-ever-use-it">Never ever ever ever use it ?</h1>

<p>Well you can if you know it is the end of the line, but for instance doing a <code>.onErrorResume(Function&lt;Throwable, ? extends Void&gt;)</code> is not a cool thing to do. Even if a <code>Mono.then()</code> will fix the problem it just makes everything so unnecessarily complex.</p>

<p><a href="https://stealthycoder.writeas.com/tag:java" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">java</span></a> <a href="https://stealthycoder.writeas.com/tag:reactive" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">reactive</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/stay-clear-of-the-void</guid>
      <pubDate>Wed, 22 Sep 2021 18:02:39 +0000</pubDate>
    </item>
  </channel>
</rss>