Java Reference
In-Depth Information
Vector v ;
for ( int
int i = 0 ; i < v . size (); i ++) {
process ( v . get ( i ));
In production, this loop was found to be taking a surprising amount of time, and the logical
assumption was that the process() method was the culprit. But it wasn't that, nor was the
issue the size() and get() method calls themselves (which had been inlined by the com-
piler). The get() and size() methods of the Vector class are synchronized, and it turned
out that the register flushing required by all those calls was a huge performance problem.
This isn't ideal code for other reasons. In particular, the state of the vector can change
between the time a thread calls the size() method and the time it calls the get() method. If
a second thread removes the last element from the vector in between the two calls made by
the first thread, the get() method will throw an ArrayIndexOutOfBoundsException . Quite
apart from the semantic issues in the code, the fine-grained synchronization was a bad choice
One way to avoid that is to wrap lots of successive, fine-grained synchronization calls within
a synchronized block:
synchronized ( v ) {
for ( int
int i = 0 ; i < v . size (); i ++) {
process ( v . get ( i ));
That doesn't work well if the process() method takes a long time to execute, since the vec-
tor can no longer be processed in parallel. Alternately it may be necessary to copy and parti-
tion the vector so that its elements can be processed in parallel within the copies, while other
threads can still modify the original vector.
The effect of register flushing is also dependent on the kind of processor the program is run-
ning on; processors that have a lot of registers for threads will require more flushing than
simpler processors. In fact, this code executed for a long time without problems in thousands
of environments. It became an issue only when it was tried on a large SPARC-based machine
with a large number of registers per thread.
Does that mean you are unlikely to see issues around register flushing in smaller environ-
ments? Perhaps. But just as multicore CPUs have become the norm for simple laptops, more
Search WWH ::

Custom Search