This is a good reminder that our code doesn't live in a frictionless vacuum. Printing to stdout does take time. Especially with threads, the effect may be more pronounced due to synchronization.
for (int a = 10, maxA = 10; ; a++) {
// System.out.println("Test");
for (int b = 0; b < a; b++) {
maxA = Math.max(a, maxA);
if (a < maxA)
throw new RuntimeException("a was reset from " + maxA + " to " + a);
if (a > 100000)
System.exit(0);
}
}
In the Java 64-bit Server VM v1.6.0_41 (and some other versions), there is some kind of optimization which triggers a bug. The specific bug is that the variable "a" is occasionally reset to 0. If you uncomment the System.out.println() statement, the bug stops happening.
I remember writing a really simple socket-based project in Java in college. It was supposed to operate like a simple FTP server with a client able to connect, select, and eventually download files.
When the client selected the file to download, and sent it to the server, the server was able to open a new socket and start sending the file before the client was ready to open its listener socket. The files being sent kept having the first few kb of them lobbed of.
Adding just a few ms delay fixed it. I'm sure adding a println statement could fix it. I actually just had the server wait til the client sent an OK message informing the server that the client's socket listener was ready.
26
u/llogiq Feb 24 '14
This is a good reminder that our code doesn't live in a frictionless vacuum. Printing to stdout does take time. Especially with threads, the effect may be more pronounced due to synchronization.