Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About unsynchronized & synchronized access in Java Collections Framework?

Tags:

java

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

like image 274
unknownsatan Avatar asked Jun 21 '11 09:06

unknownsatan


2 Answers

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.

like image 84
aioobe Avatar answered Oct 07 '22 17:10

aioobe


Synchronized access means it is thread-safe. So different threads can access the collection concurrently without any problems, but it is probably a little bit slower depending on what you are doing.

Unsynchronized is the opposite. Not thread-safe, but a little bit faster.

like image 33
Christian Avatar answered Oct 07 '22 17:10

Christian