<?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 Uche Elekwa on Medium]]></title>
        <description><![CDATA[Stories by Uche Elekwa on Medium]]></description>
        <link>https://medium.com/@utchayy?source=rss-2b55b43e612------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PBaNFGKri2s8a09JIKn9kw.png</url>
            <title>Stories by Uche Elekwa on Medium</title>
            <link>https://medium.com/@utchayy?source=rss-2b55b43e612------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:14:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utchayy/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[Java threads — Common operations, race conditions, and synchronization]]></title>
            <link>https://medium.com/@utchayy/java-threads-common-operations-race-conditions-and-synchronization-2824721590ac?source=rss-2b55b43e612------2</link>
            <guid isPermaLink="false">https://medium.com/p/2824721590ac</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Uche Elekwa]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 20:49:28 GMT</pubDate>
            <atom:updated>2025-01-24T20:49:28.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java threads — Common operations, race conditions, and synchronization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*59f76NnuuCR1Dobh" /><figcaption>Photo by <a href="https://unsplash.com/@bkaraivanov?utm_source=medium&amp;utm_medium=referral">Bozhin Karaivanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In modern times of engineering, multithreading is a strong tool that enables software engineers to run multiple processes simultaneously.<br> For example, we want to start a long-running process such as a complex mathematical operation that will take time while running another method simultaneously. Another example is typing in a Word document while another thread/process auto-saves simultaneously. In short, threads are great at allowing us to do a lot of different operations simultaneously without one operation waiting for another operation to complete. This is the beauty of multithreading.</p><p>In the concept of Java, there are two different ways that a thread class can be implemented:</p><p><strong>1. Extending the Thread Class</strong> — Extending the thread class is one way to implement multithreading in Java. Extending the thread class allows the inheritance of all the methods available in the parent thread class. This also gives us fine-grained control over more methods you want to override in the Thread class. If you extend the Thread class, you can directly override its run() method to create and start a thread without needing to manage a separate Runnable instance. This is useful when you don’t need your class to inherit any other class and rather its main purpose is to define a thread.</p><pre>class MyThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Thread is running&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MyThread thread = new MyThread();<br>        thread.start(); // Start the thread<br>    }<br>}</pre><p>Another method you can override from the parent class is the interrupt method. Here, you can have a custom implementation of what you want the interrupt method to do in your thread. This can also be used to do some cleanup behavior such as garbage collection or resource release after that thread is interrupted. Here is an example method:</p><pre>@Override<br>public void interrupt() {<br>    System.out.println(&quot;Thread is being interrupted...&quot;);<br>    super.interrupt();<br>}</pre><p>However , in the real world, overriding methods beyond run() is rare and may complicate the thread behavior so be careful. Only extend threads if you want fine-grained control over the threads advanced behaviour.</p><p>2. <strong>Implementing the Runnable Interface:</strong> This is another way to define a thread that is often considered safer. Why?</p><ul><li>As Java supports single inheritance, implementing the Runnable interface allows your thread class to extend another class or implement other interfaces.</li><li>Runnable interface has only one method to override, which is the run() method. This means your Thread is only executing the main logic rather than inheriting every method from the main Java Thread class. Your code is clean and modular.</li><li>If your thread is tightly coupled to the parent Java thread, it mixes the task logic with the thread lifecycle management. As code complexity grows, your program becomes harder to maintain and test.</li><li>Use Runnable to keep task and thread management separate, ensuring <strong>cleaner, safer, and more maintainable code</strong>.</li></ul><pre>    class MyTask implements Runnable {<br>        @Override<br>        public void run() {<br>            System.out.println(&quot;Task is running by: &quot; + Thread.currentThread().getName());<br>        }<br>    }<br><br>    public class Main {<br>        public static void main(String[] args) {<br>            MyTask task = new MyTask();  // Define the task<br>            Thread thread = new Thread(task); // Assign it to a thread<br>            thread.start();  // Start the thread<br>        }<br>    }</pre><p>The thread goes through different lifecycles such as</p><ul><li>New: This is where the thread is created. Then the method starts and changes the state of the thread to ready</li><li>Ready: After ready, it goes into the run method, this is where the main execution of the thread happens and it starts running</li><li>While running, you can make it go into wait — where it can wait for some operation or resource until it becomes available</li><li>A timed delay means you can make the thread sleep or delay for some time using sleep/wait. Once the sleep time expires it goes back into running. -&gt; Thread.sleep(1000+)</li><li>Blocked — let&#39;s say for example two threads are trying to read or maybe write to one resource file. We shouldn’t allow both access so in this state we can make it blocked until one thread has finished. Once it has finished thread2 can notify thread one to continue. A thread can also lock a resource until it is done using it. If Thread1 wants to block other threads, it calls the wait() function. If it is done with its task, it calls the notify() function</li></ul><h3>COMMON THREAD OPERATIONS</h3><p><strong>Instance methods</strong></p><ul><li>Void join() — when a thread is done, ususally it will terminate but the join method tells the thread to wait for other threads to complete before terminating.</li><li>Void join(long millis) — the length of time it can wait for other threads before terminating.</li><li>Void run() — actual functionality of the thread.</li><li>Void start() — To start the thread.</li></ul><p><strong>Static methods</strong></p><ul><li>Int activeCount() — how many threads are active</li><li>Thread currentThread() — reference to a current thread.</li><li>Void yield() — yield() is a static method in the Thread class that Pauses the current thread temporarily to allow other threads of the same priority or higher to execute.</li></ul><p><strong>Getters and Setters</strong></p><ul><li>Long getId() — get the Id of the thread by JVM.</li><li>String getName()- get the name of the thread set.</li><li>Int getPriority() — the thread priority (By default all threads are 5).</li><li>ThreadState getState() — get the state of the current thread.</li><li>ThreadGroup getThreadGroup().</li><li>Void setName(String name) — set a name you want to remember.</li><li>Void setPrioity(int p) — Set the priority of the thread ranging from 1–10. Higher priority threads get higher CPU time.</li><li>Void setDaemon(boolean d) — a daemon thread is a background thread with the least priority that runs while other threads do some work.</li></ul><p><strong>Inquiry</strong></p><ul><li>Boolean isAlive() — is the thread still alive or terminated?</li><li>Boolean isDaemon() — is the thread a daemon thread?</li><li>Boolean isInterrupted() — is the thread interrupted?</li></ul><h3>RACE CONDITIONS</h3><p>Typically, when one or more threads try to access a shared object or resource and modify its data simultaneously it will lead to unpredictable behaviors or incorrect results. Imagine a thread, sending a data to a printer and another thread also sending data to a printer, the printer may print both information on the same paper. Another instance could be two threads modifying the same data in another class. Let us see an example below where threads are depositing into the same BankAccount object.</p><pre>class BankAccount {<br>    private int balance = 0;<br><br>    public void deposit(int amount) {<br>        balance += amount; // Non-atomic operation<br>    }<br><br>    public int getBalance() {<br>        return balance;<br>    }<br>}<br>     <br>public class Main {<br>            public static void main(String[] args) {<br>                BankAccount account = new BankAccount();<br><br>                Runnable task = () -&gt; {<br>                    for (int i = 0; i &lt; 1000; i++) {<br>                        account.deposit(1);<br>                    }<br>                };<br><br>                Thread t1 = new Thread(task);<br>                Thread t2 = new Thread(task);<br><br>                t1.start();<br>                t2.start();<br>                //Without join method , the Main method thread may end <br>                // before t1 or t2 has completed as both threads are inside <br>                //the Main method thread<br>                try {<br>                    t1.join();//Main thread waits for thread1 to finish<br>                    t2.join();//Main thread waits for thread2 to finsh<br>                } catch (InterruptedException e) {<br>                    e.printStackTrace();<br>                }<br><br>                System.out.println(&quot;Final Balance: &quot; + account.getBalance());<br>            }<br>        }</pre><p>The expected final balance is supposed to be 2000 but because of race conditions, both t1 and t2 are adding to the account balance causing unexpected results such as 1816, 2000, 1976, and other arbitrary results each time the application is run. This is where Synchronized method type comes in.</p><p><strong>ENTER SYNCHRONIZED.</strong></p><p>Each object in Java has an intrinsic lock, when a thread calls a synchronized method, it acquires that lock on the object and releases it after the method finishes. This is to avoid another thread tampering with that method while it is being used by the current thread. To get our guaranteed account balance as 2000, let us add the synchronized keyword to any method/resource that is being shared by more than one thread(Critical Section). In this case, under the task thread, we see that it calls the deposit method. So deposit will now have the synchronized keyword attached to it in the BankAcccount class. Optionally, it can be added to the getBalance (), especially if that method is being called in the task thread.</p><pre>package Multithreading;<br><br>class BankAccount {<br>    private int balance = 0;<br><br>    public synchronized void deposit(int amount) {<br>        balance += amount; // Non-atomic operation<br>    }<br><br>    public int getBalance() {<br>        return balance;<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        BankAccount account = new BankAccount();<br><br>        Runnable task = () -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) {<br>                account.deposit(1);<br>            }<br>        };<br><br>        Thread t1 = new Thread(task);<br>        Thread t2 = new Thread(task);<br><br>        t1.start();<br>        t2.start();<br><br>        try {<br>            t1.join();<br>            t2.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        System.out.println(&quot;Final Balance: &quot; + account.getBalance());<br>    }<br>}</pre><p>Thank you for reading, I hope this article has helped shape your knowledge of multithreading in Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2824721590ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into practical use of Interfaces and Abstract classes in Java]]></title>
            <link>https://medium.com/@utchayy/deep-dive-into-practical-use-of-interfaces-and-abstract-classes-in-java-c1ae19f88052?source=rss-2b55b43e612------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1ae19f88052</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Uche Elekwa]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 20:42:30 GMT</pubDate>
            <atom:updated>2024-12-20T20:42:30.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1JM3LsgdOXT6Hiu" /><figcaption>Photo by <a href="https://unsplash.com/@lanceanderson?utm_source=medium&amp;utm_medium=referral">Lance Anderson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>In object-oriented programming, Java provides several key building blocks to help you design clean, extensible, and maintainable code. Two of the most fundamental concepts are interfaces and abstract classes. While both serve as blueprints for creating classes, each one solves slightly different design problems. Understanding when to choose one over the other can help you create more flexible architectures and avoid headaches down the line.</p><p>In this article, we’ll go beyond the textbook definitions and dive into some practical, real-world use cases of interfaces and abstract classes in Java. By the end, you’ll have a clearer understanding of how to leverage these features to write more modular and testable code.</p><p><strong>Recap: Interfaces vs. Abstract Classes</strong></p><p>Before we delve into more practical scenarios, let’s quickly restate the key differences — just to ensure we’re on the same page.</p><p><strong>Interfaces:</strong></p><ul><li><strong>What they are:</strong> Contracts that specify which methods a class must implement, without dictating how.</li></ul><p><strong>Key characteristics:</strong></p><ul><li>They can contain abstract methods (by default in older Java versions), static methods, and default methods.</li><li>A class can implement multiple interfaces, promoting a form of multiple inheritance.</li><li>They do not hold state (no instance variables other than implicitly static and final fields).</li></ul><p><strong>Abstract Classes:</strong></p><ul><li><strong>What they are:</strong> Classes that cannot be instantiated directly and can contain both abstract and concrete methods.</li></ul><p><strong>Key characteristics:</strong></p><ul><li>Can hold state (instance variables) and provide partial implementations.</li><li>Only one abstract class can be extended by a given subclass.</li><li>Perfect for setting up foundational behavior that all subclasses should share, but still leaving some methods abstract for subclasses to flesh out.</li></ul><p>With the basics established, let’s move into more nuanced territory.</p><p><strong>1. Designing Clean APIs With Interfaces</strong></p><p>Interfaces are essential when you want to define roles and capabilities decoupled from implementation details. This is frequently the case when building APIs, frameworks, or libraries consumed by multiple teams.</p><p><strong>Example Scenario:</strong></p><p>Suppose you’re building a payment processing module for an e-commerce platform. Different payment methods (credit card, PayPal, bank transfer) might share the same contract: they need to be able to authorizePayment(), captureFunds(), and refund(). You can define an interface like this:</p><pre>public interface PaymentGateway {<br>    boolean authorizePayment(double amount);<br>    boolean captureFunds(String transactionId, double amount);<br>    boolean refund(String transactionId, double amount);<br>}</pre><p><strong>Why use an interface here?</strong></p><p>• Each payment provider can implement these methods differently. A PayPal class might call PayPal’s REST API, while a Stripe class might use Stripe’s SDK.</p><p>• The client code that uses PaymentGateway doesn’t care about which provider is underneath. It just knows these methods are available and consistent across implementations.</p><p>• Interfaces allow you to seamlessly add new payment methods later without changing existing code.</p><p><strong>Takeaway:</strong></p><p>Use interfaces to define a contract and enable polymorphism. This ensures that clients of the code depend only on abstractions, not on concrete implementations — a key principle of SOLID design (the Dependency Inversion Principle).</p><p><strong>2. Introducing Common Behavior With Abstract Classes</strong></p><p>Abstract classes come into play when you need to provide partial implementations or share common state among subclasses. They are ideal when you know that all subclasses need a certain core functionality or a set of fields, but you still want to leave some room for customization.</p><p><strong>Example Scenario:<br></strong>Imagine you’re building a file processing framework. All file processors should be able to do some common pre-processing (like reading a file into memory), and some common post-processing (like logging the processing time). But each type of file processor (CSV, JSON, XML) will have its own logic for handling the file’s contents.</p><p>You can start with an abstract class:</p><pre>public abstract class AbstractFileProcessor {<br>    protected File file;<br>    <br>    public AbstractFileProcessor(File file) {<br>        this.file = file;<br>    }<br>    <br>    // A template method pattern: the general workflow<br>    public final void processFile() {<br>        readFile();<br>        parseFileContents(); // abstract method to be implemented by subclasses<br>        logProcessing();<br>    }<br>    <br>    private void readFile() {<br>        // Common logic to read the file from disk<br>    }<br>    <br>    protected abstract void parseFileContents();<br>    <br>    private void logProcessing() {<br>        // Common logging code<br>    }<br>}</pre><p><strong>Why use an abstract class here?</strong></p><p>• You want to ensure that all file processors follow a specific workflow (read, then parse, then log).</p><p>• You offer a partial implementation that’s reused by all subclasses, reducing code duplication.</p><p>• By forcing subclasses to implement parseFileContents(), you allow them to customize that part of the process without changing the overarching template.</p><p><strong>Takeaway:</strong></p><p>Choose abstract classes when you have a clear parent-child relationship and you need to enforce a certain structure or shared logic. This is often useful when employing design patterns like the <strong>Template Method</strong> pattern.</p><p><strong>3. Guidelines for Choosing Between Interfaces and Abstract Classes</strong></p><p>To summarize the decision-making process:</p><p><strong>Use Interfaces When:</strong></p><ul><li>You’re defining a capability or contract that can be implemented in multiple, unrelated hierarchies.</li><li>You want to ensure loose coupling and adhere to dependency inversion principles.</li><li>You don’t need shared state or guaranteed common behavior.</li></ul><p><strong>Use Abstract Classes When:</strong></p><ul><li>You have a well-defined inheritance hierarchy, and all subclasses should share certain fields and behaviors.</li><li>You want to avoid code duplication by offering partial implementations.</li><li>You need to ensure a common lifecycle or template method pattern that all subclasses must follow.</li></ul><p><strong>Consider Using Both:</strong></p><ul><li>Sometimes, you’ll use interfaces to define the core contract and then provide an abstract class that implements that interface with some partial logic. This gives your consumers the freedom to use the abstract class for convenience or implement the interface from scratch if they prefer.</li></ul><p><strong>Practical Tips for the Real World</strong></p><p>• <strong>Evolving your code over time:</strong> Start with interfaces for maximum flexibility. Later, if certain implementation details consistently repeat, introduce an abstract base class to encapsulate common logic.</p><p>• <strong>Composition over inheritance:</strong> Don’t forget that both interfaces and abstract classes are tools, not silver bullets. Sometimes it’s better to compose objects rather than rely on extended hierarchies.</p><p>• <strong>Testing and Mocking:</strong> Interfaces are easier to mock in unit tests since you can quickly create a test double. This can be a strong motivator to lean on interfaces when designing code meant to be tested extensively.</p><p>• <strong>API Stability:</strong> If you’re designing a public API, interfaces give you a stable contract and keep you flexible. Default methods can help you evolve the interface without breaking backward compatibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ae19f88052" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>