Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Java Newsletter September 2003


Dr. Dobb's Java Newsletter - 9/17/03


There's an old story about a farmer at a hardware store mentioning that he is going to start clearing some wooded area. The shopkeeper, sensing an opportunity to make a sale, offered to loan him a chainsaw, knowing that the farmer would buy the chainsaw once he saw how easy it made his job.

The next day, the farmer returned to the hardware store. "This thing makes my work ten times as hard," he exclaimed.

The shopkeeper, puzzled, said, "Well, there must be something wrong with it. Let me see it." With that, he pulled the cord and started the engine running with a sputter.

Shocked, the farmer yelled, "What's that noise?"

I often wonder how many times as developers we (figuratively, of course) try to use a dead chainsaw. I've certainly seen cases where a developer reinvented a data structure object when the Java library has a perfectly good version of the same data structure. Worse still, it seems to me that the plethora of integrated development environments (IDEs) are often our chainsaws. Some of the new ones are so complicated that I only have a vague suspicion of what some of the features actually do.

I still write a lot of simple code with Emacs and the command-line SDK. Of course, I grew up coding that way, so it seems familiar to me. Still, I have used many IDEs over time. I was on the panel that awarded IntelliJ Idea a Jolt award this year. It has a lot of features, and—the part that I like—the features are relatively unobtrusive.

