Jul 2, 2012

Java : final,Synchronisation,ConcurrentModification


Following are some of the Java's little surprising things (atleast to me),

1: final's operation by reference:

final which do not mean an object cannot be changed, actually objects reference cannot be changed.

final StringBuffer sb = new StringBuffer("arun");
sb.replace(0, 2, "ab");                    // works !
sb = new StringBuffer("test");       //throws error: final can't be changed

final String s = new String("arun");
s.replace(0, 2, "ab");     // throws error
s = "test";                      // throws error
//do not work since String is immutable (same reference can't be modified)
Working things makes change on same reference, but others creates new reference which final can't allow.

This also means final != immutable


2 : Object lock of Synchronised methods on multiple threads

Synchronised method operates by establishing Object level Lock that calls the method.


3: ConcurrentModificationException

1) modification of an object while being iterated at other place
2) In certain violations, single thread can also cause the same issue


Github code on 2 & 3