What Else Is There?


Java contains many more advanced topics that most developers will rarely have a need for. There are also dozens upon dozens of additional APIs that you may need to consider. This section briefly mentions some of these topics and APIs.

Custom Class Loaders

When you access a class for the first time, the Java VM uses one of three default class loaders to load the class for use. The first class loader Java uses is the bootstrap class loader. The bootstrap class loader looks in the system JAR files rt.jar and i18n.jar to find Java classes from the core Java API library. If Java does not find the class, it then looks in the Java extension directory, ./lib/ext under the JRE installation directory. If necessary, Java finally uses the directories on your classpath to load the class.

You can create additional custom class loaders. A custom class loader can load a class from an alternate location. It might load a class from a database, from a web site, from an FTP site, or from dynamically created byte codes.

For further information, refer to the article "Create a Custom Java 1.2-Style Classloader" by Ken McCrary at http://www.javaworld.com/javaworld/jw-03-2000/jw-03-classload.html. For more-up-to-date information, start with the API documentation for the class java.lang.ClassLoader.

Weak References

Java's garbage collection scheme manages reclaiming memory for objects that you're done with. But what if you want to write an application that monitors memory use? In order to monitor an object, you must hold a reference to it. As long as your monitor application retains such a reference, the garbage collector cannot reclaim the object in question.

You might also want to implement a caching scheme. A cache loads frequently accessed objects. But since the cache data structure must (by definition) refer to cached objects, the garbage collector can never consider them for reclamation. You must write complex additional code to manage removing objects from the cache from time to time. Otherwise your cache will continue to grow until you get an out-of-memory error.

To help with these and other problems, Java lets you use weak references. A weak reference to an object does not count for purposes of garbage collection. The garbage collector will reclaim any object with weak references but no strong references.

Java supplies three levels of weak references, in order from weakest to strongest:[16] phantom, weak, and soft. A phantom reference can be used for special cleanup processing after object finalization. A weak reference results in the referred object being removed when garbage is collected. A soft reference results in the referred object being removed only when the garbage collector determines that memory is really needed.

[16] [JavaGloss2004b].

The class java.util.WeakHashMap is a Map implementation with weak keys. Refer to its API documentation for further details.

Refer to the Java API documentation for the package java.lang.ref for more information on the various weak reference types.

The finalize Method

