Saturday, December 12, 2009

Interesting Java Data Structures

Vector & Collections.synchronizedList(new ArrayList()); are similar. They get the lock on the entire object.

So are HashTable and Collections.synchronizedMap(new HashMap());.

Though lock is taken on entire object - during operations like iterations they have to be in a synchronised block.Else parallel access by other thread will lead to a concurrent access exception.

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collection.html

Solution to these are data structures like CopyOnWrtieArrayList(for list) ConcurrentHashMap(for map).

ConcurrentHashMap doesnt lock the entire object , instead allows parallel reads, when a write operation is on.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html


Similarly with CopyOnWriteArrayList there is no need to lock the entire object during iteration, as the iteration will happen on a copy object.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

RentrantReadWriteLock - This helps in taking a lock .So that all other access through this point will wait for the lock to be released. This lock is not resticted to a object and hence can be used in the business logic to get fine thread safety and synchronisation over business objects.This also provided read and write locks which will help in granular control for read and write operations.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html

Synchronizing method against block(object)

When a method is synchronized , the method object is blocked. No other thread can enter into any other synchronized method(non static) on this object.But other threads can enter into a non synchronized block on the same class.

When a block is synchronized - if its synchronised on a object ,two parallel thread can access two synchronized blocks at the same time., since locks are on two different objects.

Class level locks can be obtained by making static methods synchronized.

No comments:

 
Free Domain Names @ .co.nr!