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) { }
}
}
}
OUTPUTF1~
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~
DESCRIPTIONWe 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.