Synchronized Implementation of a Business Logic
Implement using existing Synchronized Java classes (Hashtable, StringBuffer, Vector)
or
synchronize the blocks when we implement Unsynchronized Java classes (HashMap, StringBuilder, ArrayList)
or
create a synchronized collection objects from Collections.synchronizedXXX() method and then use it (of course, i cant synchronize StringBuilder like this.!!)
In a multi-threaded scenario, which of the abo开发者_开发知识库ve will be the best way to achieve synchronization without any performance kill?
Thanks in advance.!!!
The best approach depends on exactly what your code is trying to do and the level of atomicity you require. Sometimes the Collections.synchronizedWhatever
is fine; sometimes you need to do your own synchronization.
In terms of performance you just need to make sure you minimise the number of synchronized
blocks that are entered. There will be little difference between
(example A)
List l = Collections.synchronizedList(originalList);
l.add(something);
and
(example B)
synchronized (originalList) {
originalList.add(something);
}
because they both enter one synchronized block. However:
(example C)
List l = Collections.synchronizedList(originalList);
l.add(something);
int index = l.indexOf(something);
will enter two synchronized blocks, whereas
(example D)
synchronized (originalList) {
originalList.add(something);
int index = originalList.indexOf(something);
}
will only enter one synchronized block. Of course it spends longer in that block so it may increase contention, but the add and the indexOf now behave like a single atomic operation. This may or may not be what you want: it's entirely application dependent.
EDIT: To answer Deepak's question:
The 'synchronizedList' in example C means that each call to a method on 'l' will be wrapped inside a synchronized block. You can think of C as doing this:
synchronized (originalList) {
originalList.add(something);
}
synchronized (originalList) {
int index = originalList.indexOf(something);
}
There is some added cost here, but unless it's in a performance-critical section of your code it's probably not going to be a problem. I'd suggest you think more about ensuring your code behaves correctly before you think about optimising it. It's hard to get thread-safe code right so be very careful with how you write things. For example, in C there is a possible race condition between 'l.add(something)' and 'l.indexOf(something)'. D does not have the same race condition because both operations are inside a single synchronized block.
Brian Goetz's book (Java Concurrency in Practice) is an excellent resource for learning how to write thread-safe code. I highly recommend it. I'm sure it's on Amazon.
精彩评论