« July 2007 | Main | September 2007 »

August 2007 Archives

August 23, 2007

QUIZ: Does this code have issues?

Over my holidays I had some time to read some books from cover to cover. Since my family requested a good amount of attention, I managed to finish only two, but this is fine as I'm in the middle of the next.

Where is the issue in this code?

There are many ways to iterate through lists in Java. One of my favorite is this one:
for (int i = 0; i < list.size(); ++i) {
  Object obj = list.get(i);
  // do something
}
I developed a habit to change it into this form:
for (int i = 0, size = list.size(); i < size; ++i) {
  Object obj = list.get(i);
  // do something
}

It is at least faster then the first version. Yes, it is. Consider a type of Vector with all methods synchronized for the list...

But, where is the issue?

Credits

This was inspired by Brian Duff's other blog.

August 31, 2007

SOLUTION: Does this code have issues?

Thank you for all your comments on my previous post.

Non-Issues

Using the ++ increment operator

The usage of the ++ increment operator was done deliberately and is not an issue. The difference between the two is the point in time when the value of the variable is returned. The postfix notation (i++) needs to save the value of i first and then increments. Using the ++i version helps even the dumbest compiler to generate the fastest possible code, while i++ needs at least a second operation. Today's compiler techniques should be good enough to detect that ++i and i++ are the same and the return value of i++ is not used in this situation. Using the prefix notation is more a matter of taste here.

Using Typed Iterators

Using typed Iterators is surely a big advantage in Java 5. I'm a big fan of that style. But this not a real issue.

The Issue

Many of you where correct that the modification of the list will be the issue. If you modify the code in the loop the issue could be easily spotted. It is more difficult to spot the problem if you just iterate through the list to get the values. Code Reviewers should be careful and consider whether the list is concurrently modified. Antony Reynolds provided the best answer here.

Further Reading

  • Java Concurrency in Practice, Brian Goetz
  • Concurrent Programming in Java, 2nd Edition, Doug Lea


About August 2007

This page contains all entries posted to Olaf Heimburger's Blog in August 2007. They are listed from oldest to newest.

July 2007 is the previous archive.

September 2007 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type and Oracle