In Lesson 4, you learned a bit about garbage collection. Java automatically collects unused objectsones that no other objects refer to. Once in a while, you may find the need to accomplish something when an object is garbage collected. To do so, you might consider defining a finalize method:

 protected void finalize() throws Throwable {    try {       // do some cleanup work    }    finally {       super.finalize();    } } 

The garbage collector calls the finalize method against any objects that it collects.

The problem is that you cannot guarantee that finalize ever gets called. Even when the Java VM shuts downwhen your application exitsfinalize might not get called. This means that you should never write code in finalize that must execute. Closing file or database connections in a finalize method is not a good ideachances are that these resources will never be released.

If you think you need a finalize method, try to find a way to redesign your code. Or consider the use of phantom references as an alternative. If you do implement finalize, it is a good idea to ensure that you always call the superclass finalize method (as shown in the above bit of code).

Instrumentation

Using Java instrumentation capabilities, you can add informational byte codes to Java class files. This information can be used to aid in logging messages, profiling method execution times, or building code coverage tools. The goal is to allow you to insert such information in a manner that does not alter the functionality of the existing application.[17]

[17] Java's instrumentation API is an example of a scheme known as aspect-oriented programming.

To use instrumentation, you implement the ClassFileTransformer interface. You register this implementation at the java command line using the -javaagent switch. As the class loader attempts to load a class, it calls the transform method in your ClassFileTransformer implementation. The goal of the transform method is to return a byte array representing the replacement class file.

Refer to the Java API documentation for the package java.lang.instrument for more information.

Management

The Management API allows you to monitor and manage the Java VM. It also allows for some management of the OS under which the VM is executing. The Management API allows you to do things such as compare performance characteristics of the garbage collector, determine the number of processors available, monitor memory usage, monitor threads, or to monitor class loading from an external perspective.

Refer to the API documentation for the package java.lang.management for more information.

Networking

The java.net package supplies several classes to help you build network applications. This package provides support for low-level communications, based on the universal concept of a bidirectional communication mechanism known as a socket. Sockets allow you access to the TCP/IP protocol. Sockets are the underpinning of most host-to-host communication.

The java.net package also provides a number of higher-level APIs centered on web programming and URLs (Universal Resource Locators).

For more information, refer to the API documentation for the package java.net.

NIO

Java NIO ("New I/O") is an advanced, high-performance facility for input-output operations. If you need to boost your performance for mass data transfers, you many want to consider NIO. While Sun has retrofitted many of the java.io streams to use NIO, you may want to directly interact with the NIO API for the fastest possible data transfers.

NIO is not stream based. You instead use channels, which are similar to streams in that they are sources and sinks for data. A buffer contains chunks of data that channels read from and write to. The main speed gain in NIO comes from the use of direct buffers. Normally, data is copied between Java arrays and VM buffers. Direct buffers are allocated directly within the VM and allow your code to directly access them. This avoids the need for expensive copy operations.[18]

[18] [Travis2002], pp. 23.

NIO is nonblocking. Normally when you execute an I/O operation, calling code is blockedit must wait until the operation completes. Using nonblocking I/O, your code can continue to execute even if a read or write operation is taking place. You can use nonblocking socket channels as the foundation for socket servers. This increases the scalability of the socket server and simplifies the management of incoming connections and requests. Blocking I/O requires the judicious use of multithreading, while NIO allows you to manage all incoming requests in a single thread.

Conceptually, NIO is more complex than the standard java.io library. The tradeoff is worth it if performance is paramount. In the case of socket servers, NIO is definitely the way to go. For most other needs, the standard I/O library will suffice.

For more information, refer to the Sun NIO document at http://java.sun.com/j2se/1.4.2/docs/guide/nio/index.html.

JNI

The Java Native Interface (JNI) is your hook to the outside world. You might need to interact with a hardware API written in C, or perhaps you might need to call operating system routines that go beyond the capabilities of Java. Using JNI, you can call libraries (DLLs in Windows and sos in Unix) written in other languages including C++ and C.

For more information, the Sun tutorial is a good place to start (but it may be somewhat out of date): http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/index.html.

As with any Java technology that allows you to interact with external resources, minimize your use of JNI in order to maximize your potential for cross-platform deployment.

RMI

Remote Method Invocation (RMI) is an API that allows you to call methods on Java objects that execute in the context of another Java VM. The other VM can be on the same machine or on a remote machine. RMI is the basis for the distributed component-based computing used in EJBs (Enterprise Java Beans).

RMI uses the proxy design pattern. A client object can interact with a server method located on another machine by working through its public interface. In reality, the client interacts with a client-side stub. The stub takes a Java message and translates it into serialized objects that can be sent across the wire. The stub interacts with a server-side skeleton, the job of which is to take those object streams and translate them into a method call against the actual server class.

You generate the stub and skeleton Java source using the RMI compiler rmic, located in your Java bin directory.

Using RMI keeps your clients from having to build remote communication code. As far as your client code knows, it is interacting with just another Java object in the same virtual machine. Network limitations will inherently slow your application, however, so you must still design your application with the high overhead of RMI in mind. The primary design goal for distributed applications is to minimize the amount of distributed processingdon't distribute your objects unless you must![19]

[19] [Fowler 2003a], p. 89.

Beans

You use JavaBeans, not to be confused with Enterprise Java Beans (EJBs), for building pluggable GUI components. You might build a new Java stoplight GUI control that you want to sell to Java GUI developers. The stoplight Java-Bean is a Java class like any other. But in order for developers to load and use your stoplight control in tools such as JBuilder, it must adhere to JavaBeans specifications.

To be a visual JavaBean, a class must inherit from java.awt.Component and must be serializable. It must expose its information using accessor methods that follow the standard Java naming convention (e.g. getName to return the value of the field name). The ability of tools to gather bean information based on knowledge of these conventions is known as introspection. A bean has a related BeanInfo class that provides relevant bean metadata. Beans communicate with other beans using an event mechanism.

For more information, the best place to start is the Sun tutorial at http://java.sun.com/docs/books/tutorial/javabeans/.

Security

Security in Java is easily a topic for a whole book. The J2SE security API, located in various packages starting with the name java.security, includes classes for things that include certificate management, key store management, policy files, encryption/decryption algorithms, and access control lists.

The Java security model is based on the concept of a sandbox, a customizable virtual place. In the sandbox, Java programs can execute without adverse impact to the underlying system or its users.

The core J2SE security API grows with each new release of Java. For full information on what's available, refer to the Java API and release documentation.

J2EE

The Java 2 Platform Extended Edition (J2EE) is a collection of various enterprise-level APIs. J2EE can allow you to create scalable component-based applications.

Often when people refer to J2EE, they specifically mean Enterprise Java Beans (EJBs). EJBs are components. The goal of EJBs is to eliminate the need for an application developer to re-create deployment, security, transaction, and persistence services. An EJB application server such as BEA's WebSphere, IBM's WebLogic, or JBoss is a container that provides these services for EJBs.

J2EE is heavily weighted toward XML as the common data language. Four APIs center on XML: the Java API for XML Processing (JAXP), the Java API for XML-based RPC (remote procedure calls) (JAX-RPC), SOAP with Attachments API for Java (SAAJ), and the Java API for XML Registries (JAXR).

Another set of J2EE APIs centers on Web development. The Java Servlet API is the basis for web applications. JavaServer Pages (JSPs) simplify the presentation layer for web applications. The JSP Standard Tag Library (JSTL) provides common custom tags to simplify writing JSPs. JavaServer Faces gives you a framework for simplifying the development of the model and application facets of a web application.

Various other J2EE APIs support transactions, resource connections, and security. The Java Message Service (JMS) provides an interface for asynchronous message needs.

Scads of books exist on J2EE. The J2EE tutorial available at http://java.sun.com/j2ee/download.html is as good a place as any to start. Before you leap into the extremely complex world of J2EE, ensure that you have justified your decision from the standpoints of functionality need, cost of development, complexity requirements, performance need, and scalability needs. Many shops invested heavily in J2EE, only to find that they didn't need most of the things it provides. Often you will find that your own custom implementation provides all you need, is vastly simpler, and is a far more flexible solution.

More?

Dozens more Java APIs exist. They support various things such as image manipulation, speech, applets, cryptography, shared data, telephony, accessibility, and automatic web installation.

Java is an entrenched technology that will not go away anytime soon. The evidence is the fact that for virtually every computing need, a Java API for it exists. The best place to start is Sun's Java site, http://java.sun.com. Beyond that, the world is a haystack with many needles. Use Google to find them!

Go fish!




Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net