<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gavindualwis on Medium]]></title>
        <description><![CDATA[Stories by Gavindualwis on Medium]]></description>
        <link>https://medium.com/@gavindualwis99?source=rss-2b3e6a5dd913------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4yUHxN6r-60NgUof</url>
            <title>Stories by Gavindualwis on Medium</title>
            <link>https://medium.com/@gavindualwis99?source=rss-2b3e6a5dd913------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:24:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gavindualwis99/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Apache Kafka]]></title>
            <link>https://gavindualwis99.medium.com/apache-kafka-284936a696d1?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/284936a696d1</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-topic]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka-consumer-group]]></category>
            <category><![CDATA[kafka-producer]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 03:29:33 GMT</pubDate>
            <atom:updated>2025-06-06T03:29:33.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaqLpH76kVv3js21KCH4qw.png" /></figure><p>Apache Kafka is an open-source, distributed event streaming platform.</p><p><strong>Benefits of Kafka</strong></p><p>decoupling service</p><p>scalability</p><p>replayability</p><p>efficiency</p><p>fault tolerance</p><p>Event Streaming means continuously capturing events (data) in real-time, storing them, and allowing systems to react to them either immediately or at a later time.</p><p><strong>Kafka Architecture and Components</strong></p><p>Event — a single unit of message or data that is sending</p><p>Producer — someone who produces the message</p><p>Consumer — someone who receives or consumes the message</p><p>Topic — a channel, named category that receives messages</p><p>Partition — partition further segregates a topic. Different consumers can listen to these partitions</p><p>Consumer groups — a collection of consumers who work together to consume messages from partitions.</p><p>Offset — numerical value that indicates the order of the messages in a partition of a topic.</p><p>cluster — a group of Kafka brokers</p><p>broker — one instance on Kafka</p><p>zookeeper — a manager who coordinates Kafka brokers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9T7X-9qJnrKfcn6nV5CwwQ.png" /></figure><p><strong>Install Apache Kafka using Docker</strong></p><p>docker run -d — name zookeeper -p 2181:2181 -e ZOOKEEPER_CLIENT_PORT=2181 -e ZOOKEEPER_TICK_TIME=2000 confluentinc/cp-zookeeper:latest</p><p><strong>docker run -d — name kafka -p 9092:9092 -e KAFKA_BROKER_ID=1 -e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 — link zookeeper confluentinc/cp-kafka:latest</strong></p><p>After installing Kafka, start a bash shell inside the container.</p><p>docker exec -it kafka bash</p><p><strong>create a topic</strong></p><p>kafka-topics — create — topic my-topic — bootstrap-server localhost:9092 — partitions 3 — replication-factor 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XozYFoFYAQANhgH-LCw08g.png" /></figure><p><strong>view the existing topics</strong></p><p>kafka-topics — list — bootstrap-server localhost:9092</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWekGRS19wXMojJQFHseFA.png" /></figure><p><strong>view details of a topic</strong></p><p>kafka-topics — describe — topic my-topic — bootstrap-server localhost:9092</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REWjAJeAZRIaaLZ5UZOpIw.png" /></figure><p><strong>create a producer and publish events</strong></p><p>kafka-console-producer — topic my-topic — bootstrap-server localhost:9092</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc_yZY1fSs_p0xJexyCpSQ.png" /></figure><p><strong>create a consumer</strong></p><p>kafka-console-consumer — topic my-topic — bootstrap-server localhost:9092</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U80IMYN2e1Y55H4zNQ_QBQ.png" /></figure><p>This consumer is created for the topic, my-topic. This consumer consumes the events that the producer produces.</p><p>Let’s create another consumer for my-topic. When the producer produces events both consumers consume those events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIOylvGlUY9kWwJxAYKYLg.png" /><figcaption>Producer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLIvf_KnjZ4Oqy8eFy-Rtg.png" /><figcaption>Consumer1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRjiP6Bub6SxxRnyGjzoEQ.png" /><figcaption>Consumer2</figcaption></figure><p><strong>Assign the consumer to a group</strong></p><p>kafka-console-consumer — topic my-topic — bootstrap-server localhost:9092 — group my-group — from-beginning</p><p>When both consumers are assigned to the same group, only one consumer consumes the event at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLjbxd3y7IbfipDjdXzxjw.png" /><figcaption>Consumer1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KgeBifeKMSb_6DvXDmixg.png" /><figcaption>Consumer2</figcaption></figure><p>As consumer1 and consumer2 are in the same group(my-group), only consumer1 consumes the event produced by the producer.</p><p>Let’s move to code demonstration.</p><p><strong>create a topic</strong></p><pre>@Configuration<br>public class KafkaTopicConfig {<br>    @Bean<br>    public NewTopic createTopic(){<br>        return new NewTopic(&quot;my-topic&quot;,3,(short) 1);<br>    }<br>}</pre><p>The topic name is &#39;my-topic&#39;, which includes 3 partitions and a replication factor of 1.</p><p><strong>create a producer</strong></p><pre>@PostMapping(&quot;/send&quot;)<br>public String sendMessage(@RequestParam String message){<br>    kafkaTemplate.send(&quot;my-topic&quot;,message);<br>    return &quot;message sent: &quot;+message;<br>}</pre><p>This producer sends messages to the Kafka topic ‘my-topic’.</p><p><strong>create a consumer</strong></p><pre>@Component<br>public class KafkaConsumer {<br>    @KafkaListener(topics = &quot;my-topic&quot;,groupId = &quot;my-new-group&quot;)<br>    public void Listen(String message){<br>        System.out.println(&quot;received message: &quot;+message);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*1iII7LjYBq9sZefoc5y3Eg.png" /></figure><p>This consumer listens to the ‘my-topic’ topic with consumer group id ‘my-new-group’.</p><p><strong>create consumer groups</strong></p><pre>@Component<br>public class KafkaConsumer {<br>    @KafkaListener(topics = &quot;my-topic&quot;,groupId = &quot;my-new-group-1&quot;)<br>    public void Listen1(String message){<br>        System.out.println(&quot;received message 1: &quot;+message);<br>    }<br><br>    @KafkaListener(topics = &quot;my-topic&quot;,groupId = &quot;my-new-group-2&quot;)<br>    public void Listen2(String message){<br>        System.out.println(&quot;received message 2: &quot;+message);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*cVbU8hEhyYh6Euz8STCGFA.png" /></figure><p>Since the two consumers are in different consumer groups, both will consume every message published on ‘my-topic’.</p><pre>@Component<br>public class KafkaConsumer {<br>    @KafkaListener(topics = &quot;my-topic&quot;,groupId = &quot;my-new-group&quot;)<br>    public void Listen1(String message){<br>        System.out.println(&quot;received message 1: &quot;+message);<br>    }<br><br>    @KafkaListener(topics = &quot;my-topic&quot;,groupId = &quot;my-new-group&quot;)<br>    public void Listen2(String message){<br>        System.out.println(&quot;received message 2: &quot;+message);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*iDLXRgUOq8xsu2VNXKHhSw.png" /></figure><p>Since here both consumers are in the same consumer group, only one consumer consumes the messages at a time that are received to ‘my-topic’. This is because Kafka treats all consumers in the same group as members of a load-balancing pool. Messages from partitions are distributed among group members, and each partition is only assigned to one consumer in a group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284936a696d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 7]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-7-7efda89578de?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/7efda89578de</guid>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[atomic-variables]]></category>
            <category><![CDATA[forkjoinpool]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Sat, 10 May 2025 16:41:38 GMT</pubDate>
            <atom:updated>2025-05-10T16:42:42.947Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Multithreading in Java — Part 7</strong></h3><p><strong>Other Important Concepts</strong></p><p><strong>Read Modify write</strong></p><p>When writing for a shared variable in a multi-threaded environment, its final value takes an unpredicted value. The read-modify-write (RMW) pattern ensures safe updates to shared resources in concurrent programming.</p><p><strong>Atomic Variables</strong></p><p>Atomic values mean the variables that are indivisible and thread-safe. They cannot be interrupted or corrupted by other threads during execution. In a multi-threaded environment, atomicity guarantees that operations like reading, writing, or updating a value happen as one unbreakable step.</p><pre>public class AtomicValue {<br>    private static int count = 0;<br>    private static final AtomicInteger counter = new AtomicInteger(0);<br><br>    public static void main(String[] args) throws InterruptedException {<br>        Thread one = new Thread(() -&gt; {<br>            for (int i=0;i&lt;10000;i++){<br>                count++;<br>                counter.incrementAndGet();<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            for (int i=0;i&lt;10000;i++){<br>                count++;<br>                counter.incrementAndGet();<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br>        one.join();<br>        two.join();<br>        System.out.println(&quot;count: &quot;+count);<br>        System.out.println(&quot;counter: &quot;+counter);<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*zPwbh09fLfrmOdzuknZWKA.png" /></figure><p>Here the output for the count is an unpredictable value and the counter is 20000. That is the expected and correct value. The counter is an atomic variable because of that the process happens as an unbreakable step. So other threads are unable to interrupt the execution process.</p><p><strong>Semaphores</strong></p><p>A semaphore is a synchronization mechanism used to control access to a shared resource in concurrent programming. It uses counters to manage the allowed access to the resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*cFJ0pNbiR06vuOe5oJn4fA.png" /></figure><p>Here semaphore only permits three threads to access at a time. When a thread needs to execute it requests from semaphore. So, the semaphore is checking does the thread has the permit or not. If there is a permit give the chance to the thread. If thread4 comes into the picture when thread1, thread2, and thread3 acquire the semaphore, thread4 has to wait until a semaphore is available.</p><pre>public class SemaphoreDemo {<br>    public static void main(String[] args) {<br>        ExecutorService service = Executors.newCachedThreadPool();<br>            for(int i=0;i&lt;15;i++){<br>                service.execute(new Runnable() {<br>                    @Override<br>                    public void run() {<br>                        ScrapeService.INSTANCE.scrape();<br>                    }<br>                });<br>            }<br>    }<br>}<br><br>enum ScrapeService{<br>    INSTANCE;<br><br>    private Semaphore semaphore = new Semaphore(3);<br><br>    public void scrape(){<br>        try {<br>            semaphore.acquire();<br>            invokeScrape();<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }finally {<br>            semaphore.release();<br>        }<br>    }<br><br>    private void invokeScrape(){<br>        try {<br>            System.out.println(&quot;scraping data&quot;);<br>            Thread.sleep(2000);<br>        }catch (InterruptedException e){<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><p>Here semaphore permits only 3 threads. If you run this code you can see how the process happens.</p><p><strong>Mutex</strong></p><p>Mutex is the short form of mutual exclusion. This is also a synchronization mechanism that is used to control access to a shared resource in a multithreaded environment.</p><p>This prevents multiple threads from accessing the critical section of code simultaneously.</p><p>Mutex is nothing but a fancy term for locks and synchronized blocks.</p><p><strong>Fork-Join</strong></p><p>Fork-Join is dividing tasks into smaller sub-tasks, executing them parallel, and combining the results.</p><p>Fork-Join is the same as the executor service, which picks a task by one thread from a pool of threads and executes. However, fork-join is different from the executor service.</p><p>In fork-join, a task is capable of creating sub-tasks.</p><p>In fork-join per thread, there is a queue. In the executor service, there is a shared queue.</p><p>In fork-join work stealing happens. If a thread is in an idle state, steals a task from another thread’s queue.</p><p>The fork-join mechanism is used as it utilizes the multicore processors, simplifying parallelism and work stealing.</p><p><strong>Key concepts of fork-join mechanism</strong></p><p>Forking — breaking a large task into small, independent sub-tasks</p><p>Joining — Waiting for the completion of a forked task and combining its results</p><p>Recursive Task — Used when the computation produces a value</p><p>Recursive Action — Used when the computation does not return anything</p><p><strong>Recursive Task</strong></p><pre>public class SearchOccuranceTask extends RecursiveTask&lt;Integer&gt; {<br>    int[] arr;<br>    int start;<br>    int end;<br>    int searchElement;<br><br>    public SearchOccuranceTask(int[] arr, int start, int end, int searchElement) {<br>        this.arr = arr;<br>        this.start = start;<br>        this.end = end;<br>        this.searchElement = searchElement;<br>    }<br><br>    @Override<br>    protected Integer compute() {<br>        int size = (end-start)-1;<br>        if(size&gt;50){<br>            int mid = (start+end)/2;<br>            SearchOccuranceTask task1 = new SearchOccuranceTask(arr,start,mid,searchElement);<br>            SearchOccuranceTask task2 = new SearchOccuranceTask(arr,mid+1,end,searchElement);<br>            task1.fork();<br>            task2.fork();<br><br>            return task1.join()+task2.join();<br>        }else {<br>            return search();<br>        }<br>    }<br><br>    private Integer search(){<br>        int count = 0;<br>        for (int i =0; i&lt;arr.length;i++){<br>            if(arr[i] == searchElement){<br>                count++;<br>            }<br>        }<br>        return count;<br>    }<br>}<br>class ForkJoinDemo{<br>    public static void main(String[] args) {<br>        int[] arr = new int[100];<br>        Random random = new Random();<br>        for (int i=0;i&lt;arr.length;i++){<br>            arr[i] = random.nextInt(10)+1;<br>        }<br>        int searchElement = random.nextInt(10)+1;<br>        ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());<br>        SearchOccuranceTask task = new SearchOccuranceTask(arr,0,arr.length-1,searchElement);<br>        Integer occurance = pool.invoke(task);<br>        System.out.println(&quot;Array is: &quot;+ Arrays.toString(arr));<br>        System.out.println(&quot;search element: &quot;+searchElement);<br>        System.out.println(&quot;occurrence: &quot;+occurance);<br>    }<br>}</pre><p>Output</p><p>Array is: [10, 4, 9, 10, 9, 8, 10, 6, 3, 6, 4, 2, 6, 1, 6, 4, 2, 2, 4, 10, 6, 6, 4, 4, 6, 7, 3, 2, 7, 10, 6, 5, 5, 10, 10, 1, 1, 10, 3, 4, 1, 7, 1, 10, 3, 1, 7, 7, 5, 5, 2, 10, 6, 3, 7, 8, 4, 10, 3, 3, 3, 1, 7, 1, 2, 4, 7, 9, 3, 3, 9, 5, 2, 10, 8, 7, 3, 5, 1, 8, 9, 6, 4, 10, 6, 2, 4, 8, 9, 6, 5, 10, 6, 8, 7, 10, 8, 3, 3, 4]<br>search element: 10<br>occurrence: 30</p><p>In the above code searching an element from an array. When array size is more than 50 divide the task into two subtasks. Finally, return the results of both tasks.</p><p><strong>Recursive Action</strong></p><pre>public class WorkLoadSplitter extends RecursiveAction {<br>    private final long workLoad;<br><br>    public WorkLoadSplitter(long workLoad) {<br>        this.workLoad = workLoad;<br>    }<br><br>    @Override<br>    protected void compute() {<br>        if(workLoad &gt; 16){<br>            System.out.println(&quot;workload is too big.Thus splitting &quot;+workLoad);<br>            long firstWorkload =workLoad/2;<br>            long seconrdWorkload = workLoad-firstWorkload;<br><br>            WorkLoadSplitter splitter1 = new WorkLoadSplitter(firstWorkload);<br>            WorkLoadSplitter splitter2 = new WorkLoadSplitter(seconrdWorkload);<br><br>            splitter1.fork();<br>            splitter2.fork();<br>        }else {<br>            System.out.println(&quot;workload within limits &quot;+workLoad);<br>        }<br>    }<br>}<br><br>class ForkJoinDemoAction{<br>    public static void main(String[] args) {<br>        ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());<br>        WorkLoadSplitter workLoadSplitter = new WorkLoadSplitter(128);<br>        pool.invoke(workLoadSplitter);<br>    }<br>}</pre><p>Output</p><p>workload is too big.Thus splitting 128<br>workload is too big.Thus splitting 64<br>workload is too big.Thus splitting 32<br>workload within limits 16<br>workload within limits 16<br>workload is too big.Thus splitting 32<br>workload is too big.Thus splitting 64<br>workload within limits 16<br>workload within limits 16<br>workload is too big.Thus splitting 32<br>workload within limits 16<br>workload is too big.Thus splitting 32<br>workload within limits 16<br>workload within limits 16</p><p>In the above code work on a workload. When workload size is more than 16 divide the task into two subtasks. Likewise, recursively divide the task into sub-tasks until size becomes 16.</p><p>This is the end of the article series on multithreading in Java. Good Bye😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7efda89578de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 6]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-6-124753af7ed4?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/124753af7ed4</guid>
            <category><![CDATA[reentrant-lock]]></category>
            <category><![CDATA[deadlock]]></category>
            <category><![CDATA[readwritelock]]></category>
            <category><![CDATA[volatile]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Sun, 04 May 2025 09:33:38 GMT</pubDate>
            <atom:updated>2025-05-10T16:43:36.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 6</h3><p><strong>Locks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*N7Uv2XnRF-Cvt5EmhaoLmg.jpeg" /></figure><p><strong>What are locks?</strong></p><p>When multiple threads run simultaneously, they all try to access the same resource without proper synchronization, which causes data inconsistency. To handle this issue, Java uses locks to ensure that only one thread can access a resource at a given point in time.</p><p><strong>Synchronization Blocks vs Locks</strong></p><p>Synchronized blocks provide intrinsic locking, which is associated with the object and released automatically by the JVM. They are easy to use and have fewer boilerplate codes than locks. However, synchronized blocks are less flexible and problematic when handling interrupts. Locks are more flexible and can manually acquire and release them in any scope.</p><p>Synchronized blocks can be used for simple synchronization, and locks can be used for more flexibility and fine-gain control.</p><p><strong>Condition on Locks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glF7Lx8Eja0RwDkbUals7g.png" /></figure><p>There are two threads in this image. Thread one is running and then going to a waiting state due to a condition. As an example, if a queue is full thread goes to a waiting state. When thread two is running and due to fulfilling a condition, signals thread one to run again which was waiting until a condition was fulfilled.</p><p><strong>Reentrant Lock</strong></p><p>The reentrant lock allows a thread to acquire the same lock without causing any deadlocks.</p><p>A lock is maintaining an internal state. When a thread tries to acquire the lock, the lock checks whether the state. If the state is 0 it marks the current thread as the owner of the lock and sets the state to 1. If the same thread acquires the lock again increments the state of the lock. When the thread that acquired the lock calling unlock decrement the state by 1. Other threads can’t acquire this lock until the state becomes 0.</p><p>When a thread invokes two methods that need the same lock to maintain consistency in a multi-threaded context using reentrant lock.</p><pre>public class ReetrantLock {<br>    private final ReentrantLock lock = new ReentrantLock();<br>    private int sharedData = 0;<br><br>    public void MethodA(){<br>        lock.lock();<br>        try {<br>            sharedData++;<br>            System.out.println(&quot;Method A: &quot;+sharedData);<br>            MethodB();<br>        }finally {<br>            lock.unlock();<br>        }<br>    }<br><br>    public void MethodB(){<br>        lock.lock();<br>        try {<br>            sharedData--;<br>            System.out.println(&quot;Method B: &quot;+sharedData);<br>        }finally {<br>            lock.unlock();<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        ReetrantLock reetrantLock = new ReetrantLock();<br>        for(int i=0;i&lt;5;i++){<br>            new Thread(reetrantLock::MethodA).start();<br>        }<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*XL2Q1ee_9bBlGbwLH6A9mA.png" /></figure><p>MethodA acquires the lock increments the sharedData and then calls MethodB. MethodB also accesses sharedData and acquires the same lock. Otherwise causes a blocking scenario. MethodB decrements the sharedData and then unlocks the lock. Then the MethodA also unlocks the lock.</p><p>The lock fairness controls the order in which a thread acquires a lock. When several threads are waiting, a fair lock means first come first served which means the thread that waits for a long time gets the lock next. The order of waiting threads does not matter in unfair lock. Reentrant locks are unfair in default.</p><pre>ReentrantLock unfairLock = new ReentrantLock();   // fairness = false (default)</pre><pre>ReentrantLock fairLock = new ReentrantLock(true); // fairness = true</pre><p><strong>Read Write Locks</strong></p><p>The read-write lock is a synchronization mechanism that allows multiple threads to read a shared resource concurrently and only one thread able to write to the resource at a time. This is more beneficial when reading heavily than writing heavily.</p><p>As an example, there is a film seat booking system, where the seats can be booked and can view the available seats. Viewing the seats is the reading process and booking the seats is the writing process. There are threads for the reading and writing process. For any thread needs to acquire a lock to do the read or write process. If reading threads one by one acquires a lock and the reading is not efficient as in reading no data is modified. Because of that the multiple reading threads together acquire a lock and do reading. This is much more efficient. However, in the writing process, the data is modified. So, writing threads one by one acquire the lock, and do writing.</p><pre>public class ReadWriteLockDemo {<br>    private int counter = 0;<br>    private final ReadWriteLock lock = new ReentrantReadWriteLock();<br><br>    public void increment(){<br>        lock.writeLock().lock();<br>        try {<br>            counter++;<br>            System.out.println(Thread.currentThread().getName()+ &quot; writes: &quot;+ counter);<br>        }finally {<br>            lock.writeLock().unlock();<br>        }<br>    }<br>    public void getValue(){<br>        lock.readLock().lock();<br>        try {<br>            System.out.println(Thread.currentThread().getName()+ &quot; reads: &quot;+ counter);<br>        }finally {<br>            lock.readLock().unlock();<br>        }<br>    }<br>}<br><br>class Demo{<br>    public static void main(String[] args) {<br>        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();<br>        for(int i=0; i&lt; 2; i++){<br>            Thread readThread = new Thread(() -&gt; {<br>               for(int j=0;j&lt;3;j++){<br>                   readWriteLockDemo.getValue();<br>               }<br>            });<br>            readThread.setName(&quot;Reader Thread &quot;+ (i+1));<br>            readThread.start();<br>        }<br>        Thread writeThread = new Thread(() -&gt; {<br>            for(int i=0;i&lt;5;i++){<br>                readWriteLockDemo.increment();<br>            }<br>        });<br>        writeThread.setName(&quot;write thread&quot;);<br>        writeThread.start();<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*yalbdioeTru3enyrX6sAhA.png" /></figure><p><strong>Visibility Problem in Java</strong></p><p>The visibility problem means changes made to a shared variable by one thread are not visible to another thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*NQr7du1ljJMie5yiieAyhA.png" /></figure><p>Here cores have a separate register and a common shared cache. The value in the shared cache is count=0. The thread1 modifies the value of count as count=1. However, the count value does not update in the shared cache. So, thread2 takes the count value as 0 although it was updated by thread1.</p><p>As a solution to this problem use the volatile keyword. By using this whenever there is a change in the value it’s flushed to the shared memory.</p><p><strong>DeadLocks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*csb5y4WAmK36NdZTHXdIGw.png" /></figure><p>Here, two threads are running. To complete the execution, both threads need lock A and lock B. Only after the execution completes, the locks are released. At time t, thread 1 needs lock B while thread 2 acquires it, and thread 2 needs lock A while thread 1 acquires it. Because of that, both threads can’t acquire the needed locks and can’t complete the execution. This situation is called a deadlock, in which two or more threads are blocked forever.</p><pre>public class DeadlockDemo {<br>    private final Lock lockA = new ReentrantLock(true);<br>    private final Lock lockB = new ReentrantLock(true);<br><br>    public void workerOne(){<br>        lockA.lock();<br>        System.out.println(&quot;Worker one acquire lock A&quot;);<br>        try {<br>            Thread.sleep(200);<br>        }catch (InterruptedException e){<br>            throw new RuntimeException(e);<br>        }<br>        lockB.lock();<br>        lockA.unlock();<br>        lockB.unlock();<br>    }<br><br>    public void workerTwo(){<br>        lockB.lock();<br>        System.out.println(&quot;Worker two acquire lock B&quot;);<br>        try {<br>            Thread.sleep(200);<br>        }catch (InterruptedException e){<br>            throw new RuntimeException(e);<br>        }<br>        lockA.lock();<br>        lockA.unlock();<br>        lockB.unlock();<br>    }<br><br>    public static void main(String[] args) {<br>        DeadlockDemo deadlockDemo = new DeadlockDemo();<br>        new Thread(deadlockDemo::workerOne).start();<br>        new Thread(deadlockDemo::workerTwo).start();<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*IhLV5SaRFcRLTbEGZMD0Xw.png" /></figure><p>Here workerOne needs lockB at the time the workerTwo acquires it. Also, workerTwo needs lockA at the time the workerOne acquires it. Because of that occurs a deadlock. After printing “Worker one acquire lock A” and “Worker two acquire lock B” a deadlock occurs.</p><pre>new Thread(() -&gt; {<br>    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();<br>    while (true){<br>        long[] threadIds = threadMXBean.findDeadlockedThreads();<br>        if(threadIds != null) {<br>            System.out.println(&quot;deadlock detected&quot;);<br>            ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds);<br>            for(long threadId : threadIds){<br>                System.out.println(&quot;Thread with ID&quot;+ threadId+ &quot;in deadlock&quot;);<br>            }<br>            break;<br>        }<br>        try {<br>            Thread.sleep(5000);<br>        }catch (InterruptedException e){<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}).start();</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*zYw0B21C1K_lwQJAcAN7AA.png" /></figure><p>By using this code snippet we can identify IDs of threads that are in deadlocks.</p><p><strong>How to Prevent Deadlocks</strong></p><p>Use timeouts — when the thread is trying to acquire a lock give the timeouts</p><p>Global ordering of locks — All threads must acquire multiple locks in a predefined, consistent global order. Imagine there are two locks, lockA and lockB. If one thread needs both locks, it must always acquire lockA before lockB. If all threads follow this order, circular wait conditions can’t happen.</p><p>Avoid nesting of locks — Prevents acquiring one lock while already holding another and simplifies concurrency control.</p><p>Use thread-safe alternatives</p><p>Next Chapter — Part 7 — Other Important Concepts</p><p><a href="https://gavindualwis99.medium.com/multithreading-in-java-part-7-7efda89578de">https://gavindualwis99.medium.com/multithreading-in-java-part-7-7efda89578de</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124753af7ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 5]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-5-472cade69634?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/472cade69634</guid>
            <category><![CDATA[copyonwritearray]]></category>
            <category><![CDATA[exchanger]]></category>
            <category><![CDATA[sychronized-collections]]></category>
            <category><![CDATA[cyclic-barrier]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 14:45:23 GMT</pubDate>
            <atom:updated>2025-05-04T09:35:14.753Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 5</h3><p><strong>Sychronized Collections</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*0W_DE10-PEM1sJb6Z5mNBg.png" /></figure><p><strong>Cyclic Barrier</strong></p><p>A cyclic barrier allows a set of threads to wait for each other to reach a common barrier point. Once all the threads reach it, the barrier can be reused, as it resets automatically.</p><pre>public class CyclicBarrierDemo {<br>    private static final int NO_OF_THREADS = 4;<br>    private static final int STAGE = 3;<br><br>    private static final CyclicBarrier barrier = new CyclicBarrier(NO_OF_THREADS,() -&gt; {<br>        System.out.println(&quot;All threads reached the barrier. Proceeding...&quot;);<br>    });<br><br>    public static void main(String[] args) {<br>        for(int i=0;i&lt;NO_OF_THREADS;i++){<br>            Thread thread = new Thread(new DemoThread(i));<br>            thread.start();<br>        }<br>    }<br><br>    static class DemoThread implements Runnable {<br><br>        private final int threadId;<br><br>        public DemoThread(int threadId) {<br>            this.threadId = threadId;<br>        }<br><br>        @Override<br>        public void run() {<br>            for(int i=0;i&lt;STAGE;i++){<br>                try {<br>                    Thread.sleep(1000);<br>                } catch (InterruptedException e) {<br>                    throw new RuntimeException(e);<br>                }<br>                System.out.println(&quot;Thread &quot;+ threadId + &quot; completed stage &quot;+ (i+1));<br><br>                try {<br>                    barrier.await();<br>                    System.out.println(&quot;Thread &quot;+ threadId+ &quot; continue execution&quot;);<br>                } catch (InterruptedException e) {<br>                    throw new RuntimeException(e);<br>                } catch (BrokenBarrierException e) {<br>                    throw new RuntimeException(e);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ZoWUpqq5pj0QqcZkEGLn9w.png" /></figure><p>Here, each thread completes three stages. Once one thread reaches the barrier point after completing a stage, it waits for other threads to reach it. barrier.await() waiting for all threads to reach the barrier point. Once all threads complete the stage and reach the barrier point, release the barrier and continue the execution.</p><p><strong>Exchanger</strong></p><p>An exchanger is a synchronized point where two threads can exchange objects. Each thread presents an object to exchange() method. After two threads present their objects to exchange() method swap objects and continue the process.</p><pre>public class ExchangerDemo {<br>    public static void main(String[] args) {<br>        Exchanger&lt;Integer&gt; exchanger = new Exchanger&lt;&gt;();<br>        Thread one = new Thread(new FirstThread(exchanger));<br>        Thread two = new Thread(new SecondThread(exchanger));<br>        one.start();<br>        two.start();<br>    }<br>}<br>class FirstThread implements Runnable{<br><br>    private final Exchanger&lt;Integer&gt; exchanger;<br><br>    public FirstThread(Exchanger&lt;Integer&gt; exchanger){<br>        this.exchanger = exchanger;<br>    }<br><br>    @Override<br>    public void run() {<br>        int dataToSend = 10;<br>        System.out.println(&quot;First thread sending data: &quot;+dataToSend);<br>        try {<br>            Integer receivedData = exchanger.exchange(dataToSend);<br>            System.out.println(&quot;First thread received data: &quot;+receivedData);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}<br><br>class SecondThread implements Runnable{<br>    private final Exchanger&lt;Integer&gt; exchanger;<br><br>    public SecondThread(Exchanger&lt;Integer&gt; exchanger){<br>        this.exchanger = exchanger;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            Thread.sleep(3000);<br>            int dataToSend = 20;<br>            System.out.println(&quot;Second thread sending data: &quot;+dataToSend);<br>            Integer receivedData = exchanger.exchange(dataToSend);<br>            System.out.println(&quot;Second thread received data: &quot;+receivedData);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br><br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*772BcQljyuY9DSXpXE_V2w.png" /></figure><p>Here thread one prints the data that is sent as 10. Then, thread one is presented to the exchange() method. At that time thread two is in the sleep state for 3 seconds. After thread one presents to exchange() method, it waits until thread two presents to exchange() method. After 3 seconds start executing thread two. Thread two print data to send as 20. Then present to exchange() method. Now as both threads present to exchange() method happen the swapping. The output is given as thread one receives data as 20 and thread two receives data as 10 after swapping.</p><p><strong>CopyOnWriteArray</strong></p><p>Here creates a new copy of the underlying array every time you modify it. This is safe for concurrent access of reads and writes.</p><pre>public class CopyOnWriteArrayDemo {<br>    public static void main(String[] args) {<br>        Simulation simulation = new Simulation();<br>        simulation.simulate();<br>    }<br>}<br><br>class Simulation{<br>    private List&lt;Integer&gt; list;<br><br>    public Simulation(){<br>        this.list = new ArrayList&lt;Integer&gt;();<br>        this.list.addAll(Arrays.asList(0,0,0,0,0));<br>    }<br><br>    public void simulate() {<br>        Thread one = new Thread(new WriteTask(list));<br>        Thread two = new Thread(new WriteTask(list));<br>        Thread three = new Thread(new WriteTask(list));<br>        Thread four = new Thread(new ReadTask(list));<br><br>        one.start();<br>        two.start();<br>        three.start();<br>        four.start();<br>    }<br><br>}<br><br>class ReadTask implements Runnable{<br>    private final List&lt;Integer&gt; list;<br><br>    public ReadTask(List&lt;Integer&gt; list){<br>        this.list = list;<br>    }<br>    @Override<br>    public void run() {<br>        while (true){<br>            try {<br>                Thread.sleep(1000);<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>            System.out.println(list);<br>        }<br>    }<br>}<br><br>class WriteTask implements Runnable{<br>    private final List&lt;Integer&gt; list;<br>    private Random random;<br><br>    public WriteTask(List&lt;Integer&gt; list){<br>        this.list = list;<br>        this.random = new Random();<br>    }<br><br>    @Override<br>    public void run() {<br>        while (true) {<br>            try {<br>                Thread.sleep(1200);<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>            list.set(random.nextInt(list.size()), random.nextInt(10));<br>        }<br>    }<br>}</pre><p>Output</p><p>[0, 0, 0, 0, 0]<br>[0, 4, 0, 4, 0]<br>[9, 4, 7, 4, 9]<br>[9, 4, 7, 4, 2]<br>[5, 4, 7, 8, 2]<br>[5, 4, 7, 8, 5]<br>[5, 4, 7, 8, 2]<br>[5, 6, 7, 1, 2]<br>[1, 6, 1, 1, 2]<br>[8, 6, 3, 1, 2]…</p><p>The process that happens here is when a thread needs to read from the array it creates the snapshot of the array and uses that to read. If a thread wants to write to the array it creates a snapshot and performs the write operation. Once the write operation is completed changed array is considered as the latest version of the array.</p><p>Next Chapter — Part 6 — Locks</p><p><a href="https://medium.com/@gavindualwis99/multithreading-in-java-part-6-124753af7ed4">https://medium.com/@gavindualwis99/multithreading-in-java-part-6-124753af7ed4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472cade69634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 4]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-4-ab5a59ac25b5?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5a59ac25b5</guid>
            <category><![CDATA[countdownlatch]]></category>
            <category><![CDATA[blockingqueue]]></category>
            <category><![CDATA[synchronized-collections]]></category>
            <category><![CDATA[concurrenthashmap]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 16:39:54 GMT</pubDate>
            <atom:updated>2025-04-25T04:24:21.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 4</h3><p><strong>Synchronized Collections</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*w71eodoHrVNMnZUMIR726g.jpeg" /></figure><p>Most Java collections are not thread-safe.</p><pre>public class synchronizedCollection {<br>    public static void main(String[] args) throws InterruptedException {<br>        List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br><br>        Thread one = new Thread(() -&gt; {<br>            for(int i=0; i&lt;1000;i++){<br>                list.add(i);<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0; i&lt;1000;i++){<br>                list.add(i);<br>            }<br>        });<br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br><br>        System.out.println(list.size());<br>    }<br><br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*xWLpDbRg1PpQNS7LGPasRQ.png" /></figure><p>According to the code, we are adding a total of 2000 items to the arraylist. But the size of the list shows as 1346. This value differs from time to time. So, we have to make the list thread-safe.</p><p>There are different ways to make a collection thread-safe.</p><ol><li>Using Collections.synchronize() method</li><li>Using the concurrent collections, which are synchronized</li></ol><p>First, use the Collections.synchronized() method.</p><pre>public class synchronizedCollection {<br>    public static void main(String[] args) throws InterruptedException {<br>//        List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br>        List&lt;Integer&gt; list = Collections.synchronizedList(new ArrayList&lt;&gt;());<br><br>        Thread one = new Thread(() -&gt; {<br>            for(int i=0; i&lt;1000;i++){<br>                list.add(i);<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0; i&lt;1000;i++){<br>                list.add(i);<br>            }<br>        });<br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br><br>        System.out.println(list.size());<br>    }<br><br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*W-AU4RJirhmwmcselSJphQ.png" /></figure><p>Here, we are giving the output 2000. This value does not change from time to time. This is because the list has no inconsistency, even though we use it across multiple threads.</p><p>However, using the Collections.synchronized() approach has downsides.</p><ol><li>Coarse-grained locking — Using a single lock to synchronize all the operations in the collection. This means only one thread can access the collection at a given time. This can lead to a lack of concurrency.</li><li>No fail-fast iterators—The Fail-Fast iterator returns a concurrentModificationException if it detects structural modifications to a collection while iterating over it. Collections. The synchronized() approach does not support the fail-fast iterator, which can lead to unnoticed modifications.</li><li>Performance overhead</li></ol><p>Let’s learn about concurrent collections, which are synchronized</p><p><strong>Countdown Latch</strong></p><p>The countdown latch allows one or more threads to wait until a set of operations execution is complete. This is initialized with a count that is the number of operations that need to be completed. Each time an operation execution completes, the countdown is decremented by 1. Once all operations execution is finished, all waiting threads are released.</p><pre>public class Resturant {<br>    public static void main(String[] args) throws InterruptedException {<br>        int noOfChefs = 3;<br>        CountDownLatch latch = new CountDownLatch(noOfChefs);<br>        new Thread(new Chef(&quot;chef A&quot;,&quot;Pizza&quot;,latch)).start();<br>        new Thread(new Chef(&quot;chef B&quot;,&quot;Pasta&quot;,latch)).start();<br>        new Thread(new Chef(&quot;chef C&quot;,&quot;Lasagna&quot;,latch)).start();<br><br>        latch.await();<br>        System.out.println(&quot;all dished prepared&quot;);<br>    }<br>}<br><br>class Chef implements Runnable{<br><br>    private final String name;<br>    private final String dish;<br>    private final CountDownLatch countDownLatch;<br><br>    public Chef(String name, String dish, CountDownLatch countDownLatch) {<br>        this.name = name;<br>        this.dish = dish;<br>        this.countDownLatch = countDownLatch;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            System.out.println(name+&quot; preparing &quot;+dish);<br>            Thread.sleep(2000);<br>            System.out.println(name+&quot; finished &quot;+dish);<br>            countDownLatch.countDown();<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*0gGQPgTcwd7YpFF6ZO_i8g.png" /></figure><p>There are three operations to complete here. So, initialize the latch with count 3. Once an operation is completed, update the latch by countDownLatch.countDown();. Threads await() on the latch until the count becomes 0.</p><p>The countdown latch is not similar to the join() method. The countdown latch is designed to allow one or more threads to wait until a set of operations is complete. The join() method is used to wait for a thread to complete the execution. Simply, countdown latch is used in a multiple-thread context, while join is used in a single-thread context.</p><p>The count of the countdown latch can’t be reset.</p><p><strong>Blocking Queue</strong></p><p>The blocking queue supports blocking operations for adding and retrieving items. If a thread tries to retrieve an item from an empty queue, it will be paused. If a thread tries to add an item to a full queue, it will be blocked until a space is available. This follows the first-in, first-out principle.</p><p>The blocking queue interface is the parent interface, but there are other interfaces as well. The blocking dequeue and transfer queue are sub-interfaces that extend the blocking queue.</p><p>Blocking dequeue is a double-ended queue that allows access to the queue from both ends in a thread-safe manner. In the transfer queue, producers are blocked until a consumer directly receives an item.</p><p>Blocking queue operations</p><p>put(E e) — add element to queue if space is available. If the queue is full, the operation is blocked until a space is available.</p><p>take() — Retrieves and removes the head of the queue. If the queue is empty, the operation blocks until an element is available.</p><p>offer(E e) — add an element to the queue if space is available. This returns true if the element is added successfully. This returns false if the queue is full. This is blocked until a space is available.</p><p>poll() — retrieves and removes the head of the queue. This returns null if the queue is empty. It does not block the queue like the take() operation.</p><p>peek() — retrieves but does not remove the head of the queue. This returns null if the queue is empty.</p><pre>public class BlockingQueueDemo {<br>    static final int QUEUE_CAPACITY = 10;<br>    static BlockingQueue&lt;Integer&gt; taskQueue = new ArrayBlockingQueue&lt;&gt;(QUEUE_CAPACITY);<br><br>    public static void main(String[] args) {<br>        Thread producer = new Thread(() -&gt; {<br>            try {<br>                for(int i=0;i&lt;20;i++){<br>                    taskQueue.put(i);<br>                    System.out.println(&quot;task produced &quot;+i);<br>                    Thread.sleep(100);<br>                }<br>            }catch (InterruptedException e){<br>                throw new RuntimeException(e);<br>            }<br>        });<br><br>        Thread consumerOne = new Thread(() -&gt; {<br>            try {<br>                while (true){<br>                    int task = taskQueue.take();<br>                    processTask(task,&quot;ConsumerOne&quot;);<br>                }<br>            }catch (InterruptedException e){<br>                throw new RuntimeException(e);<br>            }<br>        });<br><br>        Thread consumerTwo = new Thread(() -&gt; {<br>            try {<br>                while (true){<br>                    int task = taskQueue.take();<br>                    processTask(task,&quot;ConsumerTwo&quot;);<br>                }<br>            }catch (InterruptedException e){<br>                throw new RuntimeException(e);<br>            }<br>        });<br>        producer.start();<br>        consumerOne.start();<br>        consumerTwo.start();<br>    }<br>    private static void processTask(int task, String consumerName) throws InterruptedException {<br>        System.out.println(&quot;task &quot;+ task+&quot; being processed by- &quot;+consumerName);<br>        Thread.sleep(1000);<br>        System.out.println(&quot;task &quot;+ task+&quot; consumed by- &quot;+consumerName);<br>    }<br>}</pre><p>Output</p><p>task produced 0<br>task 0 being processed by- ConsumerOne<br>task produced 1<br>task 1 being processed by- ConsumerTwo<br>task produced 2<br>task produced 3<br>task produced 4<br>task produced 5<br>task produced 6<br>task produced 7<br>task produced 8<br>task produced 9<br>task 0 consumed by- ConsumerOne<br>task 2 being processed by- ConsumerOne<br>task produced 10<br>task 1 consumed by- ConsumerTwo<br>task 3 being processed by- ConsumerTwo<br>task produced 11<br>task produced 12<br>task produced 13<br>task 2 consumed by- ConsumerOne<br>task produced 14<br>task 4 being processed by- ConsumerOne<br>task 3 consumed by- ConsumerTwo<br>task 5 being processed by- ConsumerTwo<br>task produced 15<br>task 4 consumed by- ConsumerOne<br>task produced 16<br>task 6 being processed by- ConsumerOne<br>task 5 consumed by- ConsumerTwo<br>task 7 being processed by- ConsumerTwo<br>task produced 17<br>task 6 consumed by- ConsumerOne<br>task 8 being processed by- ConsumerOne<br>task produced 18<br>task 7 consumed by- ConsumerTwo<br>task 9 being processed by- ConsumerTwo<br>task produced 19<br>task 8 consumed by- ConsumerOne<br>task 10 being processed by- ConsumerOne<br>task 9 consumed by- ConsumerTwo<br>task 11 being processed by- ConsumerTwo<br>task 10 consumed by- ConsumerOne<br>task 12 being processed by- ConsumerOne<br>task 11 consumed by- ConsumerTwo<br>task 13 being processed by- ConsumerTwo<br>task 12 consumed by- ConsumerOne<br>task 14 being processed by- ConsumerOne<br>task 13 consumed by- ConsumerTwo<br>task 15 being processed by- ConsumerTwo<br>task 14 consumed by- ConsumerOne<br>task 16 being processed by- ConsumerOne<br>task 15 consumed by- ConsumerTwo<br>task 17 being processed by- ConsumerTwo<br>task 16 consumed by- ConsumerOne<br>task 18 being processed by- ConsumerOne<br>task 17 consumed by- ConsumerTwo<br>task 19 being processed by- ConsumerTwo<br>task 18 consumed by- ConsumerOne<br>task 19 consumed by- ConsumerTwo</p><p>Here, the blocking queue size is 10. 20 elements put into the blocking queue. We are using Thread.sleep() to clarify the execution code. The producer thread puts elements into the queue when space is available. The consumerOne and consumerTwo threads retrieve and remove the head of the queue as soon as the queue is not empty. Likewise, the blocking queue provides a thread-safe data structure.</p><p><strong>Concurrent Map</strong></p><p>The concurrent map is a thread-safe version of a map that allows multiple threads to read and write without explicit synchronization.</p><pre>public class ConcurrentCache {<br>    private static final Map&lt;String,String&gt; cache = new ConcurrentHashMap&lt;&gt;();<br><br>    public static void main(String[] args) {<br>        for(int i=0;i&lt;10;i++){<br>            final int threadNum = i;<br><br>            new Thread(()-&gt;{<br>                String  key = &quot;Key @ &quot;+ threadNum;<br>                for(int j=0;j&lt;3;j++){<br>                    String value;<br>                    try {<br>                        value = getCachedValue(key);<br>                    } catch (Exception e) {<br>                        throw new RuntimeException(e);<br>                    }<br>                    System.out.println(&quot;Thread &quot;+ Thread.currentThread().getName() + &quot;: Key= &quot;+key+&quot;:  Value= &quot;+value);<br>                }<br>            }).start();<br>        }<br>    }<br><br>    private static String getCachedValue(String key) throws Exception {<br>        String value = cache.get(key);<br>        if(value == null){<br>            value = compute(key);<br>            cache.put(key,value);<br>        }<br>        return value;<br>    }<br><br>    private static String compute(String key) throws Exception {<br>        System.out.println(key + &quot; not in cache, so need to compute&quot;);<br>        try {<br>            Thread.sleep(500);<br>        }catch (InterruptedException e){<br>            throw new Exception(e);<br>        }<br>        return &quot;Value for &quot;+key;<br>    }<br>}</pre><p>Output</p><p>Key @ 9 not in cache, so need to compute<br>Key @ 6 not in cache, so need to compute<br>Key @ 8 not in cache, so need to compute<br>Key @ 3 not in cache, so need to compute<br>Key @ 5 not in cache, so need to compute<br>Key @ 0 not in cache, so need to compute<br>Key @ 7 not in cache, so need to compute<br>Key @ 1 not in cache, so need to compute<br>Key @ 4 not in cache, so need to compute<br>Key @ 2 not in cache, so need to compute<br>Thread Thread-9: Key= Key @ 9: Value= Value for Key @ 9<br>Thread Thread-9: Key= Key @ 9: Value= Value for Key @ 9<br>Thread Thread-9: Key= Key @ 9: Value= Value for Key @ 9<br>Thread Thread-0: Key= Key @ 0: Value= Value for Key @ 0<br>Thread Thread-6: Key= Key @ 6: Value= Value for Key @ 6<br>Thread Thread-6: Key= Key @ 6: Value= Value for Key @ 6<br>Thread Thread-5: Key= Key @ 5: Value= Value for Key @ 5<br>Thread Thread-6: Key= Key @ 6: Value= Value for Key @ 6<br>Thread Thread-0: Key= Key @ 0: Value= Value for Key @ 0<br>Thread Thread-5: Key= Key @ 5: Value= Value for Key @ 5<br>Thread Thread-0: Key= Key @ 0: Value= Value for Key @ 0<br>Thread Thread-5: Key= Key @ 5: Value= Value for Key @ 5<br>Thread Thread-1: Key= Key @ 1: Value= Value for Key @ 1<br>Thread Thread-1: Key= Key @ 1: Value= Value for Key @ 1<br>Thread Thread-4: Key= Key @ 4: Value= Value for Key @ 4<br>Thread Thread-4: Key= Key @ 4: Value= Value for Key @ 4<br>Thread Thread-4: Key= Key @ 4: Value= Value for Key @ 4<br>Thread Thread-2: Key= Key @ 2: Value= Value for Key @ 2<br>Thread Thread-7: Key= Key @ 7: Value= Value for Key @ 7<br>Thread Thread-3: Key= Key @ 3: Value= Value for Key @ 3<br>Thread Thread-8: Key= Key @ 8: Value= Value for Key @ 8<br>Thread Thread-3: Key= Key @ 3: Value= Value for Key @ 3<br>Thread Thread-7: Key= Key @ 7: Value= Value for Key @ 7<br>Thread Thread-2: Key= Key @ 2: Value= Value for Key @ 2<br>Thread Thread-1: Key= Key @ 1: Value= Value for Key @ 1<br>Thread Thread-2: Key= Key @ 2: Value= Value for Key @ 2<br>Thread Thread-7: Key= Key @ 7: Value= Value for Key @ 7<br>Thread Thread-3: Key= Key @ 3: Value= Value for Key @ 3<br>Thread Thread-8: Key= Key @ 8: Value= Value for Key @ 8<br>Thread Thread-8: Key= Key @ 8: Value= Value for Key @ 8</p><p>Here, trying to fetch the same key three times, the 1st time cache is empty and should be put to cache. Then, the value is fetched from the cache.</p><p>Next Chapter — Part 5 — Sychronized Collections</p><p><a href="https://gavindualwis99.medium.com/multithreading-in-java-part-5-472cade69634">https://gavindualwis99.medium.com/multithreading-in-java-part-5-472cade69634</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5a59ac25b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 3]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-3-99081b5f3843?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/99081b5f3843</guid>
            <category><![CDATA[executorservice]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[callable-function]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 09:12:29 GMT</pubDate>
            <atom:updated>2025-03-30T07:49:38.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 3</h3><p><strong>Executor Service</strong></p><p>When there are several tasks to execute, it is not easy to make several threads to execute them as creating a thread is expensive. Creating thousands of threads is not a scalable approach.</p><p>To fix that executor service provides a pool of threads to execute tasks. These threads do not kill once the execution is complete rather they are reused to execute another task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*tWK5lS-ZJyFD9pAo0ggoiw.png" /></figure><p>As shown in the image there is a thread pool and a blocking queue where tasks are placed. New tasks are added to the blocking queue. Once the main thread calls the executor service, the task is picked by either thread and executed. Once that task is executed that thread is available for another task.</p><p>There are 4 types of executor services.</p><p><strong>Single Thread Executor</strong></p><pre>public class SingleThreadExecutorDemo {<br>    public static void main(String[] args) {<br>        ExecutorService service = Executors.newSingleThreadExecutor();<br>        for(int i=0;i&lt;10;i++){<br>            service.execute(new Task(i));<br>        }<br>    }<br>}<br><br>class Task implements Runnable{<br>    private final int taskId;<br><br>    public Task(int taskId){<br>        this.taskId = taskId;<br>    }<br><br>    @Override<br>    public void run() {<br>        System.out.println(&quot;task id:&quot;+taskId+&quot;executed from thread&quot;+Thread.currentThread().getName());<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><p>Output</p><p>task id:0 executed from threadpool-1-thread-1<br>task id:1 executed from threadpool-1-thread-1<br>task id:2 executed from threadpool-1-thread-1<br>task id:3 executed from threadpool-1-thread-1<br>task id:4 executed from threadpool-1-thread-1<br>task id:5 executed from threadpool-1-thread-1<br>task id:6 executed from threadpool-1-thread-1<br>task id:7 executed from threadpool-1-thread-1<br>task id:8 executed from threadpool-1-thread-1<br>task id:9 executed from threadpool-1-thread-1</p><p>According to the output each task executes using the same thread. If we don’t use the executor service have to create a thread for each task and execute it.</p><p>In the single-thread executor, there is only one thread. That thread picks a task from the task queue and then executes it. The tasks run sequentially. If that thread is killed executor recreates a new thread and executes tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*WvQX3xW6d5nXGO7IpY6SpA.png" /></figure><p><strong>Fixed Thread Pool Executor</strong></p><pre>public class FixedThreadExecutorDemo {<br>    public static void main(String[] args) {<br>        ExecutorService service = Executors.newFixedThreadPool(4);<br>        for(int i=0;i&lt;10;i++){<br>            service.execute(new Task2(i));<br>        }<br>    }<br>}<br><br>class Task2 implements Runnable{<br>    private final int taskId;<br><br>    public Task2(int taskId){<br>        this.taskId = taskId;<br>    }<br><br>    @Override<br>    public void run() {<br>        System.out.println(&quot;task id:&quot;+taskId+&quot; executed from thread&quot;+Thread.currentThread().getName());<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><p>Output</p><p>task id:0 executed from threadpool-1-thread-1<br>task id:3 executed from threadpool-1-thread-4<br>task id:2 executed from threadpool-1-thread-3<br>task id:1 executed from threadpool-1-thread-2<br>task id:4 executed from threadpool-1-thread-1<br>task id:5 executed from threadpool-1-thread-3<br>task id:6 executed from threadpool-1-thread-4<br>task id:7 executed from threadpool-1-thread-2<br>task id:8 executed from threadpool-1-thread-1<br>task id:9 executed from threadpool-1-thread-3</p><p>In the fixed thread pool, the executor uses a fixed number of threads in the thread pool. Here, the thread pool size is 4. All the tasks are executed using 4 threads. Once a thread completes the execution of one task it will pick another task from the task queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*hemalKc0L590alLXtpE6Mg.png" /></figure><p><strong>Cached Thread Pool Executor</strong></p><pre>public class CachedThreadPoolDemo {<br>    public static void main(String[] args) {<br>        ExecutorService service = Executors.newCachedThreadPool();<br>        for(int i=0;i&lt;10;i++){<br>            service.execute(new Task3(i));<br>        }<br>    }<br>}<br><br>class Task3 implements Runnable{<br>    private final int taskId;<br><br>    public Task3(int taskId){<br>        this.taskId = taskId;<br>    }<br><br>    @Override<br>    public void run() {<br>        System.out.println(&quot;task id:&quot;+taskId+&quot; executed from thread&quot;+Thread.currentThread().getName());<br>        try {<br>            Thread.sleep(500);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><p>Output</p><p>task id:8 executed from threadpool-1-thread-9<br>task id:5 executed from threadpool-1-thread-6<br>task id:0 executed from threadpool-1-thread-1<br>task id:7 executed from threadpool-1-thread-8<br>task id:9 executed from threadpool-1-thread-10<br>task id:1 executed from threadpool-1-thread-2<br>task id:6 executed from threadpool-1-thread-7<br>task id:4 executed from threadpool-1-thread-5<br>task id:2 executed from threadpool-1-thread-3<br>task id:3 executed from threadpool-1-thread-4</p><p>In the cached Thread pool executor doesn’t have a fixed number of threads. There is a synchronized queue here that has space only for one task. Whenever a new task is submitted it goes to the synchronized queue. Then search whether threads are available without a work. If such a thread is available the task is assigned to that thread. If such a thread is not available executor creates a new thread and the task is assigned to it.</p><p>As an example, if 5 threads working on 5 tasks, at that time the 6th task comes to the synchronized queue as other threads are not available create the 6th thread and assign the 6th task.</p><p>When a thread completes execution and if there are no tasks available for executing that thread is killed. A thread can exist without a task only 60s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*h3sH6TRk45b3dZjMxOqWdw.jpeg" /></figure><p><strong>Scheduled Thread Pool Executor</strong></p><pre>public class ScheduleThreadPoolExecutor {<br>    public static void main(String[] args) {<br>        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);<br>        service.scheduleAtFixedRate(new Task4(),1000,2000, TimeUnit.MILLISECONDS);<br>        try {<br>            if(!service.awaitTermination(10000,TimeUnit.MILLISECONDS)){<br>                service.shutdownNow();<br>            }<br>        }catch (InterruptedException e){<br>            service.shutdownNow();<br>        }<br><br><br>    }<br>}<br><br>class Task4 implements Runnable{<br><br>    @Override<br>    public void run() {<br>        System.out.println(&quot;task4 run&quot;);<br>    }<br>}</pre><p>Output</p><p>task4 run<br>task4 run<br>task4 run<br>task4 run<br>task4 run</p><p>The task runs every 2 seconds after 1 second of delay. After 10 seconds it is gracefully shut down if it is not already terminated. As shown in the output task 4 is running every 2 seconds and then shuts down.</p><p>There are two ways of shutdowns shutdown() and shutdownNow().</p><p>In shutdown() previously submitted tasks in the task queue executed and after shutdown. But in shutdownNow() shut down everything.</p><p>Here task queue does not operate sequentially, this operates according to the priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*AdLj7wI03X-31vOOjFDTjA.png" /></figure><p><strong>Ideal Pool Size</strong></p><p>There is no ideal pool size. But generally, the thread pool size equals the number of CPU cores available in the system. But this differs according to the available tasks.</p><p>When there are more CPU-intensive tasks set the pool size to the number of available CPU cores. Here CPU is the bottleneck, adding more threads causes performance degradation due to excessive context switching. When there are I/O intensive tasks set the thread pool size more than available cores. The tasks are waiting for I/O. So threads are in an idle state waiting for the response. Increasing the pool size allows more tasks to be handled concurrently.</p><p>So, there is no idle pool size. It should be set after considering the tasks that need to be executed.</p><p><strong>Callable &amp; Future</strong></p><p>When we have to return something from thread execution we can’t use the runnable interface. So, using the Callable interface.</p><pre>public class CallableDemo {<br>    public static void main(String[] args) throws ExecutionException, InterruptedException {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        Future&lt;Integer&gt; output = executorService.submit(new ReturnValue());<br>        System.out.println(output.get());<br>    }<br>}<br><br>class ReturnValue implements Callable&lt;Integer&gt; {<br><br>    @Override<br>    public Integer call() {<br>        return 12;<br>    }<br>}</pre><p>Output</p><p>12</p><p>The above code shows how that is implemented. As run() is used in runnable, in callable using call().</p><p>In callable can’t use the execute method, have to use the submit method. But in runnable can use either execute or submit when passing to executor service.</p><p>Here using the Future as a blocking mechanism. When Future is calling blocking the main thread until the execution is complete and returns the value. After that, the main thread resumes.</p><pre>public class CallableDemo {<br>    public static void main(String[] args) throws ExecutionException, InterruptedException {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        Future&lt;Integer&gt; output = executorService.submit(new ReturnValue());<br>        System.out.println(output.get());<br>        System.out.println(&quot;execution completed, main thread resume&quot;);<br>    }<br>}<br><br>class ReturnValue implements Callable&lt;Integer&gt; {<br><br>    @Override<br>    public Integer call() throws InterruptedException {<br>        Thread.sleep(1000);<br>        return 12;<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*Ds71Rr6fPXuJUJuMv93tzA.png" /></figure><p>Here when future.get() executes main thread is blocked until the processing is completed. After completing resumes the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*owWx-a8E6DNu5IN59kHzhw.png" /></figure><p>We can give a time duration to wait until execution is completed and after that resume the main thread.</p><pre>public class CallableDemo {<br>    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {<br>        ExecutorService executorService = Executors.newFixedThreadPool(2);<br>        Future&lt;Integer&gt; output = executorService.submit(new ReturnValue());<br>        System.out.println(output.get(1,TimeUnit.SECONDS));<br>        System.out.println(&quot;execution completed, main thread resume&quot;);<br>    }<br>}<br><br>class ReturnValue implements Callable&lt;Integer&gt; {<br><br>    @Override<br>    public Integer call() throws InterruptedException {<br>        Thread.sleep(5000);<br>        return 12;<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*hfpG54qKpr0x_urAGpJghQ.png" /></figure><p>Here the latency in execution is 5 seconds. But blocking time is 1 second. The main thread blocks only 1 second. After 1 second execution is not complete. So, return an exception like this. We can handle this exception if needed.</p><p>Next Chapter — Part 4 — Synchronized Collections</p><p><a href="https://gavindualwis99.medium.com/multithreading-in-java-part-4-ab5a59ac25b5">https://gavindualwis99.medium.com/multithreading-in-java-part-4-ab5a59ac25b5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99081b5f3843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 2]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-2-446f48d50879?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/446f48d50879</guid>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 06:32:45 GMT</pubDate>
            <atom:updated>2025-04-25T04:26:55.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 2</h3><p><strong>Thread</strong> <strong>Synchronization</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*XDJ3z1LbIFuYpFDaFK9mXg.jpeg" /></figure><pre>public class SynchronizationDemo {<br>    private static int counter = 0;<br>    public static void main(String[] args) throws InterruptedException {<br>        Thread one = new Thread(() -&gt;{<br>            for (int i=0;i&lt;10000;i++) {<br>                counter++;<br>            }<br>        });<br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0;i&lt;10000;i++) {<br>                counter++;<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br>        System.out.println(&quot;counter value = &quot;+ counter);<br>    }<br>}</pre><p>Think about the output of this code. Do you think it is 20000?</p><p>Output</p><p>counter value = 18007</p><p>counter value = 16110</p><p>counter value = 16123</p><p>counter value = 13684</p><p>counter value = 14969</p><p>As you can see here the final value of the counter takes different values at different times. That doesn’t have a fixed value. But you will think the output will be 20000 as these two threads run 20000 times.</p><p>The counter value incrementation has three steps. Loading the current value of the counter, increment the counter, and set back the value. (counter = counter + 1)</p><p>For the two threads, the counter is a shared variable. When thread one starts it loads the counter and increases the counter value. (counter = 0, increment value = 1) Thread one is still not set back to the incremented value to counter. At that time thread two comes to the picture and loads the counter&#39;s value.(counter = 0, increment value = 1) The expected value of the counter now is 2 (by incrementing from thread one and thread two). But it is still 1 because of inconsistency. This is why the output of the above program is not 20000.</p><p>To fix this issue there should be mutual execution. That means once a thread accesses the counter that thread should complete all three parts(load, increment, and setting back) Here restricting the access to the shared resource by multiple threads at a given time.</p><p><strong>Synchronized Methods</strong></p><pre>public class SynchronizationDemo {<br>    private static int counter = 0;<br>    public static void main(String[] args) throws InterruptedException {<br>        Thread one = new Thread(() -&gt;{<br>            for (int i=0;i&lt;10000;i++) {<br>                increment();<br>            }<br>        });<br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0;i&lt;10000;i++) {<br>                increment();<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br>        System.out.println(&quot;counter value = &quot;+ counter);<br>    }<br>    private synchronized static void increment(){<br>        counter++;<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*HFBl2eDxhV0nlhZ1ba9Z1g.png" /></figure><p>Here we are using synchronized methods. That means this method can be accessed by only one thread at a given time. Because of that, all the steps are complete. So, here we get the exact output of 20000.</p><p><strong>Problems of Synchronized Methods</strong></p><p>Reduce concurrency and performance bottlenecks — Until the entire synchronized method completes execution, other threads must wait.</p><p>This is unsuitable if we need to synchronize only one section inside a method or synchronize multiple methods together as an atomic operation.</p><p>When a subclass overrides a synchronized method from its superclass, the subclass’s overridden method also becomes synchronized.</p><pre>public class SynchronizationDemo {<br>    private static int counter1 = 0;<br>    private static int counter2 = 0;<br>    public static void main(String[] args) throws InterruptedException {<br>        Thread one = new Thread(() -&gt;{<br>            for (int i=0;i&lt;10000;i++) {<br>                increment1();<br>            }<br>        });<br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0;i&lt;10000;i++) {<br>                increment2();<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br>        System.out.println(&quot;counter value = &quot;+ counter1 +&quot;=&gt;&quot;+counter2);<br>    }<br>    private synchronized static void increment1(){<br>        counter1++;<br>    }<br><br>    private synchronized static void increment2(){<br>        counter2++;<br>    }<br>}</pre><p>Output</p><p>counter value = 10000=&gt;10000</p><p>Even though thread 2 directly does not work on counter 1, thread 2 is blocked as the synchronized method of thread 1. Thread 2 has to wait until the lock is released in thread 1.</p><p>When a thread enters a synchronized method it acquires the intrinsic lock (or monitor lock). If the method is static lock apply for class level. If the method is non-static lock applies for instance.</p><pre>public class Example {<br>    public synchronized void syncMethod() {  // Locks &#39;this&#39;<br>        System.out.println(&quot;Executing synchronized method...&quot;);<br>    }<br><br>    public static synchronized void staticSyncMethod() { // Locks Example.class<br>        System.out.println(&quot;Executing static synchronized method...&quot;);<br>    }<br>}</pre><p><strong>Synchronized Blocks</strong></p><pre>public class LockWithCustomObjects {<br>    private static int counter1 = 0;<br>    private static int counter2 = 0;<br><br>    //custom lock objects<br>    private static final Object lock1 = new Object();<br>    private static final Object lock2 = new Object();<br><br>    public static void main(String[] args) throws InterruptedException {<br>        Thread one = new Thread(() -&gt; {<br>            for(int i=0;i&lt;100000;i++) {<br>                increment1();<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            for(int i=0;i&lt;100000;i++) {<br>                increment2();<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br><br>        one.join();<br>        two.join();<br><br>        System.out.println(&quot;counter 1:&quot;+counter1+&quot;\ncounter 2:&quot;+counter2);<br>    }<br><br>    private static void increment1() {<br>        synchronized (lock1) {<br>            counter1++;<br>        }<br>    }<br><br>    private static void increment2(){<br>        synchronized (lock2) {<br>            counter2++;<br>        }<br>    }<br>}</pre><p>The synchronization blocks are applied for the only critical section of the method instead of the entire method. Because of that other threads don’t have to wait unnecessarily to execute. Here different threads need to acquire separate locks. This allows partial synchronization and more flexibility.</p><p><strong>Wait &amp; Notify</strong></p><p>Threads are waiting until get the chance to execute. When a thread completes execution other threads are notified to execute.</p><pre>public class WaitNotifyDemo {<br>    private static final Object LOCK = new Object();<br><br>    public static void main(String[] args) {<br>        Thread one = new Thread(() -&gt; {<br>            try {<br>                one();<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            two();<br>        });<br><br>        one.start();<br>        two.start();<br><br>    }<br><br>    public static void one() throws InterruptedException {<br>        synchronized (LOCK) {<br>            System.out.println(&quot;hi from thread one&quot;);<br>            LOCK.wait();<br>            System.out.println(&quot;hi from thread one after wait&quot;);<br>        }<br>    }<br><br>    public static void two(){<br>        synchronized (LOCK){<br>            System.out.println(&quot;hi from thread two&quot;);<br>            LOCK.notify();<br>            System.out.println(&quot;hi from thread two after notify&quot;);<br>        }<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*VFh6SCFk8O6DpARAbOO4yQ.png" /></figure><p>As the example given here threads one and two start. First thread one gets a chance to execute and a lock has been acquired. Then it prints 1st line “hi from thread one”. Then the thread is suspended and goes to the waiting state. Then thread two gets the chance to execute and the lock has been acquired. Then print the line “hi from thread two”. Then notify for a waiting thread. When calling notify, whatever the code execution that left over in the particular synchronized block, all those things are executed. So, print “hi from thread two after notify”. Then after that the waiting thread one is executed and prints “hi from thread one after wait”.</p><p>If used notifyAll(), notify all the threads that are waiting for the given lock.</p><p><strong>Producer and Consumer using wait and notify</strong></p><p>The producer and consumer problem is that one or more producer threads generate data and put them into a shared buffer, while one or more consumer threads retrieve and process the data in the shared buffer concurrently.</p><p>When the buffer is full consumer stops generating the data and when the buffer is empty consumer stops consuming.</p><pre>public class ProducerConsumer {<br>    public static void main(String[] args) {<br>        Worker worker = new Worker(5,0);<br><br>        Thread one = new Thread(() -&gt; {<br>            try {<br>                worker.Producer();<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>        });<br><br>        Thread two = new Thread(() -&gt; {<br>            try {<br>                worker.Consumer();<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>        });<br><br>        one.start();<br>        two.start();<br>    }<br>}<br><br>class Worker{<br>    private int sequence = 0;<br>    private final Integer top;<br>    private final Integer bottom;<br>    private final LinkedList&lt;Integer&gt; container;<br>    private final Object lock = new Object();<br><br>    public Worker(Integer top, Integer bottom){<br>        this.top = top;<br>        this.bottom = bottom;<br>        this.container = new LinkedList&lt;&gt;();<br>    }<br><br>    public void Producer() throws InterruptedException {<br>        synchronized (lock){<br>            while (true){<br>                if(container.size() == top){<br>                    System.out.println(&quot;container is full remove items&quot;);<br>                    lock.wait();<br>                }else{<br>                    System.out.println(sequence+&quot; added to container&quot;);<br>                    container.add(sequence++);<br>                    lock.notify();<br>                }<br>                Thread.sleep(5000);<br>            }<br>        }<br>    }<br><br>    public void Consumer() throws InterruptedException {<br>        synchronized (lock){<br>            while (true){<br>                if(container.size() == bottom){<br>                    System.out.println(&quot;container is empty add items&quot;);<br>                    lock.wait();<br>                }else {<br>                    System.out.println(container.removeFirst()+&quot; remove item from container&quot;);<br>                    lock.notify();<br>                }<br>                Thread.sleep(5000);<br>            }<br>        }<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*mMH4Hde2CshK991Z7829gw.png" /></figure><p>In the producer method, add items to the container if it is not full. When notify(), again goes to the synchronized block&#39;s start and adds items until the container is full. The producer thread goes to the wait state when the container is full.</p><p>The consumer thread starts execution. The consumer removes items from the container until it becomes empty. When notify() is called, it again goes to the start of the synchronization block and removes items until the container becomes empty. When the container is empty, the consumer goes to the wait state.</p><p>This is how producer and consumer threads execute using wait() and notify().</p><p>Next Chapter — Part 3 — Executor Service</p><p><a href="https://gavindualwis99.medium.com/multithreading-in-java-part-3-99081b5f3843">https://gavindualwis99.medium.com/multithreading-in-java-part-3-99081b5f3843</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=446f48d50879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java — Part 1]]></title>
            <link>https://gavindualwis99.medium.com/multithreading-in-java-part-1-1ad6be366513?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad6be366513</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[join-method-in-threads]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[runnable-method]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 05:35:06 GMT</pubDate>
            <atom:updated>2025-05-19T10:30:14.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading in Java — Part 1</h3><p><strong>Introduction</strong></p><p>When there are several tasks to do it can perform in several ways. If it is done in a sequential manner that means doing a task one by one (After completing one task then move to the next task)</p><p><strong>Concurrency vs Parallelism</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQe-edKy9IIlOeC3MpVZlQ.gif" /></figure><p>In concurrency managing multiple tasks efficiently. That means executing part of one task, then part of another, and again executing part of the previous task, likewise switching from task to task. This can be achieved using threading. Here requieres only one CPU.</p><p>In parallelism executing several tasks simultaneously. That means several tasks are executed at the same time. This can be achieved using multitasking. This requires more than one CPU.</p><p>A thread is a unit of execution within a given program.</p><p><strong>Pros and Cons of multithreading</strong></p><p>Pros — Utilizing the resources as multithreading prevents the idle state of resources, improves the performance of the programs</p><p>Cons — The synchronizing process is hard, difficult to design and test the multithreading environment</p><p><strong>Thread Lifecycle</strong></p><p>New — State until the thread is started</p><p>Runnable — A thread is ready to execute waiting for the CPU time</p><p>Running — A thread that is executing</p><p>Blocked — A thread that is paused and waiting for CPU time</p><p>Terminated — A thread that completes the execution and end</p><p>The default thread in Java is the main thread. JVM creates this to execute the main method of the program.</p><p><strong>Creating a thread using the runnable interface</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*7R4Lf2AaH_YBAh6OXKZggQ.png" /></figure><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*1UgC2ZAIufGs5TtxF6emPg.png" /></figure><p>According to this output, threads one and two are running without sequence. This happens because the CPU scheduler gives the chance for both threads. Once an available spot finds out to run the thread it’s assigned to the CPU. That time other threads can’t access the CPU and have to wait until they get the chance. That’s why here see a back-and-forth execution of two threads.</p><p><strong>Creating a thread using the thread class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*YEcsOQJi4lmi6NmqGQaZUA.png" /></figure><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*1UgC2ZAIufGs5TtxF6emPg.png" /></figure><p>Here also, the same process happens like implementing from the runnable interface.</p><p><strong>Implementing Runnable interface vs Extends Thread class</strong></p><p>When extending from the thread, the class can extend only one class, we can’t extend any other class even if required. But when implementing from the runnable class we can extend any other class.</p><p>Extending from the thread class creates unique objects for each thread. But when implementing from the runnable interface, share the same object for multiple threads.</p><p><strong>Join method in Java</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*6-w4oIWF3GxbJhjh0yPVdA.png" /></figure><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*BrIC3xT9Oxc8cODOMS0xDQ.png" /></figure><p>According to this example the “start executing the threads” and “done executing the threads” lines first execute and then start executing one and two threads. This happens because of the print lines in the main thread. The main thread gets the highest priority to execute and other threads are in the runnable state until the completion of the main thread. When other threads start execution they run concurrently and independently. Because of that here one and two threads were executed after the main thread execution was completed.</p><p>By using the join method we can keep the main thread wait until the child thread completes execution.</p><p>Example 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfAwFuLGjvYZqqFNkz1J-A.png" /></figure><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*_7YUWna8iRyt11b-dgdBww.png" /></figure><p>Example 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*LUamTEUu5pOjOWsjs4o-5w.png" /></figure><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*yBgfbp8fks8rqqxmK2nDuA.png" /></figure><p>In example 1, thread one starts execution. Because of one.join() the main thread waits until the execution of thread one. After thread one is finished start thread two. But the main thread does not wait until thread two is completed.</p><p>In example 2, thread one and thread two start the execution concurrently. As one.join() the main thread waits until thread one execution is complete. But the main thread does not wait for thread two to complete.</p><p><strong>Daemon Threads</strong></p><p>The threads can be of two types.</p><p>Daemon Threads</p><p>User Threads</p><p>Daemon threads are helper threads and low-priority threads that can be run in the background. JVM terminates daemon threads once all the user threads are terminated.</p><pre>public class DaemonThreadExample {<br>    public static void main(String[] args) {<br>        Thread daemonthread = new Thread(new DaemonThread());<br>        Thread userthread = new Thread(new UserThread());<br><br>        daemonthread.setDaemon(true); //set this thread as daemon <br>        daemonthread.start();<br>        userthread.start();<br>    }<br>}<br><br>class DaemonThread implements Runnable{<br>    public void run(){<br>        for(int i=0;i&lt;500;i++){<br>            try {<br>                Thread.sleep(1000);<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>            System.out.println(&quot;from daemon thread&quot;);<br>        }<br>    }<br>}<br><br>class UserThread implements Runnable{<br>    public void run(){<br>        try {<br>            Thread.sleep(5000);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>        System.out.println(&quot;from user thread&quot;);<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*dOmeA_3ssfVT8AjZnhsnWw.png" /></figure><p>As you can see, after printing the daemon thread 4 times, print the user thread and then terminate. Here, the user thread sleeps for 5000ms. At that period running the daemon thread. After ending that period then start executing the user thread. After the execution of the user thread ends, the daemon thread is terminated.</p><p><strong>Thread Priority</strong></p><p>When there is one CPU, only one thread can execute at a time. Because of that, threads should have a priority to decide which thread should run at a time. The order of threads executing is decided by the thread scheduler. Each thread has a priority from 1 to 10. 1 represents the min_priority and 10 is the max_priority. By default, the priority of a thread is 5, and it is called norm_priority. The threads with the same priority execute in the FIFO manner.</p><pre>public class ThreadPriorityExample {<br>    public static void main(String[] args) {<br>        System.out.println(Thread.currentThread().getName());<br>        System.out.println(Thread.currentThread().getPriority());<br>        Thread.currentThread().setPriority(10);<br>        System.out.println(Thread.currentThread().getPriority());<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*Ie3BUVOcah-UMgULegA1Wg.png" /></figure><p>The priority of the main thread is 5.</p><pre>public class ThreadPriorityExample {<br>    public static void main(String[] args) {<br>        System.out.println(Thread.currentThread().getName());<br><br>        Thread one = new Thread(() -&gt; {<br>            System.out.println(&quot;thread one&quot;);<br>        });<br><br>        one.setPriority(Thread.MAX_PRIORITY);<br>        one.start();<br>    }<br>}</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*JSsl1tz8OQFHCbPQjWLamw.png" /></figure><p>Here, thread one is set to max_priority, and the main thread has priority 5. However, the main thread executes first, although thread one has the highest priority.</p><p>Next Chapter — Part 2 — Thread Sychronization</p><p>https://gavindualwis99.medium.com/multithreading-in-java-part-2-446f48d50879</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad6be366513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consensus Mechanisms Use in Blockchain]]></title>
            <link>https://gavindualwis99.medium.com/consensus-mechanisms-use-in-blockchain-a71f99a1def5?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71f99a1def5</guid>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Fri, 21 Jul 2023 09:35:20 GMT</pubDate>
            <atom:updated>2023-07-21T09:42:04.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*65bmDj0TvrrRXn2gdf762w.png" /></figure><p>Consensus<strong> </strong>mechanism is a fundamental concept in distributed systems like blockchain technology. The consensus mechanism decides which group of nodes or participants reach an agreement on the validity and order of transactions or data that collectively maintain in the network. The consensus mechanisms aim to ensure the network’s consistency, security, and trustworthiness.</p><p>In traditional centralized systems, a single authority (central server) is responsible for validating and approving transactions. As a blockchain network is a decentralized and distributed network it can’t operate like a centralized network. So, consensus mechanisms enable decentralized networks to function smoothly by allowing participants to agree on a single version of the truth without the need for a central intermediary.</p><p>There are various consensus mechanisms used in blockchain networks. Here described some of such consensus mechanisms.</p><h4><strong>Proof of Work (PoW)</strong></h4><p>Proof of Work (PoW) is a consensus algorithm used in blockchain networks to validate transactions and create new blocks. Here the participants of the network (miners) perform a computationally intensive task (computationally challenging puzzle) to find a solution. The first miner to find the correct solution gets the chance to add the next block to the blockchain network. Apart from that, that miner is rewarded with newly minted cryptocurrency. When a miner successfully solves the Proof of Work puzzle by finding the right solution, they immediately broadcast this solution to all the other nodes in the network. This broadcasting ensures that everyone else can quickly verify the validity of the solution.</p><p>When a new block is wanted to add to the blockchain, the miners need to find a nonce(a random number). The nonce combined with the block’s data( transaction data, a timestamp, and a reference to the previous block), results in a hash that meets specific difficulty criteria. Miners start by selecting a random nonce and calculating the hash of the entire block (data + nonce). If the resulting hash doesn’t meet the required difficulty criteria, they try again with a different nonce. The miners keep trying different nonces until they find the valid hash. The first miner who successfully finds a valid hash (meeting the required difficulty criteria) announces it to the network as proof of work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGSDn4SF2R3KZB37SghnJQ.png" /><figcaption>Proof of Work (PoW)</figcaption></figure><p>The proof of Work mechanism is resource-intensive and requires significant computational power, leading to high energy consumption.</p><h4>Proof of Stake (PoS)</h4><p>Proof of Stake (PoS) is a way for blockchain networks to agree on transactions and ensure security without the need for energy-intensive mining like in Proof of Work (PoW). Instead of miners solving puzzles, validators are selected based on the number of coins they hold. The participants in the network who want to become validators need to own a certain amount of coins. This amount of coins they own is known as the stake. The PoS algorithm selects validators to create new blocks and validate transactions based on the stake. Validators who successfully create and validate blocks are rewarded with transaction fees and newly minted coins. Those rewards encourage validators to act honestly and securely in the network. If a validator behaves dishonestly or maliciously, they may lose their staked coins as a penalty, which is known as “slashing.”</p><p>In Proof of Stake (PoS) blockchain networks, there is often a minimum limit or requirement for the number of coins that validators must stake to participate in block validation. The reason why staking more coins increases the likelihood of being chosen as a validator is because the selection process in most PoS algorithms is designed to be “weight-based.” In real-world Proof of Stake (PoS) blockchain networks, staking pools are commonly used to pool together the staked coins of multiple individual participants. These staking pools increase the collective stake, giving the pool a higher chance of being selected to validate blocks or perform tasks compared to individual validators with smaller stakes. When a staking pool successfully completes a task or validates a block, the rewards earned are divided among the members of the pool. Each member receives a portion of the reward based on their individual contribution to the total staked coins in the pool.</p><h4>Delegated Proof of Stake (DPoS)</h4><p>Delegated Proof of Stake (DPoS) is a consensus mechanism used in blockchain networks to achieve consensus and validate transactions. It is a variation of Proof of Stake (PoS). Here the stakeholders can participate as delegates to produce new blocks in the blockchain network. The selection of delegates is typically determined through a voting process. Stakeholders can cast votes for their preferred delegates, and the individuals or entities with the most votes become the active delegates responsible for block production.</p><p>The delegates produce new blocks according to a predefined schedule. Once a delegate produces a new block, they broadcast it to the entire network. All the other nodes in the network receive the proposed block almost simultaneously. In a Delegated Proof of Stake (DPoS) system, block verification is performed by all network nodes, not just the elected delegates responsible for block production. Each node independently verifies the validity of the proposed block and its included transactions. This verification process involves checking the digital signatures, ensuring that the transactions adhere to the consensus rules, and confirming that the sender has enough balance to perform the transactions. If the majority of nodes agree that the proposed block is valid, the block is added to the blockchain. If a delegate fails to validate the block properly, other nodes will reject the block, and it will not be added to the blockchain. The delegates who consistently fail to validate blocks correctly or engage in malicious behavior might face penalties. Penalties could include losing their delegate status and losing some or all of their staked coins.</p><h4>Proof of Authority (PoA)</h4><p>Proof of Authority (PoA) is a consensus mechanism used in some blockchain networks to validate transactions. PoA relies on a group of known and trusted validators who take turns adding blocks to the blockchain. Here there are predefined validators who are known as trusted entities. The validators are selected manually or through a predetermined governance mechanism. These validators could be individuals, organizations, or even specific nodes that have been approved to participate in the consensus process.</p><p>Validators in a PoA network take turns to create new blocks. The frequency of rotation and the process for selecting the next validator can vary depending on the specific PoA implementation. When a validator creates a new block, they sign it with their digital signature to indicate their approval of the block. his signature serves as proof that the block has been created and validated by a legitimate and authorized participant. Consensus is achieved when a majority of the authorized validators agree on the validity of a new block. Since all validators are known and trusted, it is assumed that they will act honestly and follow the network’s rules.</p><p>However, it’s essential to note that PoA does introduce centralization to some extent since the validation process relies on a limited number of trusted validators. As a result, it might not be suitable for public, fully decentralized blockchain networks that aim to be open to anyone as validators. Instead, PoA is commonly used in private or consortium blockchains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71f99a1def5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Blockchain Technology]]></title>
            <link>https://gavindualwis99.medium.com/introduction-to-blockchain-technology-e2e4ec4bad35?source=rss-2b3e6a5dd913------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e4ec4bad35</guid>
            <dc:creator><![CDATA[Gavindualwis]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 06:44:46 GMT</pubDate>
            <atom:updated>2023-07-10T06:44:46.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cE46uFV-EU9fmprgyqN5A.png" /></figure><p>Blockchain technology has emerged as one of the most transformative technological innovations in recent years. Blockchain technology was invented by an anonymous person or group of people using the pseudonym Satoshi Nakamoto. In 2008, blockchain technology was introduced as the underlying technology for the cryptocurrency Bitcoin. Blockchain is a decentralized and distributed digital ledger that records transactions across multiple nodes. Blockchain technology’s unique characteristics make it a promising solution for financial, supply chain management, and healthcare industries beyond cryptocurrencies.</p><p>Here are the key features of blockchain technology.</p><p>Decentralization — Blockchain runs on a decentralized network of nodes. This means that there is no central authority governing the blockchain network.</p><p>Distributed Ledger — The ledger in blockchain is a collection of all the transactions in the network. The blockchain is a distributed ledger that contains a continuously growing list of records called blocks. Each block contains a batch of transactions, a timestamp, and a reference to the previous block, forming a chain of blocks.</p><p>Security — Blockchain technology relies on cryptography to secure the transactions and data stored in the blocks. Each block is linked to the previous one, forming a chain. All block has a unique hash which is generated based on the data in the block. Any change to the block’s data would result in a different hash, making it easy to identify tampering or unauthorized modifications. Because of that once a block is added to the blockchain, altering or tampering with it becomes extremely difficult.</p><p>Consensus Mechanism — Consensus mechanisms play a crucial role in blockchain networks to achieve agreement among multiple participants on the validity of transactions. Common consensus mechanisms are proof-of-work (PoW), proof-of-stake (PoS), proof-of-authority (PoA), delegated proof-of-stake (DPoS), etc. These algorithms ensure that the majority of participants agree on the validity of the transactions in the blockchain network.</p><p>Transparency — Blockchain transactions are generally transparent and visible to all participants in the network. The distributed nature of blockchain ensures that all participants have access to the same copy of the ledger, promoting transparency and accountability.</p><p>Smart Contracts — Smart contracts are self-executing contracts with predefined conditions written into code. Some blockchains support smart contracts. They automatically execute transactions and agreements when specific conditions are met.</p><p>Speed and Efficiency — Blockchain can increase efficiency by automating and digitizing workflows. Smart contracts, which are automated agreements embedded in the blockchain, enable the automatic execution of predefined rules and conditions, reducing the need for manual intervention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e4ec4bad35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>