Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java Tip 141: Fast math with JNI

Use JNI to dramatically speed math in J2SE 1.4

  • Print
  • Feedback

Page 2 of 2

java -classpath . com.softtechdesign.math.MathLib


The benchmark code in your main method should execute. If you want to compare the execution speed with the StrictMath versions, change the calls in MathLib.java from MathLib.xxx() to Math.xxx(). On my Pentium 4, 2-GHz machine, the benchmark took 24.5 seconds with the StrictMath routines and 7 seconds with the MathLib (JNI) routines. Not a bad performance boost!

The MathLib (JNI) routines are about half as fast as the Math routines in J2SE 1.3.1—a result of the overhead involved in making a JNI call. Note that when you make numerous calls to the MathLib routines in a tight loop, you sometimes get an exception:

Unexpected Signal : EXCEPTION_FLT_STACK_CHECK occurred at PC=0x9ED0D2


I submitted a bug report to Sun about this problem, but I have not received a response. The good news is that in practice, I have never gotten the error when running any of my hologram program code.

Hooray for JNI

JNI enables programmers to employ fast C/C++ math routines in their Java programs. It solves problems for which Java is poorly suited: when you need the speed of C or assembler, or when you need to write low-level code to communicate directly with hardware. It can also be used to access legacy applications or interface with libraries written in other languages.

This MathLib example barely scratches the surface of what you can do with JNI. JNI native methods can create and manipulate Java objects such as strings and arrays and accept Java objects as parameters. JNI can even catch and throw exceptions from native methods and handle these exceptions from the native code or from your Java application. This almost seamless sharing of objects makes it very easy to incorporate native methods in your Java applications.

About the author

Jeff S. Smith is president of SoftTech Design, a Web and software development company located near Denver, Colo. Jeff has a BA in physics from the University of Virginia and 15 years of software/database/Web development experience as well as 6 years of experience as a Delphi and Java instructor. He has written numerous games and home entertainment programs and authored articles on genetic algorithms and Java Database Connectivity (JDBC) frameworks. You can read more of Jeff's articles at: http://www.SoftTechDesign.com/media.html.
  • Print
  • Feedback

Resources