Synchronized Static Method Tutorial

The synchronized keyword can be applied to a method or a block of code. The primary purpose of the synchronized keyword is to lock a shared resource to a single thread. The technical term for locking a resource is called an intrinsic lock or monitor lock. In this tutorial I will demonstrate populating an ArrayList from multiple threads using the non-thread-safe add() method. This tutorial will demonstrate applying the synchronized keyword to a static method and a code block to make our method thread safe.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md SynchronizedStatic
C:\Java>cd SynchronizedStatic
C:\Java\SynchronizedStatic>Notepad SynchronizedStatic.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.util.*;
class SynchronizedStatic {
    public static void main(String args[]) {
        for (int i = 0; i < 100; i++) {
            new NumberThread(i);
        }
        System.out.println("Active threads: "+Thread.activeCount());
        StaticList.displayList();
    }
}

class StaticList {
    private static ArrayList<Integer> numberList = new ArrayList<>();
   
    static void addToList(Integer number) {
        numberList.add(number);  // ArrayList add() method in addToList is not thread-safe - problems
    }
    static void displayList() {
        System.out.println(numberList);
    }    
}

class NumberThread implements Runnable {
    private int number = 0;

    NumberThread(int number){
        this.number = number;
        new Thread(this).start();
    }

    @Override
    public void run() { // this is where the new thread starts
        StaticList.addToList(number);
    }
}

Now switch back to the command prompt (CMD) and type in javac SynchronizedStatic.java and press Enter.
Now type in java SynchronizedStatic and press Enter.


C:\Java\SynchronizedStatic>javac SynchronizedStatic.java
C:\Java\SynchronizedStatic>java SynchronizedStatic
see video for results


Final thoughts

In my next tutorial I will demonstrate how to apply the synchronized keyword to instance methods.


Tutorials