Sun bought NetBeans and then converted the NetBeans IDE into Sun One Studio. There was a "community edition" for free and another, paid, version. Now, Sun has gone to a completely paid version, but has spun NetBeans back to an open source IDE (see http://www.netbeans.org). I actually like NetBeans and I've been trying to train myself to use it for simple projects instead of just opening up a command shell.

What's your favorite IDE? Or are you using the command line? Drop by http://www.ddj.com/forums/forum.html?forumid=52 and share your thoughts on the discussion board.


Sun + AMD = 64

Sun and AMD announced that Java will be available for the 64-bit Opteron processor in the J2SE 1.5 release scheduled for next year.


Java vs .NET

At VSLive, Microsoft's Eric Rudder announced that .Net usage has surpassed Java usage. Naturally, Sun disagrees, claiming around 3 million Java developers. Personally, I'm suspicious of how you would arrive at these numbers in either case. I've seen many copies of software languishing on shelves. This strikes me as a number that would be very hard to measure in any defensible way.

So what is the right metric? I suspect this is like processor benchmarks —you'll always be able to find one that gives you the numbers you want to shore up your position.


Java Top to Bottom

Years ago I had occasion to use an Ada workstation where the entire operating system was actually Ada. You didn't write shell scripts, you wrote Ada functions. The shell prompt executed Ada. I've seen Lisp machines like this too. If you've ever thought about a complete Java operating environment, you might enjoy https://jinux.dev.java.net/. This project seeks to build a Java operating system over a bare minimum Linux kernel. Not sure how much progress is being made, but with a fast JVM this could be an interesting project.


API Focus: Regular Expressions

Anyone familiar with Unix (or Linux, or Perl, or Awk...) is familiar with regular expression. These powerful constructs allow you to create patterns that can be surprisingly complex.

Until JDK 1.4 you had to write your own regular expression code (or borrow some—I liked the Apache Oro library myself). However, JDK 1.4 introduces the java.util.regexp package, which handles regular expressions as part of the base specification.

The good news? The java.util.regexp package is very easy to use. An example is worth a thousand words, so consider this:

Pattern pat = Pattern.compile("d+j");
Matcher mat = pat.matcher("ddj");
boolean b = mat.matches();

This will set b to true if the string ("ddj") matches the pattern ("d+j"). Of course, the Matcher object has many other useful methods like find, start, and end. You can even call replaceFirst and replaceAll to perform string replacement.

Java regular expressions! Who needs Perl?


Better Coding Through Robotics

Robots seem to be all the rage lately. Television has several "killer robot" competitions where remote controlled robots try to dismember each other. The problem is, it is hard to find time (and money) to build all of that hardware just to have it ripped apart. If you take a look at http://robocode.alphaworks.ibm.com you'll find you can create killer robots (in Java) virtually and have them compete in the arena.

This is a great team-building exercise if you have a staff of programmers. It also lets junior coders sharpen their skills in a Darwinian fashion. The program provides an API (documented with JavaDoc) and even includes the Jikes compiler, so everything you need is all in one place.


Microsoft VM Deadline

If you develop (or have developed) applications that target the Microsoft JVM, you should mark your calendar and count the days. Because of the settlement Sun and Microsoft reached in 2001, January 2004 marks the date when Microsoft will no longer be able to make change to its JVM. Of course, Microsoft has removed its JVM for the most part, so I suspect that most people have already moved to a different JVM. If you haven't, though, there will be no more security patches or enhancements. It is very likely there won't be support for future operating systems, either. You can read "Transitioning from the Microsoft Virtual Machine" at http://www.microsoft.com/mscorp/java/. Not surprisingly, Microsoft's list starts with "Migrate to .Net" and ends with "Switch to a third-party JRE."


Tech: Native Interface

Of course, one of Java's biggest attractions is its portability. Still, in the real world there are times you simply have to call an operating system function. In addition, there is a giant code base of existing software that is, for the most part, C-compatible. Coexisting with legacy code is often a necessary evil.

The good news is that Java has a built-in mechanism for calling native methods—that is, methods that the underlying operating system understands. The Java Native Interface—JNI—allows you to call functions in a shared library (a DLL in Windows parlance) that can then call out to operating system functions or code written in another language. Typically this shared library code is written in C or C++.

If you are a hardcore Java programmer, JNI might seem a little intimidating. However, it isn't hard at all if you take it step by step.

The first thing you need to do is create a native method. This is reminiscent of an abstract method. It has a declaration but no body. Unlike an abstract method, though, the native method does have a body—but the body isn't written in Java.

Your Java program also has to load the library that contains the native method body (or, in most cases, the library will contain many bodies). As an example, consider a simple program that prints how many processors a Windows PC has. Here's the Java portion:

public class GoNative
{
    public native int GetNumberOfProcessors();
    static
    {
        System.loadLibrary("JHelper");
    }
    public static void main(String [] args)
    {
        GoNative me;
        me=new GoNative();
        System.out.println(me.GetNumberOfProcessors()+" processors");
    }
}
        

The GetNumberOfProcessors method is native. In addition, System.loadLibrary loads the JHelper.dll file (if this were a Unix-style program, the library would be JHelper.so). You can compile this program to a class file in the usual way. Of course, it won't run until you supply the JHelper.dll file.

To start, run javah on the class file. Assuming the GoNative.class file is on your class path, you'd issue the following command:

javah GoNative

This produces a C/C++ header file that defines all the native methods that you must supply. Here's an excerpt from the GoNative.h file:

JNIEXPORT jint JNICALL Java_GoNative_GetNumberOfProcessors
  (JNIEnv *, jobject); 
        
This tells you that you have to implement a function called Java_GoNative_GetNumberOfProcessors. The function returns a jint (a synonym for an integer) and has two special arguments that allow the function to access the Java environment. All JNI functions take these two arguments—even functions like this that take no user-supplied arguments.

The C program is easy to write (I've left off the Windows DllMain code which is standard):
int GetNumberOfProcessors(void)
{
        SYSTEM_INFO sinfo;
        GetSystemInfo(&sinfo);
        return sinfo.dwNumberOfProcessors;
}

JNIEXPORT jint JNICALL Java_GoNative_GetNumberOfProcessors(JNIEnv *, jobject)
{
        return GetNumberOfProcessors();
}
        
To get the Java types, you'll need to include jni.h which resides in your JDK's include directory. You'll probably need to tell your compiler to also search include/win32 in this case to pick up some system-specific headers that jni.h includes.

Once you have the DLL built (and placed where the Java program can find it), you can run the Java program like usual. The GoNative.GetNumberOfProcessors method calls into the DLL and you've seamlessly integrated your C code with your Java program.

Of course, there is more to it than this simple example, but this gives you somewhere to start. Your C code can access Java objects (including strings and arrays). It can also call Java methods, throw exceptions, and otherwise behave more or less like a Java program. JNI also provides some useful abstractions for C++ programmers that make some tasks even simpler in C++.

Of course, there are other ways you might integrate alien code. For example, you could write a socket-based server around your C code and communicate using a Java socket. Extending that idea, you could even use Corba. However, JNI allows you to quickly and cleanly expose C code to Java and Java objects to C programs. Sure, it isn't portable, but sometimes you absolutely have to call out to another language.

You can learn more about JNI directly from Sun (http://java.sun.com/docs/books/tutorial/native1.1/index.html). There is also a popular toolkit that simplifies JNI at http://sourceforge.net/projects/jace/.


Better Late than Never Department

The FreeBSD Foundation announced the availability of a native binary release for Java JDK 1.3.1. They are now working on delivering 1.4.x.


Sleepy Java Cats

Speaking of Berkeley, Sleepycat Software (the makers of the open source Berkeley DB embedded database) announced that in October they will release Berkeley DB 4.2 which will contain a Java API based on Collections. See http://www.sleepycat.com/ for more about Berkeley DB.


Job Security

The most offbeat site this month? How about a manual on how to write unmaintainable code? This site (http://mindprod.com/unmain.html) is full of sage advice including, "You don't want to overdo this. Your code should not look hopelessly unmaintainable, just be that way. Otherwise it stands the risk of being rewritten or refactored."

Of course, this manual is tongue-in-cheek and doesn't focus specifically on Java. However, there are some serious pages that focus on bad Java techniques. Have a look at http://cardboard.nu/archives/000107.html or check out http://www.j2life.com/bitterjava/bitterjava.html. The latter is the site for the book Bitter Java which is Bruce Tate's book on antipatterns. That's right—there is a formal name for bad design (see http://www.antipatterns.com/).

Apparently, I've worked with some of the experts in this field and didn't know it! On the other hand, sometimes obscurity depends on your cultural frame of reference. For example, industry-specific jargon seems cryptic if you aren't in the industry (ask you neighbor if his VGA is AGP or PCI, for example). I'm guilty of using variable i, j, and k for integer variables (and I'm not the only one). Why? Because in old-fashioned Fortran, these were automatically integers. If you've barely heard of Fortran this makes no sense (other than the fact that enough people use this convention that it has a life of its own now).

Although one person's obscure construct is another person's clever technique, this Web site showcases some items that would be hard to defend on any basis.


Love for Sale

According to CNet, Motorola is planning to sell off its 19% ownership in Symbian to partners Nokia and Psion. Symbian produces operating system software for smart handsets. CNet quoted John Thode from Motorola: "We want to love all operating systems equally." He also said, "... we wanted to de-emphasize the focus on the OS and focus it on Java. We found Java is more important. It speaks to applications developers, and it speaks to consumers."


Red Hat Enterprise

Red Hat unveiled plans to ship JonAS (an open-source J2EE implementation) and OpenEJB (open-source Java beans) with RedHat Linux. They are covering their bets though since they still support Eclipse (IBM's open-source consortium) and Apache Tomcat. Speaking of Apache...


Apache Jumps In

The Apache Group (makers of the popular Apache web server) announced "Apache Geronimo" which aims to produce an open source J2EE server. Apache says the new project will incorporate many existing Apache Java projects and hinted that there would be some involvement from the Castor, JBoss, MX4J, and OpenEJB communities.

Apache thinks that its relationship with Sun will allow it to achieve certification, a problem that has plagued other similar projects (notably, JBoss). If Apache can deliver an open certified J2EE server with the popularity of Apache they will have another winner on their hands.


Certifications

This month, Sun will start issuing Sun Certified Business Component Developer certifications. Find out more at http://suned.sun.com/US/certification/java/java_busj23e.html.


Coming up in DDJ

In the November issue of Dr. Dobb's Journal:

Oliver Goldman presents Argv, an extendable Java-based argument handling library that lets you parse argument types and string values.

Ed Nisley looks at the history of cryptography, and examines what it means for embedded systems developers programming in Java today.

If you still haven't done so, be sure to download the Dr. Dobb's Special Edition on Java from the Dr. Dobb's Website. This free PDF download covers Java topics ranging from e-commerce, services, mobile applications, and embedded systems. Check it out at http://www.ddj.com/downloads/.


In Closing

There are quite a few new releases on the horizon that should mix up the Java development landscape. A new JDK, new tools from Apache, upcoming releases for several application servers, and a development edition of Sun's Orion (a platform for distributing and updating software) are just some of the things on their way. What are you looking forward to? Drop me a note at [email protected] and let me know.

See you next month!

Al Williams
Dr. Dobb's Journal

 


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.