termine if the load on the production system can obtain a sufficient number of random num-
1. Java's default Random class is expensive to initialize, but once initialized, it can be
2. In multithreaded code, the ThreadLocalRandom class is preferred.
3. The SecureRandom class will show arbitrary, completely random performance.
Performance tests on code using that class must be carefully planned.
Java Native Interface
If you are interesting in writing the fastest possible code, avoid JNI.
Well-written Java code will run at least as fast on current versions of the JVM as correspond-
ing C or C++ code (it is not 1996 anymore). Language purists will continue to debate the rel-
ative performance merits of Java and other languages, and there are doubtless examples you
can find where an application written in another language is faster than the same application
written in Java (though often those examples contain poorly written Java code). However,
that debate misses the point of this section: when an application is already written in Java,
calling native code for performance reasons is almost always a bad idea.
Still, there are times when JNI is quite useful. The Java platform provides many common
features of operating systems, but if access to a special, operating-system-specific function is
required, then so is JNI. And why build your own library to perform some operation, when a
commercial (native) version of the code is readily available? In these and other cases, the
question becomes how to write the most efficient JNI code.
The answer is to avoid making calls from Java to C as much as possible. Crossing the JNI
boundary (the term for making the cross-language call) is quite expensive. Because calling
an existing C library requires writing some glue code in the first place, take the time to create
new, coarse-grained interfaces via that glue code: perform many, multiple calls into the C lib-
rary in one shot.