<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Shreyans</title>
    <description>The latest articles on DEV Community by Shreyans (@shreyansiscoding).</description>
    <link>https://dev.to/shreyansiscoding</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1147091%2Feeda7670-0744-4ef6-9053-e234b48a404a.jpeg</url>
      <title>DEV Community: Shreyans</title>
      <link>https://dev.to/shreyansiscoding</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shreyansiscoding"/>
    <language>en</language>
    <item>
      <title>Java Concurrency : Future</title>
      <dc:creator>Shreyans</dc:creator>
      <pubDate>Tue, 12 Sep 2023 02:30:00 +0000</pubDate>
      <link>https://dev.to/shreyansiscoding/java-concurrency-future-1djc</link>
      <guid>https://dev.to/shreyansiscoding/java-concurrency-future-1djc</guid>
      <description>&lt;p&gt;In my previous post in this series, I talked about the concept of a &lt;em&gt;Callable&lt;/em&gt; in Java. We saw that when we execute a Callable task using the &lt;em&gt;ExecutorService&lt;/em&gt;, we get back a &lt;code&gt;Future&amp;lt;T&amp;gt;&lt;/code&gt;. What is this 'Future' ? In the previous post in this series, you have already seen basic usage of Futures. In this post, we'll discuss two of the most important methods detailed out in the Future API.&lt;/p&gt;




&lt;p&gt;In simple words, a &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html"&gt;&lt;em&gt;Future&lt;/em&gt;&lt;/a&gt; is a placeholder for the result of an asynchronous computation that is to be performed some time in the future. It is used as a reference to the result of an asynchronous computation.&lt;/p&gt;




&lt;h2&gt;
  
  
  T get()
&lt;/h2&gt;

