Thursday, 26 February 2009

Welcome to "Il Mondo JavaBeans" (including "Il Mondo EJB")

Java beans are just Java classes that conform to a convention. Multiple objects are encapsulated into a single object (the bean).

Class must:
1. have a public default constructor
2. class properties must have get, set that obey a specific convention
3. class should be readily serializable - allow applications and frameworks to reliably save and restore the bean's state independent of vm and platform

GUI toolkits like AWT and Swing use JavaBeans conventions for their components.

Beans == way of writing component-oriented software in Java programming language.

Enterprise JavaBeans is the use of Java bean components to build an "enterprise app" in a modular way. The components must conform to the EJB specification (javax.ejb, javax.ejb.spi, javax.interceptor).
EJBs include entity beans (which essentially represent relational database tables), session beans and message-driven beans (MDBs). MDBs can receive messages asynchronously.

Monday, 23 February 2009

Thinking like Eckel: Objects are Like Trains

Basics First: The wait/notify dynamic

One fine day, an instance of the java.lang.Object class had its wait() method invoked and application X came to a standstill. Why and wherefore did this happen?

void wait()

wait throws an InterruptedException. It causes the current thread to WAIT until another thread calls notify or notifyAll on the same object.

wait() == wait(0) == wait(0,0)

which means invoke wait with a zero millisecond timeout (i.e. never timeout). The current thread must own the object's monitor. Think of it as a UNIX process that sleeps until some event occurs or a bus that stops at traffic lights and must be "notified" either by the traffic lights or by a car honking from behind it! An object, to put it in baby terms, is like a "choo-choo train"! A "choo-choo" train with locks that can only be manipulated by synchronized methods! Tampering illegaly with the locks results in a vandalism-detection mechanism being triggered.

Some notes on wait/notify

There's a little more to wait/notify than meets the eye and some of this "extra insight" can be obtained from reading good Java books such as Bruce Eckel's Thinking in Java (Bruce Eckel is both a "Java Black Belt" and also founding member of the C++ Standards Committee, the two facts being not entirely unrelated). One key point he makes is that synchronized methods of an object can be called on an object in a wait state, precisely because calling wait releases the lock on the object. Because wait does jiggery-pokery with the object, calling wait outside of a synchronized method results in an IllegalMonitorStateException (present since JDK 1.0 so don't act all surprised!)

Saturday, 21 February 2009

Java New IO: Channels

Channels (which came in JDK1.4) represent connections to entities capable of performing I/O operations e.g. files and sockets; and selectors, for multiplexed non-blocking I/O operations. It uses an idiom from telecommunications.

What is this business of multiplexing I/O operations?

In electronics, a multiplexer is an electronic component that performs multiplexing: selects one of many digital or analog input signals and outputs to a single line. Demultiplexers do the reverse. Ther term originated in telegraphy and became used widely in the context of computer networks. The two main forms of multiplexing are time-division (turn-taking) multiplexing (TDM) and frequency-division multiplexing (non-overlapping frequency ranges for different signals) aka FDM. Both are methods of "sharing a medium" / "sharing the airwaves".

The Java Selector class is a multiplexor of SelectableChannel objects. These implement the Channel interface, a nexus for I/O operations (nexus = form of connection. the hub).

Some of the interesting types of Channels are GatheringByteChannels and ScatteringByteChannels. Within this melee of channels we also see DatagramChannel and ServerSocketChannel in the mix.

Read the original JSR for the NIO library. NIO2 is currently in development (the expert group includes Sun, Doug Lea, IBM Google). By the way, Doug has a very interesting paper on design patterns for avionics control systems

To see how NIO may change in Java7 see the Draft API documentation.

Tuesday, 17 February 2009

Debugging the Java Heap (jmap and other tools)

How to debug the Java heap?

There are many tools, one is jmap (shows you the heap, gc algorithm etc).

jmap -histo pid

shows the number of objects of each class in a given java process.

Debug Java Threads

jstack -l -m

-m means mixed mode (Java and native C/C++ stack frames)

Jargon

In output of jmap you'll see some jargon. For example:

CMS - Concurrent Mark Sweep (aka low latency collector). computes transitive closure of live references for garbage collection.
gc "ergonomics" - automatically selecting a gc algo based on conditions at runtime

Other Java Tools

jinfo - tells you the VM info you are running with
jps - ps for java processes, jps -l gives you the fully qualified classname
jstat - performance statistics for JVM

Monday, 16 February 2009

Java 6 Changes

JCF Changes

The JCF introduced the Deque interface.

public interface Deque<E>extends Queue<E>


Methods to add/remove elements at both ends of the queue.

Back to Basics: Copying Arrays and other Array Operations

Copying Arrays

One way is to use the clone method which (by default) just does a shallow copy (so it's fine only for primitive one-dimensional arrays).

Another way is to use System.arraycopy(src, 0, dest, 0, length).

Arrays.copyOf(src, nitems) will copy nitems, filling in nulls where appropriate, and copyOfRange(src, a, b) will copy src from a to b. copyOf and copyOfRange are meant to be more efficient than System.arrayCopy.

Array Utils

java.util.Arrays - contains various methods for manipulating arrays (sorting and searching). Arrays has been around since Java2, and is part of the JCF.

Arrays.binarySearch( array, key ). Can be float array, double array, int array.
Arrays.fill(array, value)
Arrays.asList returns the array presented as a java.util.List.

Sunday, 15 February 2009

Swing Vocabulary

JFrame, JPanel, JButton, BorderLayout, ActionListener

Axis of Apache

Java Web Services Technology
http://wiki.apache.org/ws/FrontPage/Axis

Axis uses SOAP protocol (Simple Object Access) for web services. It's a kind of XML-RPC.

WSDL is a specification to describe a web service (series of messages travelling between two endpoints). It is independent of the underlying protocol (e.g. SOAP).

In Axis, there is a java program, WSDL2Java, which generates client bindings for web service, described by WSDL. For .NET there is a corresponding program, wsdl.exe. Client-side Axis is built using JAX-RPC specification, a "key technology for web services integration".

Monday, 9 February 2009

Back to Basics: The java.util.List, java.lang.StringBuffer and java.lang.StringBuilder

java.util.List is an interface that extends Collection. Lists allow duplicates, unlike sets.

Fundamental methods:
add(Object)
add(index, Object)
get(index)

index goes from 0 to size-1. List also implements indexOf, which gives the index of the first occurence of some object.

java.lang.StringBuffer is a mutable sequence of characters. The binary string concatenation operator + is implemented with StringBuffers by the compiler. Key methods on SBuffers are append, insert, reverse (which returns a new StringBuffer) and toString. The thing about StringBuffer is you can't do stuff like sb+="some string", you NEED to use sb.append!

As of Java 1.5, StringBuffer implements the Appendable interface, designating an object to which char sequences and values can be appended. StringBuffer is closely related to the (java.util.) Formatter interface.

StringBuilder is a drop-in replacement for StringBuffer when no synchronisation is required.

Saturday, 7 February 2009

IntelliJ Settings

Cntrl-Alt-S Open Settings

IDE Settings->General
IDE Settings->Appearance: Set "Use antialiased font in editor", Change L&F (Idea4.5 default).

Java keywords in IntelliJ are highlighted in a horrendous dark blue colour. To change them to a more palatable light grey we can do the following:

Cntrl-Alt-S Open Settings

IDE Settings->Colors & Fonts

Set the font to Consolas, and set Java:Keyword:Foreground to light grey. Then when you read the code you are not obstructed by the "noise" of Java keywords and can focus on the functionality.

Wednesday, 4 February 2009

Debugging the Java Debug Wire Protocol: No Transports Initialized

JDWP sometimes kicks up problems.

e.g.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT

(transports allow the debugger or VM to act as a server).

Asynchronous protocol, debugger sends 14 bytes, VM replies with 14 bytes (handshake). Communication then takes place via command packets (which can be sent by debugger or VM) and reply packets. Reply packets are sent in response to command packets (to indicate success or failure).

All fields and data is sent in big-endian format (higher-order byte at the lowest address, big end comes first). Just like Adobe Photoshop. Little endian seems more natural.

JDWP facilitates the remote debugging of Java programs.

Tuesday, 3 February 2009

Prepare to be Bombarded by Java Marketing! Available NOW!

JavaFX is here, Java Buddies!!! The best marketing concoction from Sun since coinage of the name Java! Rock on, Java dudes! Immersive media written in Java??!! Bring it on!!!

Need a more techie take on this brazen new technology? Check out InfoWorld's article "Java Fights Flash". Hoo-ya!

Blog Archive