Java Concurrency: Thread Confinement

Java Concurrency: Thread Confinement

Java Concurrency: Thread Confinement - Learn more about concurrency problems and thread confinement in Java.

In this blog, we are going to explore thread confinement, what it means, and how we achieve it. So, let’s dive straight into it.

Thread Confinement

Most concurrency problems occur only when we want to share a mutable variable, or mutable state, between threads. If a mutable state is shared between multiple threads, then all of them will be able to read and modify the value of the state, thus resulting in incorrect or unexpected behavior. One way to avoid this problem is to simply not share the data between the threads. This technique is known as thread confinement and is one of the simplest ways of achieving thread safety in our application.

The Java language, in itself, does not have any way of enforcing thread confinement. Thread confinement is achieved by designing your program in a way that does not allow your state to be used by multiple threads and is, thus, enforced by the implementation. There are a few types of thread confinement, as described below.

Ad-Hoc Thread Confinement

Ad-hoc thread confinement describes a way of thread confinement, where it is the total responsibility of the developer, or the group of developers working on that program, to ensure that the use of the object is restricted to a single thread. This approach is very very fragile and should be avoided in most cases.

One special case that comes under Ad-hoc thread confinement applies to volatile variables. It is safe to perform read-modify-write operations on the shared volatile variable as long as you ensure that the volatile variable is only written from a single thread. In this case, you are confining the modification to a single thread to prevent race conditions, and the visibility guarantees for volatile variables ensure that other threads see the most up to date value.

Stack Confinement

Stack confinement is confining a variable, or an object, to the stack of the thread. This is much stronger than Ad-hoc thread confinement, as it is limiting the scope of the object even more, by defining the state of the variable in the stack itself. For example, consider the following piece of code:

private long numberOfPeopleNamedJohn(List<Person> people) {
  List<Person> localPeople = new ArrayList<>();
  localPeople.addAll(people);
  return localPeople.stream().filter(person -> person.getFirstName().equals("John")).count();
}

In the above code, we pass on a list of person but do not directly use it. We, instead, create our own list, which is local to the currently executing thread, and add all the person in** people to localPeople. Since we are defining our list in the numberOfPeopleNamedJohn method only, this makes the variable localPeople stack confined, as it exists on stack of one thread, and thus cannot be accessed by any other thread. This makes localPeople **thread safe. The only thing we need to take care of here is that we should not allow localPeople to escape the scope of this method, to keep it stack confined. This should also be documented or commented when defining this variable, as generally, it’s only in the current developer’s mind to not let it escape, and in future, another developer may mess up.

ThreadLocal

ThreadLocalallows you to associate a per-thread value with a value-holding object. It allows you to store different objects for different threads and maintains which object corresponds to which thread. It has set and get accessor methods which maintain a separate copy of the value for each thread that uses it. The get()** **method always returns the most updated value passed to set() from the currently executing thread. Let’s look at an example:

public class ThreadConfinementUsingThreadLocal {
    public static void main(String[] args) {
        ThreadLocal<String> stringHolder = new ThreadLocal<>();
        Runnable runnable1 = () -> {
            stringHolder.set("Thread in runnable1");
            try {
                Thread.sleep(5000);
                System.out.println(stringHolder.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Runnable runnable2 = () -> {
            stringHolder.set("Thread in runnable2");
            try {
                Thread.sleep(2000);
                stringHolder.set("string in runnable2 changed");
                Thread.sleep(2000);
                System.out.println(stringHolder.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Runnable runnable3 = () -> {
            stringHolder.set("Thread in runnable3");
            try {
                Thread.sleep(5000);
                System.out.println(stringHolder.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable2);
        Thread thread3 = new Thread(runnable3);
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

In the above example, we have executed three threads, using the same ThreadLocal object stringHolder. As you can see here, we have, first of all, set one string in every thread in the stringHolder object, making it contain three strings. Then, after some pause, we have changed the value from just the second thread. Below was the output of the program:

string in runnable2 changed
Thread in runnable1
Thread in runnable3

As you can see in the above output, the String for thread 2 changed, but the strings for thread 1 and thread 3 were unaffected. If we do not set any value before getting the value on a specific thread from ThreadLocal, then it returns null. After a thread is terminated, thread-specific objects in ThreadLocal become ready for garbage collection.

That is all about thread confinement. I hope this blog was helpful for you and you got to learn something new. Thanks and happy blogging!

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

.NET or Java for Web Development

.NET or Java for Web Development

Developers are often in a dilemma when trying to choose between technologies for their projects. Comparing two or more is quite daunting and confusing at times. In this article, we will focus on comparing .NET and Java.

Thinking of adopting one of these technologies for your next web development project? Read on for a basic overview.

Developers are often in a dilemma when trying to choose between technologies for their projects. Comparing two or more is quite daunting and confusing at times. In this article, we will focus on comparing .NET and Java.

The two are quite different in structure but are predisposed to comparison because of their demand when there is a call for complex and large-scale applications.

While .NET is a framework that can use several languages, Java, on the other hand, is a programming language itself.

A debate is often sparked during comparison among business owners and developers when it comes to choosing between the two. In fact, it is common for people to switch between the two periodically.

.NET, under the auspices of its framework, encompasses C#, which is basically Java, and here lies the challenge in contrasting between the better of the two. This article describes how the two are different while showing their similarity.

What Is Common to Both Java and .NET?

They Are Developed for Heavy Applications

Heavy execution, complex architecture, systems with high loads, and applications with big data specifications are some of the things that can be executed by both Java and C# in the .NET framework. This accords them the high adoption rates in technologies in the enterprise level which proves their scalability and reliability.

They Are Multipurpose

Ranging from subtle to overt, both Java and the .NET framework can be run on desktops, mobile applications, and servers. They are both widely used in the enterprise market. Both Java and C# are 'write one run anywhere' type languages.

They Are Similar in Their Syntax

C# in the .NET framework is derived from the Java language. This proves that the syntaxes of Java and C# are the same except for some basic modifications that were made. A basic syntax is common between the two since Java uses syntax from C++ and C# uses a variety of C languages and style including C, C++, and Java.

Both Are Object-Oriented

A common standard, object-oriented programming, is a basic principle of software development. Having their structure in modules, both Java and .NET are flexible and allow for code reuse while having good troubleshooting expansions.

Garbage Collection

Common to low-level languages, recalling is necessary if you have to free up space during memory administration which makes it a repetitive process. However, in .NET and Java there are no memory spills since objects that are not in use are evacuated.

Single Inheritance

Both C# and Java reinforce single inheritance. This means that a single path is always available from a base class to an inferred class.

Interfaces

Whenever methods are unique in an interface for a dynamic class, it defines an interface. A dynamic method on the other and is one that does not encompass its usage point of interest. Any interface characterization, in terms of the property, has code overseeing it, which is provided for actualization based on a specified class for its actualization.

Some of the Differences

Both Are Portable but One Exceeds the Other

Migrating between Java platforms is easy compared to the .NET framework, which is time-consuming and difficult.

Both Have Fundamental Data Types but One Exceeds the Other

.NET incorporates more fundamental data types than Java. It also allows for more extension of these value types.

They Interact Well With Different Languages

Both Java and .NET have their own languages, which they can easily integrate and work with. Examples for Java include Clojure and Groovy while .NET includes visual basic, F# and C#, among others.

Choosing .NET Core or Java for your web development project is really dependent on the type of project, the resources you have, and many other factors.

Happy web developing!