Synchronized | Unsynchronized |
StringBuffer | StringBuilder |
Vector | ArrayList |
HashTable | HashMap |
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 1 | Thread 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).
Good Explanation !!
ReplyDeleteHi , 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?
ReplyDeleteYes. 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