Synchronized Instance 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 an Instance method 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 SynchronizedInstance
C:\Java>cd SynchronizedInstance
C:\Java\SynchronizedInstance>Notepad SynchronizedInstance.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 SynchronizedInstance {
    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 SynchronizedInstance.java and press Enter.
Now type in java SynchronizedInstance and press Enter.


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


Final thoughts

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


Tutorials