Tuesday, October 18, 2011

Synchronized vs Unsynchronized

The first implementation of some Java classes were thread safe, synchronized against threads accessing their data at the same time. However, Java then realized many programs are single threaded and this is overkill as synchronization adds an overhead, so they introduced the same versions of those classes but unsynchronized (and thus faster).


SynchronizedUnsynchronized
StringBufferStringBuilder
VectorArrayList
HashTableHashMap


Note on synchronization: Only concurrent access to the same class is synchronized, you may still need to do additional synchronization outside of that class. You can't add or remove from the same class at the same time, but you might want additional synchronization, see example:


Thread 1Thread 2

if (! list.isEmpty()) {
//print list
}

for (i = 0; i < size; i++) {
list.remove();
}

Thread 1 obtains lock on the list and checks the it isn't empty. It suspends before it prints the list. Thread 2 removes a bunch of items. Thread 1 continues and now is printing out an empty list (not what it wanted to do).

3 comments:

  1. Hi , i am not a java expert , so my question is When Thread 1 has the lock on the list , how can Thread 2 able to remove items? -- is it because "It(Thread 1) suspends before it prints the list" - meaning it releases the Lock?

    ReplyDelete
  2. Yes. After Thread 1 completes the task of checking for a non empty list, it no longer needs the lock. Thread 2 acquires the lock, removes the items and releases the lock. Thread 1 can now finish execution. Both Threads operating on the list so a lock is always required

    ReplyDelete