Synchronized Instance Block Tutorial

This tutorial is a companion to my Synchronized Instance Method Tutorial and will demonstrate applying the synchronized keyword to a code block to make our instance 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 SynchronizedInstanceBlock
C:\Java>cd SynchronizedInstanceBlock
C:\Java\SynchronizedInstanceBlock>Notepad SynchronizedInstanceBlock.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 SynchronizedInstanceBlock {
    public static void main(String args[]) {
        InstanceList iL = new InstanceList();
        for (int i = 0; i < 100; i++) {
            new NumberThread(iL, i);
        }
        System.out.println("Active threads: "+Thread.activeCount());
        iL.displayList();
    }
}

class InstanceList {      
    private ArrayList<Integer> numberList = new ArrayList<>();

    void addToList(Integer number) {
        numberList.add(number);  // ArrayList add() method in addToList is not thread-safe - problems
    }
    void displayList() {
        System.out.println(numberList);
    }  
}

class NumberThread implements Runnable {
    private int number = 0;
    private InstanceList refToIL = null;

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

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

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


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


Final thoughts

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


Tutorials