Skip to content
Advertisement

About unsynchronized & synchronized access in Java Collections Framework?

Can anyone explain what is unsynchronized & synchronized access in Java Collections Framework?

Advertisement

Answer

Synchronized vs unsynchronized access doesn’t have to do with the Java Collections Framework per see.

Synchronized access means that you have some sort of locking for accessing the data. This can be introduced by using the synchronized keyword or by using some of the higher level constructs from the java.util.concurrent package.

Unsynchronized access means that you don’t have any locking involved when accessing the data.

If you’re using a collection in several threads, you better make sure that you’re accessing it in a synchronized way, or, that the collection itself is thread safe, i.e., takes care of such locking internally.

To make sure all accesses to some collection coll is accessed in a synchronized way, you can either

  • …surround accesses with synchronized (coll) { ... }

    public void someMethod() {
        synchronized (coll) {
             // do work...
        }
    }
    
  • …encapsulate it using Collections.synchronizedCollections

    coll = Collections.synchronizedCollection(coll);
    

In the former approach, you need to make sure that every access to the collection is covered by synchronized. In the latter approach, you need to make sure that every reference points at the synchronized version of the collection.

As pointed out by @Fatal however, you should understand that the latter approach only transforms a thread unsafe collection into a thread safe collection. This is most often not sufficient for making sure that the class you are writing is thread safe. For an example, see @Fatals comment.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement