Understanding of Thread Safety in Java

Understanding of Thread Safety in Java

What Does Thread Safety Mean in Java? What does it actually mean to be ''thread-safe?''

What Does Thread Safety Mean in Java? What does it actually mean to be ''thread-safe?''

Thread safety in Java means that the methods of a class are either atomic or quiescent. So what does atomic and what does quiescent mean? And why are there no other types of thread-safe methods in Java?

What Does it Mean to Be "Atomic?"

A method is atomic when the method call appears to take effect instantaneously. So, other threads either see the state before or after the method call but no intermediate state. Let us look at a non-atomic method to see how an atomic method makes a class thread-safe. You can download the source code from all examples on GitHub.

public class UniqueIdNotAtomic {
    private volatile long counter = 0;
    public  long nextId() { 
        return counter++;   
    }   
}

The class UniqueIdNotAtomic creates unique Ids by using the volatile variable counter. I use a volatile field, line 2, to make sure that the threads always see the current values, as explained in greater detail here. To see if this class is thread-safe, we use the following test:

public class TestUniqueIdNotAtomic {
    private final UniqueIdNotAtomic uniqueId = new UniqueIdNotAtomic();
    private long firstId;
    private long secondId;
    private void updateFirstId() {
        firstId  = uniqueId.nextId();
    }
    private void updateSecondId() {
        secondId = uniqueId.nextId();
    }
    @Test
    public void testUniqueId() throws InterruptedException {    
        try (AllInterleavings allInterleavings = 
                new AllInterleavings("TestUniqueIdNotAtomic");) {
        while(allInterleavings.hasNext()) { 
        Thread first = new Thread( () ->   { updateFirstId();  } ) ;
        Thread second = new Thread( () ->  { updateSecondId();  } ) ;
        first.start();
        second.start();
        first.join();
        second.join();  
        assertTrue(  firstId != secondId );
        }
        }
    }

}

To test if the counter is thread-safe, we need two threads, created in lines 16 and 17. We start those two threads, lines 18 and 19. And then, we wait until both are ended using thread join, lines 20 and 21. After both threads are stopped, we check if the two Ids are unique, as seen in line 22.

To test all thread interleavings, we put the complete test in a while loop iterating over all thread interleavings using the class AllInterleavings from vmlens, line 15.

Running the test, we see the following error:

java.lang.AssertionError: 
    at org.junit.Assert.fail(Assert.java:91)
    at org.junit.Assert.assertTrue(Assert.java:43)

The reason for the error is that since the operation ++ is not atomic, the two threads can override the result of the other thread. We can see this in the report from vmlens:

In the case of the error, both threads first read the variable counter in parallel. And then, both create the same id. To solve this problem, we make the method atomic by using a synchronized block:

private final Object LOCK = new Object();
public  long nextId() {
  synchronized(LOCK) {
    return counter++;   
  } 
}

Now, the method is atomic. The synchronized block makes sure that other threads cannot see the intermediate state of the method.

Methods that do not access shared state are automatically atomic. The same is true for classes with the read-only state. Therefore, stateless and immutable classes are an easy way to implement thread-safe classes. All their methods are automatically atomic.

Not all usages of atomic methods are automatically thread-safe. Combining multiple atomic methods for the same values typically leads to race conditions. Let us look at the atomic method get and put from ConcurrentHashMap to see why. Let us use those methods to insert a value in the map when no previous mapping exists:

public class TestUpdateTwoAtomicMethods {
    public void update(ConcurrentHashMap  map)  {
            Integer result = map.get(1);        
            if( result == null )  {
                map.put(1, 1);
            }
            else    {
                map.put(1, result + 1 );
            }   
    }
    @Test
    public void testUpdate() throws InterruptedException    {
        try (AllInterleavings allInterleavings = 
           new AllInterleavings("TestUpdateTwoAtomicMethods");) {
        while(allInterleavings.hasNext()) { 
        final ConcurrentHashMap  map = 
           new  ConcurrentHashMap(); 
        Thread first = new Thread( () ->   { update(map);  } ) ;
        Thread second = new Thread( () ->  { update(map);  } ) ;
        first.start();
        second.start();
        first.join();
        second.join();  
        assertEquals( 2 , map.get(1).intValue() );
        }
        }
    }   
}

The test is similar to the previous test. Again, we use two threads to test if our method is thread-safe, lines 18 and 19. An again, we test after both threads finished if the result is correct, line 24. Running the test, we see the following error:

java.lang.AssertionError: expected: but was:
    at org.junit.Assert.fail(Assert.java:91)
    at org.junit.Assert.failNotEquals(Assert.java:645)

The reason for the error is that the combination of the two atomic methods, get and put, is not atomic. So, the two threads can override the result of the other thread. We can see this in the report from vmlens:

In the case of the error, both threads first get the value in parallel. And then, both create the same value and put it into the map. To solve this race condition, we need to use one method instead of two. In our case, we can use the single method compute instead of the two methods, get and put:

public void update() {
  map.compute(1, (key, value) -> {
    if (value == null) {
        return 1;
    } 
    return value + 1;
  });
}

This solves the race condition since the method compute is atomic. While all operations which operate on the same element of ConcurrentHashMap are atomic, operations that operate on the complete map like size are quiescent. So, let us see what quiescent means.

What Does it Mean to Be "Quiescent?"

Quiescent means that we need to make sure that no other methods are currently running when we call the quiescent method. The following example shows how to use the quiescent method size of the ConcurrentHashMap:

ConcurrentHashMap  map = 
    new  ConcurrentHashMap();
Thread first  = new Thread(() -> { map.put(1,1);});
Thread second = new Thread(() -> { map.put(2,2);});
first.start();
second.start();
first.join();
second.join();  
assertEquals( 2 ,  map.size());

By waiting until all threads are finished using thread join, we make sure that no other threads are accessing the ConcurrentHashMap when we call the method size.

The method size uses a mechanism also used in the class  java.util.concurrent.atomic.LongAdderLongAccumulatorDoubleAdder, and DoubleAccumulator to avoid contention. Instead of using a single variable for storing the current size, it uses an array. Different threads update different parts of the array, thereby avoiding contention. The algorithm is explained in more detail in the Java doc of Striped64.

The quiescent classes and methods are useful for collecting statistics under high contention. After you collected the data, you can use a single thread to evaluate the collected statistics.

Why Are There No Other Thread-Safe Methods in Java?

In theoretical computer science, thread safety means that a data structure fulfills a correctness criterion. The most common used correctness criterion is linearizable, which means that the methods of the data structure are atomic.

For common data structures exists a provable linearizable concurrent data structures, see the book The Art of multiprocessor programming by Maurice Herlihy and Nir Shavit. But to make a data structure linearizable, an expensive synchronization mechanism like compare and swap is needed, see the paper Laws of Order: Expensive Synchronization in Concurrent Algorithms Cannot be Eliminated to learn more.

Therefore, other correctness criteria like quiescent are investigated. So, I think the question is not "why are there no other types of thread-safe methods in Java?" but rather, when will there be other types of thread safety available in Java?

Conclusion

Thread safety in Java means that the methods of a class are either atomic or quiescent. A method is atomic when the method call appears to take effect instantaneously. Quiescent means that we need to make sure that no other methods are currently running when we call the quiescent method.

Currently, quiescent methods are only used to collect statistics, like the size of the ConcurrentHashMap. For all other use cases, atomic methods are used. Let us wait and see if the future brings additional types of thread-safe methods.

Thank you for reading !

Free Online Eclipse Tutorial For Beginners : Learn Java IDE in 10 Steps | Simpliv

Free Online Eclipse Tutorial For Beginners : Learn Java IDE in 10 Steps | Simpliv

Free Online Eclipse Tutorial For Beginners: Learn Java IDE in 10 Steps

Description
Eclipse is the most popular Open Source Java IDE. More developers use Eclipse than any other tool for Java Programming.

In this course, we take you on a fun ride with Eclipse.

By the end of this course, you would have a number of Eclipse tips and tricks up your sleeve. You will also understand various features of Eclipse - Views, Perspectives, Debugger, Save Actions, Plugins and Code Generation.

You will improve your productivity with Eclipse Shortcuts . You will also learn to import projects from Git and the basics of Maven projects.

Course is Organised into 11 Steps : Experienced Eclipse Developers can give Step 0 a skip

Step 0 : Eclipse Basics - Workspace & Your First Java File
Step 1 : Most Important Editing Shortcuts ctrl-1 and ctrl-space
Step 2 : Debugging Java Programs
Step 3 : Eclipse Short Cuts
Step 4 : Refactoring with Eclipse
Step 5 : Code Generation with Eclipse
Step 6 : Automate with Save Actions
Step 7 : Eclipse Views
Step 8 : Eclipse Perspectives
Step 9 : Plugins
Step 10 : Setting up Projects From Git and Maven
Who is the target audience?

Students who want to learn Programming with Eclipse
Students who have some experience with Eclipse but who want to learn a lot more about Eclipse
Students Learning Java
Basic knowledge
Some programming experience with Java will be handy
What will you learn
Be more productive with Eclipse
Understand Eclipse Basics : Views, Perspectives, Shortcuts, Code Generation & Plugins
Make use of Eclipse Save Actions Features
To continue:

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

This program on Java programing from Simpliv’s experts uses Java and an Integrated Development Environment (IDE). Just download this, with their help of course, and open your way to hundreds of lines of source code, and hundreds of lines of comments. That is some Java programming learning!

Description
Taught by a Stanford-educated, ex-Googler, husband-wife team
This course will use Java and an Integrated Development Environment (IDE). Never fear, we have a detailed video on how to get this downloaded and set up.
Hundreds of lines of source code, and hundreds of lines of comments - just download and open in your IDE!
A Java course for everyone - accessible yet serious, to take you from absolute beginner to an early intermediate level

