Synchronized Static Block Tutorial

This tutorial is a companion to my Synchronized Static Method Tutorial and will demonstrate applying the synchronized keyword to a code block to make our static method thread safe. You will need to watch the other tutorial prior to this one in order to follow along - I'll be giving the abridged explanation.



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 SynchronizedStaticBlock
C:\Java>cd SynchronizedStaticBlock
C:\Java\SynchronizedStaticBlock>Notepad SynchronizedStaticBlock.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 SynchronizedStaticBlock {
    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 SynchronizedStaticBlock.java and press Enter.
Now type in java SynchronizedStaticBlock and press Enter.


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


Final thoughts

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


Tutorials