&lt;p&gt;This method can be used to 'get' the result of the asynchronous computation. The callable task can be in any of the many possible states when you invoke this method on the corresponding future. Three of the most basic possible scenarios is&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Still RUNNING&lt;/li&gt;
&lt;li&gt;Normal COMPLETION&lt;/li&gt;
&lt;li&gt;Exceptional COMPLETION&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following code snippet shows each of these scenarios in action. Notice how when our callable is still running, the .get() call blocks the main thread.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) {
        System.out.println("Main method has started.");

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Future&amp;lt;Integer&amp;gt; stillRunning = executorService.submit(new Task(2000, false));
        Future&amp;lt;Integer&amp;gt; normalCompletion = executorService.submit(new Task(20, false));
        Future&amp;lt;Integer&amp;gt; exceptionalCompletion = executorService.submit(new Task(20, true));

        try {
            long startEpoch = System.currentTimeMillis();
            Integer resultStillRunning = stillRunning.get();
            long endEpoch = System.currentTimeMillis();

            System.out.println("[1] Result : " + resultStillRunning);
            System.out.println("[1] Time Taken For .get() call : " + (endEpoch - startEpoch));
        } catch (InterruptedException e) {
            System.out.println("[1] InterruptedException");
        } catch (ExecutionException e) {
            System.out.println("[1] ExecutionException : " + e.getCause().getMessage());
        }


        try {
            long startEpoch = System.currentTimeMillis();
            Integer resultNormalCompletion = normalCompletion.get();
            long endEpoch = System.currentTimeMillis();

            System.out.println("[2] Result : " + resultNormalCompletion);
            System.out.println("[2] Time Taken For .get() call : " + (endEpoch - startEpoch));
        } catch (InterruptedException e) {
            System.out.println("[2] InterruptedException");
        } catch (ExecutionException e) {
            System.out.println("[2] ExecutionException : " + e.getCause().getMessage());
        }


        try {
            long startEpoch = System.currentTimeMillis();
            Integer resultExceptionalCompletion = exceptionalCompletion.get();
            long endEpoch = System.currentTimeMillis();

            System.out.println("[3] Result : " + resultExceptionalCompletion);
            System.out.println("[3] Time Taken For .get() call : " + (endEpoch - startEpoch));
        } catch (InterruptedException e) {
            System.out.println("[3] InterruptedException");
        } catch (ExecutionException e) {
            System.out.println("[3] ExecutionException : " + e.getCause().getMessage());
        }

        executorService.shutdown();

        System.out.println("Main method has finished.");
    }

    private static class Task implements Callable&amp;lt;Integer&amp;gt; {

        private final int sleepForMilliseconds;
        private final boolean throwException;

        public Task(int sleepForMilliseconds, boolean throwException) {
            this.sleepForMilliseconds = sleepForMilliseconds;
            this.throwException = throwException;
        }

        @Override
        public Integer call() throws Exception {
            if (throwException) {
                throw new Exception("Something bad happened...");
            }

            TimeUnit.MILLISECONDS.sleep(sleepForMilliseconds);
            return new Random().nextInt();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
[1] Result : 1548882964
[1] Time Taken For .get() call : 2005
[2] Result : 1474341827
[2] Time Taken For .get() call : 0
[3] ExecutionException : Something bad happened...
Main method has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  boolean isDone()
&lt;/h2&gt;

&lt;p&gt;This method returns true if this task 'completed'. Completion may be due to normal or exceptional. Also, while we will not be discussing cancelling of tasks in this post, the &lt;code&gt;isDone()&lt;/code&gt; method returns true even when the task was cancelled.&lt;/p&gt;

&lt;p&gt;The following code snippet shows this method in action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("Main method has started.");

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Future&amp;lt;Integer&amp;gt; future = executorService.submit(new Task());

        while (!future.isDone()) {
            System.out.println("Task Is Still Not Done!");
            Thread.sleep(6L); // busy-waiting (just for demonstration, bad idea in production code)
        }
        System.out.println("Task Is Done With Result : " + future.get());

        executorService.shutdown();

        System.out.println("Main method has finished.");
    }

    private static class Task implements Callable&amp;lt;Integer&amp;gt; {

        @Override
        public Integer call() throws Exception {
            TimeUnit.MILLISECONDS.sleep(20);
            System.out.println("Task Completed!");
            return new Random().nextInt();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
Task Is Still Not Done!
Task Is Still Not Done!
Task Is Still Not Done!
Task Is Still Not Done!
Task Completed!
Task Is Done With Result : 1549778552
Main method has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>java</category>
      <category>concurrency</category>
      <category>multithreading</category>
    </item>
    <item>
      <title>Java Concurrency : Callable</title>
      <dc:creator>Shreyans</dc:creator>
      <pubDate>Mon, 11 Sep 2023 06:39:00 +0000</pubDate>
      <link>https://dev.to/shreyansiscoding/java-concurrency-callable-19je</link>
      <guid>https://dev.to/shreyansiscoding/java-concurrency-callable-19je</guid>
      <description>&lt;p&gt;In the last post in this series, we understood what a &lt;em&gt;Runnable&lt;/em&gt; is in Java. Some of you may have noticed a big limitation of the &lt;em&gt;Runnable&lt;/em&gt; API, that it does not return a value. This means that while you can use a &lt;em&gt;Runnable&lt;/em&gt; to execute some unit of work in a separate thread, there isn't a straightforward way for you to retrieve a meaningful value which may represent the result of that work.&lt;/p&gt;

&lt;p&gt;For the reader's understanding, the code below shows one way how you might retrieve the result of a &lt;em&gt;Runnable&lt;/em&gt;. However, please note that this is just for your understanding and you will not find code like this in production grade applications.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) {
        System.out.println("Main method has started.");

        BlockingQueue&amp;lt;String&amp;gt; resultsHolder = new ArrayBlockingQueue&amp;lt;String&amp;gt;(10);

        new Task(resultsHolder);
        new Task(resultsHolder);
        new Task(resultsHolder);

        try {
            System.out.println(resultsHolder.take());
            System.out.println(resultsHolder.take());
            System.out.println(resultsHolder.take());
        } catch (InterruptedException e) {
            // thrown when current thread was interrupted while waiting on the blocking call .take()
            throw new RuntimeException(e);
        }

        System.out.println("Main method has finished.");
    }

    private static class Task extends Thread {

        private static int numTasks;
        private final int id;
        private final BlockingQueue&amp;lt;String&amp;gt; resultsHolder;

        public Task(BlockingQueue&amp;lt;String&amp;gt; resultsHolder) {
            this.id = ++numTasks;
            this.resultsHolder = resultsHolder;
            this.start();
        }

        @Override
        public void run() {
            System.out.println("Task has started.");

            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            String result = "Hello, World! This is Task : " + id;
            this.resultsHolder.add(result);

            System.out.println("Task has finished.");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Java Concurrency Framework provides the &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html"&gt;&lt;em&gt;Callable&lt;/em&gt;&lt;/a&gt; interface. Along with certain other differences and advantages (more about this in another post), It solves the above mentioned limitation of &lt;em&gt;Runnable&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;To execute a &lt;em&gt;Callable&lt;/em&gt; task, you can use an &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html"&gt;&lt;em&gt;ExecutorService&lt;/em&gt;&lt;/a&gt; to get a &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html"&gt;&lt;em&gt;Future&lt;/em&gt;&lt;/a&gt; representing the result of the task. (More about &lt;em&gt;Future&lt;/em&gt; and &lt;em&gt;ExecutorService&lt;/em&gt; in another post)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) {
        System.out.println("Main method has started.");

        Task t1 = new Task();
        Task t2 = new Task();
        Task t3 = new Task();

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Future&amp;lt;String&amp;gt; f1 = executorService.submit(t1);
        Future&amp;lt;String&amp;gt; f2 = executorService.submit(t2);
        Future&amp;lt;String&amp;gt; f3 = executorService.submit(t3);

        try {
            System.out.println(f1.get());
            System.out.println(f2.get());
            System.out.println(f3.get());
        } catch (InterruptedException e) {
            // thrown when current thread was interrupted
            // while waiting on the blocking call .get()
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            // thrown when attempting to retrieve the result
            // of a task that aborted by throwing an exception.
            throw new RuntimeException(e);
        }

        executorService.shutdown();

        System.out.println("Main method has finished.");
    }

    private static class Task implements Callable&amp;lt;String&amp;gt; {

        private static int numTasks;
        private final int id;

        public Task() {
            this.id = ++numTasks;
        }

        @Override
        public String call() {
            System.out.println("Task has started.");

            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return "Hello, World! This is Task : " + id;
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
Task has started.
Task has started.
Task has started.
Hello, World! This is Task : 1
Hello, World! This is Task : 2
Hello, World! This is Task : 3
Main method has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition to &lt;em&gt;Callables&lt;/em&gt;, An &lt;em&gt;ExecutorService&lt;/em&gt; can also be used for executing &lt;em&gt;Runnables&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;ExecutorService&lt;/em&gt; provides these methods for this purpose. Do check these out!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;void execute(Runnable command)&lt;/code&gt; [&lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-"&gt;Java Doc Link&lt;/a&gt;]&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Future&amp;lt;?&amp;gt; submit(Runnable task)&lt;/code&gt; [&lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.lang.Runnable-"&gt;Java Doc Link&lt;/a&gt;]&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>java</category>
      <category>concurrency</category>
      <category>multithreading</category>
    </item>
    <item>
      <title>Java Concurrency : Runnable</title>
      <dc:creator>Shreyans</dc:creator>
      <pubDate>Sun, 10 Sep 2023 07:29:18 +0000</pubDate>
      <link>https://dev.to/shreyansiscoding/java-concurrency-runnable-4fen</link>
      <guid>https://dev.to/shreyansiscoding/java-concurrency-runnable-4fen</guid>
      <description>&lt;h2&gt;
  
  
  Brief Introduction
&lt;/h2&gt;

&lt;p&gt;In Java, a &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html"&gt;&lt;em&gt;Runnable&lt;/em&gt;&lt;/a&gt; is an &lt;a href="https://docs.oracle.com/javase/tutorial/java/concepts/interface.html"&gt;&lt;em&gt;interface&lt;/em&gt;&lt;/a&gt; that represents a unit of work which can be executed by a &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html"&gt;&lt;em&gt;thread&lt;/em&gt;&lt;/a&gt;. It is part of the Java Concurrency framework &lt;code&gt;(java.util.concurrent)&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example - A &lt;em&gt;Runnable&lt;/em&gt; Task
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public class Task implements Runnable {

        @Override
        public void run() {
            // do something meaningful
            System.out.println("Hello, World!");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Example - A &lt;em&gt;Thread&lt;/em&gt; running a &lt;em&gt;Runnable&lt;/em&gt; Task
&lt;/h2&gt;

&lt;p&gt;The Java Concurrency Framework provides a &lt;em&gt;Thread&lt;/em&gt; class which can be used for running a &lt;em&gt;Runnable&lt;/em&gt; in a separate thread of execution. This can be done by using the &lt;code&gt;start()&lt;/code&gt; method provided by the &lt;em&gt;Thread&lt;/em&gt; class which initiates the execution of the thread's code in a new thread of control. This method is essential for multithreading because it tells the Java Virtual Machine (JVM) to begin executing the &lt;code&gt;run()&lt;/code&gt; method of the underlying &lt;em&gt;Runnable&lt;/em&gt; concurrently in a separate thread.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) {
        System.out.println("Main method has started.");

        Thread t = new Thread(new Task("Charlie"));
        t.start();

        System.out.println("Main method has finished.");
    }

    private static class Task implements Runnable {

        private final String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("Task " + name + " has started.");
            System.out.println("Hello, World! This is Task : " + name);
            System.out.println("Task " + name + " has finished.");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this program is non deterministic. This is because the operating system and the Java Virtual Machine (JVM) schedule and manage thread execution independently, and the order in which threads (in this case the main thread and the explicitly created task thread) are scheduled to run can vary each time the program is executed.&lt;/p&gt;

&lt;p&gt;For instance, one possible output is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
Main method has finished.
Task Charlie has started.
Hello, World! This is Task : Charlie
Task Charlie has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we are storing the thread reference of the task thread in the main method, we can also wait for its completion before proceeding further in the main method. This can be done by using the &lt;code&gt;join()&lt;/code&gt; method provided by the &lt;em&gt;Thread&lt;/em&gt; class which is a blocking call and blocks the caller thread until the callee thread completes execution and dies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) throws InterruptedException {
        System.out.println("Main method has started.");

        Thread t = new Thread(new Task("Charlie"));
        t.start();
        t.join();

        System.out.println("Main method has finished.");
    }

    private static class Task implements Runnable {

        private final String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("Task " + name + " has started.");
            System.out.println("Hello, World! This is Task : " + name);
            System.out.println("Task " + name + " has finished.");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note how we've also added the &lt;code&gt;InterruptedException&lt;/code&gt; to the main method's signature. That is because the &lt;code&gt;join()&lt;/code&gt; method of the &lt;em&gt;Thread&lt;/em&gt; class throws this checked exception. More about this in another post, but in summary When you call the join() method on a thread (let's call it "Thread 1") from another thread (let's call it "Thread 2"), Thread 2 will wait until Thread 1 completes its execution. In other words, Thread 2 will be blocked until Thread 1 finishes. If, while Thread 2 is waiting, another thread (let's call it "Thread 3") interrupts Thread 2 (e.g., by invoking Thread.interrupt() on Thread 2), Thread 2 will throw an InterruptedException.&lt;/p&gt;

&lt;p&gt;The output of this program in this case is deterministic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
Task Charlie has started.
Hello, World! This is Task : Charlie
Task Charlie has finished.
Main method has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Miscellaneous Example
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void main(String[] args) {
        System.out.println("Main method has started.");

        for (int i=0; i&amp;lt;5; ++i) {
            new Task();
        }

        System.out.println("Main method has finished.");
    }

    private static class Task extends Thread {

        private static int numTasks = 0;
        private final int id;

        public Task() {
            this.id = ++numTasks;
            this.start();
        }

        @Override
        public void run() {
            System.out.println("Task " + id + " has started.");

            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("Hello, World! This is Task : " + id);

            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("Task " + id + " has finished.");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output for this is again non-deterministic. One possible output is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Main method has started.
Main method has finished.
Task 5 has started.
Task 2 has started.
Task 4 has started.
Task 1 has started.
Task 3 has started.
Hello, World! This is Task : 4
Hello, World! This is Task : 5
Hello, World! This is Task : 1
Hello, World! This is Task : 2
Hello, World! This is Task : 3
Task 2 has finished.
Task 4 has finished.
Task 5 has finished.
Task 1 has finished.
Task 3 has finished.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>java</category>
      <category>concurrency</category>
      <category>multithreading</category>
    </item>
    <item>
      <title>Garbage Collection</title>
      <dc:creator>Shreyans</dc:creator>
      <pubDate>Sat, 02 Sep 2023 20:28:42 +0000</pubDate>
      <link>https://dev.to/shreyansiscoding/garbage-collection-226b</link>
      <guid>https://dev.to/shreyansiscoding/garbage-collection-226b</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Programs run on data. Data lives in Memory. Memory needs management. &lt;/p&gt;

&lt;p&gt;In simple words, Garbage Collection is an automated process which aids memory management by identifying and reclaiming memory occupied by objects that are no longer in use by a program, preventing memory leaks and ensuring efficient resource utilization.&lt;/p&gt;




&lt;h2&gt;
  
  
  A World Without GC
&lt;/h2&gt;

&lt;p&gt;Not all programming language support GC. Without a Garbage Collector, the programmer is responsible for "freeing up" memory which is not being used anymore. This is known as &lt;strong&gt;Manual Memory Management&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;If you are familiar with C/C++, you must have heard/read about &lt;code&gt;malloc()&lt;/code&gt; and &lt;code&gt;free()&lt;/code&gt; or &lt;code&gt;new&lt;/code&gt; and &lt;code&gt;delete&lt;/code&gt;. These are constructs which can be used by the programmer to manage the lifecycle of objects, from &lt;strong&gt;creation&lt;/strong&gt; to &lt;strong&gt;deletion&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;However, programmers are only human, and even with the best of intentions, manual memory management can often lead to serious issues. Two of the most common such issues are&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Memory Leaks&lt;/strong&gt; : This happens when you create an object on the heap but forget to delete it. Eventually, the heap gets filled with unused objects and any new request for allocating memory on the heap throws a &lt;strong&gt;Memory Limit Exceeded&lt;/strong&gt; error.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dangling Pointers&lt;/strong&gt; : This happens when you delete an object prematurely even when some other pointers still reference it. Depending upon the programming language, this can manifest differently. Most severely, it can cause intermittent issues which may survive QA and pop up unexpectedly in Production.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That being said, while Manual Memory Management has its drawbacks, it may be desirable when you want to build applications with super critical memory/latency needs. In such use cases, using manual memory management, the developer can have maximum control over the lifecycle of objects, and can decide when to create/delete them so as to optimise memory/latency performance.&lt;/p&gt;




&lt;h2&gt;
  
  
  Popular GC Algorithms
&lt;/h2&gt;

&lt;p&gt;Modern programming languages like Java and Python support Garbage Collection. Often, The Garbage Collector runs in separate thread(s) than the main program thread(s) (also called as &lt;code&gt;mutator&lt;/code&gt; threads), and every time it executes, it works towards collecting the garbage. While the goal of Garbage Collectors remains the same, they can be implemented in many different ways. Two popular Garbage Collection algorithms are&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Mark And Sweep&lt;/strong&gt; (&lt;strong&gt;Java&lt;/strong&gt;) : This is classic algorithm which is used by Garbage Collectors for reclaiming memory occupied by "unreachable" or "dead" objects in the heap. It works in 2 phases. In the "Mark" phase all "reachable" or "live" objects are marked by traversing the object reference graph starting from the known root references. In the "Sweep" phase the heap is traversed and all memory which is not marked is reclaimed for reuse.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reference Counting&lt;/strong&gt; (&lt;strong&gt;Python&lt;/strong&gt;) : This is an algorithm which keeps track of the reference count of each object to track garbage. Every time a reference to an object is created, the reference count for that object is incremented. Similarly, every time a reference to an object is deleted or replaced, the reference count for that object is decremented. When the reference count of an object becomes 0, it is considered eligible for garbage collection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both of these have their pros and cons. For example&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Mark and Sweep might cause "Heap Fragmentation" where the used heap memory becomes divided into small non-contiguous blocks. This makes it difficult to find space which may be needed for a Large contiguous data structure (like an Array). A variation of the Mark and Sweep, known as Mark, Sweep and Compact deals with Fragmentation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reference Counting cannot collect circular data structures (like circular linked lists) because each node has a reference count of 1 even after the original reference to the "head" has been removed. This inability of Reference Counting to collect circularly referenced structures can cause Memory Leaks. Due to this, Python versions 3.4 and above also include a cyclic garbage collector to handle circular references and objects that are not properly cleaned up by reference counting alone.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>computerscience</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Java : Interpreted or Compiled ? JIT and AOT !</title>
      <dc:creator>Shreyans</dc:creator>
      <pubDate>Sun, 27 Aug 2023 08:00:18 +0000</pubDate>
      <link>https://dev.to/shreyansiscoding/java-interpreted-or-compiled-jit-and-aot--2lpn</link>
      <guid>https://dev.to/shreyansiscoding/java-interpreted-or-compiled-jit-and-aot--2lpn</guid>
      <description>&lt;p&gt;As a programmer, you may have read about the concept of interpreted languages or compiled languages. &lt;/p&gt;

&lt;p&gt;Interpreted languages (example. BASIC) are those in which the source code is directly executed by the &lt;strong&gt;interpreter&lt;/strong&gt;. Compiled languages (example. C++) on the other hand are those in which a &lt;strong&gt;compiler&lt;/strong&gt; converts the source code into machine code before execution.&lt;/p&gt;

&lt;p&gt;Is Java interpreted or compiled ? Traditionally speaking, the answer is that Java is both interpreted and compiled. But the more nuanced answer is that it depends on how you choose to execute your Java program.&lt;/p&gt;

&lt;p&gt;The most popular (and maybe one could even say the "default") way of executing java programs is by using &lt;code&gt;javac&lt;/code&gt; to covert the source code into &lt;strong&gt;bytecode&lt;/strong&gt; and then executing the bytecode on a &lt;strong&gt;Java Virtual Machine (JVM)&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;While there are a number of JVMs to choose from, the most popular JVM on the planet is Oracle's HotSpot VM which was first introduced in 1999. If you have java installed on your machine, type &lt;code&gt;java --version&lt;/code&gt; in the command line and inspect the output. You'll most likely see a reference to the HotSpot VM.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xDKn7HFy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c96y6q0a9s651qrutcn9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xDKn7HFy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c96y6q0a9s651qrutcn9.png" alt="HotSpot VM" width="800" height="195"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Therefore, generally speaking what one would do is &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use the Java Compiler (&lt;strong&gt;javac&lt;/strong&gt;) which comes bundled in the Java Development Kit (&lt;strong&gt;JDK&lt;/strong&gt;) to &lt;strong&gt;compile&lt;/strong&gt; the source code (.java) and produce bytecode (.class) . &lt;/li&gt;
&lt;li&gt;Invoke the jvm using the &lt;strong&gt;java&lt;/strong&gt; command so that the JVM can &lt;strong&gt;interpret&lt;/strong&gt; the bytecode and execute it line by line. &lt;/li&gt;
&lt;li&gt;During interpretation, the JVM executes each line of bytecode by first converting it into the corresponding machine instruction. &lt;/li&gt;
&lt;li&gt;Corresponding to that line of bytecode, JVM submits the machine instruction to the CPU for the CPU to execute it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But that's not all. Even during interpretation, the HotSpot VM analyses the "&lt;strong&gt;hot&lt;/strong&gt;" (very simply put this means frequently invoked) areas of your program and caches the compiled version of those areas so that it does not have to repeat step 3 again and again. This is popularly known as &lt;strong&gt;Just In Time Compilation&lt;/strong&gt; (JIT). So now you can probably see that the execution of a Java program is not simply "interpretation" or "compilation", rather it is a well balanced combination of both in the pursuit of portability and performance.&lt;/p&gt;

&lt;p&gt;This is why, generally speaking, Java is considered to be a both interpreted and compiled language.&lt;/p&gt;

&lt;p&gt;But, there are some other ways of executing Java programs which may be better suited in certain use cases.&lt;/p&gt;

&lt;p&gt;One of these is the very popular &lt;a href="https://www.graalvm.org/"&gt;GraalVM&lt;/a&gt; project which offers an &lt;strong&gt;Ahead Of Time&lt;/strong&gt; (AOT) compilation capability using its &lt;a href="https://www.graalvm.org/22.0/reference-manual/native-image/"&gt;Native Image&lt;/a&gt; technology to directly compile Java source code into native machine code for execution.&lt;/p&gt;

&lt;p&gt;Let's see how the "&lt;strong&gt;compilation&lt;/strong&gt;" and "&lt;strong&gt;execution&lt;/strong&gt;" phases differ in both cases in terms of time performance. While there are a lot of other aspects to be compared, the time based comparison will give you a basic idea as to why AOT may be better than JIT for some use cases. &lt;/p&gt;

&lt;p&gt;We will use this program in both cases :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ComputeSquareRoots {
    public static void main(String[] args) {
        int numberOfRuns = 10000;
        long totalTime = 0;

        for (int i = 0; i &amp;lt; numberOfRuns; i++) {
            long startTime = System.nanoTime(); // Start time
            compute();
            long endTime = System.nanoTime(); // End time
            long executionTime = endTime - startTime;
            totalTime += executionTime;
        }

        double averageTime = (double) totalTime / numberOfRuns;

        System.out.println("Average Running Time: " + averageTime + " nanoseconds");
    }

    public static void compute() {
        for (int i = 0; i &amp;lt; 1_000_000; i++) {
            for (int j = 0; j &amp;lt; 100; j++) {
                Math.sqrt(i + j);
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the command line output of each step.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--l8iOBmsO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nm7mpqra882tk3n7ra5k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--l8iOBmsO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nm7mpqra882tk3n7ra5k.png" alt="Command Line Output JIT vs AOT" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The compilation phase with &lt;code&gt;javac&lt;/code&gt; took &lt;strong&gt;~400ms&lt;/strong&gt; to produce the bytecode.&lt;/li&gt;
&lt;li&gt;The execution phase with JVM took &lt;strong&gt;~40,000ns&lt;/strong&gt; as reported by the output of our code.&lt;/li&gt;
&lt;li&gt;The compilation phase for &lt;code&gt;native-image&lt;/code&gt; was actually two step as it took the bytecode produced by javac as input. Therefore, total compilation time can be considered as &lt;strong&gt;~400ms&lt;/strong&gt; + &lt;strong&gt;~16800ms&lt;/strong&gt; which is &lt;strong&gt;~17200ms&lt;/strong&gt;. &lt;strong&gt;This is more than 40 times more as compared to JIT.&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;The execution phase for the AOT compiled native executable was &lt;strong&gt;~30ns&lt;/strong&gt; as reported by the output of our code. &lt;strong&gt;This is more than 1000 times less as compared to JIT.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, while AOT has a longer compilation phase, it gives time advantage during the execution phase.&lt;/p&gt;

&lt;p&gt;The example presented above is an over-simplified one to aid basic understanding. The choice between JIT and AOT in not as simple as this in most cases. There are a lot more aspects to consider. That being said, I hope this article helped you get a basic understanding of these concepts.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