Let’s parse that.

This is a Java course for everyone. Whether you are a complete beginner (a liberal arts major, an accountant, doctor, lawyer) or an engineer with some programming experience but looking to learn Java - this course is right for you.
The course is accessible because it assumes absolutely no programming knowledge, and quickly builds up using first principles alone
Even so, this is a serious Java programming class - the gradient is quite steep, and you will go from absolute beginner to an early intermediate level
The course is also quirky. The examples are irreverent. Lots of little touches: repetition, zooming out so we remember the big picture, active learning with plenty of quizzes. There’s also a peppy soundtrack, and art - all shown by studies to improve cognition and recall.
What's Covered:

Programming Basics: What programming is, and a carefully thought-through tour of the basics of any programming. Installing and setting up an IDE and writing your first program
The Object-Oriented Paradigm: Classes, Objects, Interfaces, Inheritance; how an OO mindset differs from a functional or imperative programming mindset; the mechanics of OO - access modifiers, dynamic dispatch, abstract base classes v interfaces. The underlying principles of OO: encapsulation, abstraction, polymorphism
Threading and Concurrency: A deep and thorough study of both old and new ways of doing threading in Java: Runnables, Callables, Threads, processes, Futures, Executors.
Reflection, Annotations: The how, what and why - also the good and bad
Lambda Functions: Functional constructs that have made the crossover into the mainstream of Java - lambda functions, aggregate operators.
Modern Java constructs: Interface default methods; properties and bindings too. Also detailed coverage of Futures and Callables, as well as of Lambda functions, aggregation operators. JavaFX as contrasted with Swing.
Packages and Jars: The plumbing is important to understand too.
Language Features: Serialisation; why the Cloneable interface sucks; exception handling; the immutability of Strings; the Object base class; primitive and object reference types; pass-by-value and pass-by-object-reference.
Design: The MVC Paradigm, Observer and Command Design Patterns.
Swing: Framework basics; JFrames, JPanels and JComponents; Menus and menu handling; Trees and their nuances; File choosers, buttons, browser controls. A very brief introduction to JavaFX.
Programming Drills (code-alongs, with source code included)

Serious stuff:
A daily stock quote summariser: scrapes the internet, does some calculations, and outputs a nice, formatted Excel spreadsheet.
A News Curation app to summarise newspaper articles into a concise email snippet using serious Swing programming
Simple stuff:
Support with choosing a programming environment; downloading and setting up IntelliJ.
Simple hello-world style programs in functional, imperative and object-oriented paradigms.
Maps, lists, arrays. Creating, instantiating and using objects, interfaces
Who is the target audience?

Yep! Folks with zero programming experience - liberal arts majors, doctors, accountants, lawyers
Yep! Engineering students from non-CS majors looking to learn fairly serious programming
Nope! Experienced Java programmers - this class will be boring for you:)
Yep! Computer Science students or software engineers with no experience in Java, but experience in Python, C++ or even C#. You might need to skip over some bits, but in general the class will still have new learning to offer you :-)
Basic knowledge
No prior programming experience needed:)
The class will make use of Java and an IDE - never fear, we have a detailed video to walk you through the process of setting this up
What will you learn
Write Java programs of moderate complexity and sophistication (at an early to middling intermediate level)
Understand Object-Oriented programming concepts at the level where you can have intelligent design conversations with an experienced software engineer
Manage concurrency and threading issues in a multi-threaded environment
Create and modify files (including Excel spreadsheets) and download content from the internet using Java
Use Reflection, Annotations, Lambda functions and other modern Java language features
Build serious UI applications in Swing
Understand the Model-View-Controller paradigm, the Observer and Command Design patterns that are at the heart of modern UI programming
Gain a superficial understanding of JavaFX and Properties and Bindings
Understand the nuances of Java specific constructs in serialisation, exception-handling, cloning, the immutability of strings, primitive and object reference types
To continue:

Complete Java Tutorial Step by Step - Become a Programmer

Complete Java Tutorial Step by Step - Become a Programmer

Simpliv LLC, a platform for learning and teaching online courses. We basically focus on online learning which helps to learn business concepts, software technology to develop personal and professional goals through video library by recognized industry experts and trainers.

Description
This course will help you to learn Java from grounds up, starting from the basic up to advance level, step-by-step. Not only video tutorials but the course contains lots of coding exercises that you will do to test your acquired knowledge practically side by side of watching video tutorials.

This course will help you to prepare for Job Interviews on Core Java language also you will gain confidence in doing programs using Java.

Who this course is for:

Anyone who want to build a career in programming, having Java in their curriculum in High School/ College
Basic knowledge
No prerequisite, a computer/laptop is needed only
What will you learn
Complete Java programming from the basic to the advance level
Input Output, Basic control structures - if-else, loops, switch-case
Methods, Strings, Arrays, ArrayList
Classes and Objects
Exception Handling

Know more: