Menu
Topics Index
...
`


Collections Framework > Collection Algorithms >
Siva Nookala - 01 Apr 2016
We can create Thread Safe Collections by using Collections.synchronizedCollection() utility method. It returns thread safe Collection which can be used in multiple threads and be sure that the data is not corrupted. Note that the collection returned is synchronized at method level and if you have multiple operations performed on that collection, then we need to synchronize the return collection as well.

Thread Safe Collections Demo
import java.util.*;

class ThreadSafeCollectionsDemo
{
    public static void main(String arg[])
    {
        List<String> friends = new ArrayList<String>();
        Collection synchronizedFriends = Collections.synchronizedCollection(friends);
        FriendsAdder adder = new FriendsAdder(synchronizedFriends); // LINE A
        FriendsPrinter printer = new FriendsPrinter(synchronizedFriends); // LINE B
        adder.start();
        printer.start();    
    }
}

class FriendsAdder extends Thread
{
    Collection c;
    FriendsAdder(Collection c)
    {
        this.c = c;
    }

    public void run()
    {
        for(int i = 0; i < 10; i++)
        {
            synchronized(c) // LINE C
            {
                c.add("F" + (i + 1));
            }

            try { Thread.sleep(200); } catch(Exception e) { }
        }
    }
}

class FriendsPrinter extends Thread
{
    Collection c;
    FriendsPrinter(Collection c)
    {
        this.c = c;
    }

    public void run()
    {
        for(int i = 0; i < 10; i++)
        {
            synchronized(c) // LINE D
            {
                Iterator iterator = c.iterator(); // Must be in the synchronized block
                while (iterator.hasNext())
                {
                    System.out.print(iterator.next() + "~");
                }
            }
            System.out.println();

            try { Thread.sleep(200); } catch(Exception e) { }
        }
    }
}
OUTPUT

F1~
F1~F2~
F1~F2~F3~
F1~F2~F3~F4~
F1~F2~F3~F4~F5~
F1~F2~F3~F4~F5~F6~
F1~F2~F3~F4~F5~F6~F7~
F1~F2~F3~F4~F5~F6~F7~F8~
F1~F2~F3~F4~F5~F6~F7~F8~F9~
F1~F2~F3~F4~F5~F6~F7~F8~F9~F10~

DESCRIPTION

We created an ArrayList of Strings. If this list has to be modified by multiple threads, then we can not use it directly because ArrayList is not synchronized. But by using the synchronizedCollection method, we can get a collection which synchronized at the method level. If we are making multiple calls on this List, then it is important that we have to do that in the synchronized block as shown at LINE C and LINE D. Otherwise the results might not be predictable and it could result in corrupted data.

THINGS TO TRY
  • Pass friends instead of synchronizedFriends at LINE A and LINE B. See that the results might not be consistent.
  • Comment LINE C or LINE D and run the program multiple times, to see that the output is not consistent.
Also note that apart from synchronizedCollection there are other methods like synchronizedList, synchronizedMap, synchronizedSet, synchronizedSortedMap and synchronizedSortedSet for synchronizing various types of Collections.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App