Try-Catch-Finally Flow

A block of code executed in a try block that throws an exception will be caught by catch and then finally will be executed. For example:

String fail = null;
try {
	System.out.println("in try");	
	fail.indexOf('r');
} catch (NullPointerException e) {
	System.out.println("in catch " + e);
} finally {
	System.out.println("in finally");
}

The print out for this is:

in try
in catch java.lang.NullPointerException
in finally

The finally block executes whether there is an exception in the try block or not. However the finally will not be executed if an exception is caught and the catch block contains a System.exit() call. For instance:

String fail = null;
try {
	System.out.println("in try");	
	fail.indexOf('r');
} catch (NullPointerException e) {
	System.out.println("in catch " + e);
	System.exit(0);
} finally {
	System.out.println("in finally");
}

The print out for this is:

in try
in catch java.lang.NullPointerException

The System.exit call destroys all threads in the JVM.

Java XML Parsers

The two main technologies in Java for parsing XML files are SAX and DOM. The SAX parser is event based while the DOM loads the entire XML document into memory with tree object representation. The DOM model allows the contents of the XML tree to be manipulated in memory as well as giving random access to parts of the document object model. The downside of this is that extremely large XML documents can be memory intensive.

SAX on the other hand is fast and has low overhead as it reads through files and records events rather than loading nodes into memory. Consequently XML documents that are exceptionally large, such as several gigabytes can be parsed.

String Immutability in Java

The Java String object is immutable and final. If an operation is done on it a new instance of a string is added to the stack and returned.

The value of the object once created cannot have its state changed. Consequently a new object with the new value must be created.

The mutable versions of String in Java are supplied by StringBuffer and StringBuilder. Which allow for modifying string values in place. The main difference between StringBuffer and StringBuilder is that the StringBuffer is serializable, whereas StringBuilder is not. Consequently StringBuilder is capable of faster operations on inplace text, but is mainly for use in single threaded environments.

Java Transience

I can recall when I first heard of the FizzBuzz test I laughed. I commented to a fellow worker that I cannot recall using modulus in a production system, but, as karma happens I used it three times in the next two weeks. I am having the same experience with the java modifier transient.

I was going through the Java Persistence API in particular as part of ejb3 while developing business interfaces and beans. One of the annotations in the persistence API is @Transient. This defines the property or field as non-persistent.

The transient modifier has been part of Java for a while now and describes a field as not being part of the serialisation process, either in save or restore. It turns off the persistence mechanism for that field when using serialisation.

A real world example where transient might be used is when a serializable object contains reference to a non-serializable variable. For instance in Java the Thread, Socket and ObjectOutputStream classes cannot be serialized. So to serialize an object that contains a reference to any of these then the variables have to be marked transient.

public class PersistThis implements Serializable, Runnable {
 	int counter = 0;
	transient private Thread thread;
 	public PersistThis() {
		thread = new Thread(this);
		thread.start();
	}
 	@Override
	public void run() {
		while(counter<1000) {
			System.out.println("Counter " + counter);
			counter++;			
		}		
	}
}

Note: Transient is also commonly used in session maintenance code which keeps the amount of data to bring back up after a session fallover manageable.

Why Your Favorite Programming Language Sucks

Disclaimer, I make most of my living working in Java and this blog is written in Python. Elliotte Rusty Harold writes after seeing Python 3 come out with little care for backwards compatibility:

Unless we're willing to make the hard choices and abandon the legacy as Python has, Java is doomed to the fate of C++ and Cobol: a tool for programmers with long white beards who grew up with the language and have learned all its arcana by gradual accretion and who spend their lives maintaining code written a decade or more ago.

Meanwhile a new generation of programmers will abandon Java in favor of more nimble modern languages like Python just as we abandoned C++ in our youth in favor of Java.

There are still an awful lot of systems written in Java that will need to be maintained; there is also a great deal of business logic in freeware and payware libraries that are used to ease the burden on development. I don't see that changing soon. I do agree it is frustrating to work in a language and see its limitations and clunkiness day after day after day.

A good rant none the less.

Brief Rundown of Webservices in Java

Webservices tends to be understood as the delivery of information by http using bundled XML as communication. As the w3c notes, "vendors of software see web services as way to repackage existing capability in a way which makes it interoperable with other systems"

As information systems have expanded, and networks, with the consequent storage of data proliferated there has been different mechanisms developed to access that data across wider systems. These include CORBA, RMI, Webservices and REST.

I have worked on CORBA systems, they tend to be heavy weight and solved a problem prior to the internet when HTTP based networks made data easy to access through the browser interface. CORBA is an effective mechanism to access data without caring about where it is located.

Java has it's own inbuilt version that solves the same issue; RMI, which enables the easy access of distributed objects across a distributed system. Again it knows where to ask where the data is through a naming system, similar to CORBA, though CORBA can be set up as a language/platform agnostic system. RMI is wedded to Java only.

In the Java world the definition of webservices is pretty narrow, and for J2EE it is an interface defined by a WSDL declaration where the data is bundled with the SOAP protocol. In the same vein as Microsoft's DCOM, CORBA's IIOP and RMI's JRMP, SOAP is a distributed object protocol. Unlike the other, it marshals and unmarshals an object's data using XML. Consequently different platforms can unmarshal SOAP transported data without caring what platform marshaled it or bundled it up.

Another benefit of SOAP is that it doesn't care what protocol or network is used to transport the SOAP packet. Given the dominance of HTTP in the modern web, this is the most common protocol used to transport SOAP packets on port 80. This has an upside and a downside, especially for network engineers tasked with security of the local network. SOAP packets can come in and out as they please, where-as services that run on other ports can be filtered or watched.

WSDL is the web services description language which defines the public interface and data for the web service. Because the WSDL is defined in XML and then compiled down to Java using an application like AXIS, it is complex and confusing to make up a WSDL document. Most J2EE vendors provide an application interface to help develop the WSDL.

Another issue with the WSDL is because it is difficult to write and make, a lot of public interfaces for webservices end up messy, ugly and downright awful to use. Unfortunately, in my experience, because of this many webservice interfaces have a lot of WTFness to them. However I have been using the flickr webservices API recently and it is very simple to use.

JAX-WS supports one way and return (request-response) messaging. The one way messaging is when the client does not expect a response, such as in asynchronous messaging. The request-response is the standard ask for something and get data in return. WSDL supports notification (trapping in SNMP parlance) and solicitation, however these two are not supported by JAX-WS.

The main purpose of JAX-WS is to easily make ejb3 stateless beans into distributed objects that can be hit by webservices. This is done through the java annotations of @WebService at the class level and @WebMethod at the argument level (if no methods are annotated with this, all are exposed). The annotations are in the javax.jws packages.

One of the issues with webservices is that they run across a network and carry all the vagaries of a non-reliable transmission system. Often webservice applications are developed in the safety and speed of an intranet and then have all sorts of issues on the internet, though the internet of 2009 is not the same one from 1999. But it does mean the safe transmission of data cannot be relied upon.
I have been using Java since approximately 1999, but to my regret, I did not know that the RuntimeException was named such:

Recall that Java has a class called as the Runtime class - an abstracted representation of the underlying Java Virtual Machine that allows us to add hooks and get information. So the simple answer to "What is the meaning of the name RuntimeException" is:

"It is an exception thrown by the Runtime itself" rather than any particular piece of code.

Not that I have ever been asked that in an interview, but even so.
Why wasn't Oracle's Service Bus implemented with Java? Why XML?

Since it is atop a J2EE server that will have Java Engineers working with it, why not doing all the Service Bus processing in Java. It would be faster than the flowcharting plug-ins they offer now and the XSLT translations you need to do.

Update I expanded on the issue.

Service Bus in Java not XML

In continuation of this jot the service bus being XML based is a bad idea for multiple reasons. It should be in Java. The Oracle Service Bus sits atop a J2EE server; so do the routing, assignments, pipelines and service calls in Java. The engineers that will be working on the orchestration and aggregation through the service bus will be middleware engineers anyway, so developing and loading a jar into weblogic to the service bus functions is not a big deal. It is a skill that exists on the team already so there is no ramp up time for the developers to get used to the XML based services, proxies, wsdls, schemas, xpath, xquery etc.

The second reason is that the service bus is very difficult to debug and refactor. There are numerous tools to debug and refactor Java classes, and eclipse is rife with them. To debug a service bus proxy you cannot track the message flow directly at each point of the pipeline, assign, replace, etc. You pump it in, debug at the webservice level and then look at the XML output. If it was java based existing tools would enable the orchestration and aggregation be debugged directly at each step.

Thirdly a lot of the XML tools were fashionable ten years ago when these technologies were created. Which is great. XML has a place and is very useful in several problem domains. The service bus is not one of them. Most project teams are resource deficient anyway, and having developers that can navigate the path from back-end, to middleware and front-end are rare as it is. Throwing another difficult to debug impediment that uses non standard tools (XPath instead of Regex) is a massive drain on feature output, and hence project schedule.

I would like ten cents for every time I have made a change in a WSDL and then had to regenerate the Proxy, the XSD and then go in and fix the bindings by hand. It is frustrating and the namespaces are a pain to keep in order at the XSD and WSDL level. Working with the OSB is a frustrating experience, especially when you have the java middleware and backend debugged, tested with junit and soapUI only to see the OSB dump null and 0 variables on your service.

I think the service buses should be done in Java and kept within the same skillset domain as the J2EE backend. This isn't an old dog not wanting to learn new tricks, rather a grizzled developer with tight project schedules seeing a weak point in the technology stack that is difficult to dampen and a source of blockers, bugs, and wtfs.

Cast a Null in Java

I was working on unit test today to do with getSingleResult() from the EntityManager's query interface. I set the test up to check no results and then an outside exception. I had the query.getSingleResult() mocked to a null and got a surprising result.


context.checking(new Expectations() {{ allowing(query).getSingleResult(); will (returnValue(null)); }});

It wasn't dropping into Exception as I expected. To my ignorance I was expecting a ClassCastException but in Java (and C#) null can cast to a type. I modified the test so that it did what I wanted and then went searching to see why you would want to cast a null.

This seemed to return the best answer. I still am not sure why it is a good idea to cast null, but in the case of method over-loading, it will ensure that the correct method is hit when passing in nulls as arguments.
Next 10 articles

Most Popular on South Sea Republic

The articles that have been viewed the most:

Most Popular Restaurants in Phoenix

Phoenix Eats Out is the restaurant review site for Phoenix, Scottsdale and Old Town Scottsdale which lists the modernist and contemporary restaurants, taverns and bars in the greater Phoenix area. This is the list of the most popular restaurants pages from phoenixeatsout.com that have been viewed the most; My personal favourite restaurants in Phoenix are AZ88, Postinos, Bomberos with Grazie, Humble Pie, Orange Table, The Vig, Fez and others coming close behind. View the complete list with the photo-journalistic style images on phoenixeatsout.com

Most Popular Hikes in Arizona

Arizona is an outdoor state and has lots of hiking in the city and around the state. Phoenix is unusual for most cities in having several large mountains in the center of the city with great hiking. Anyone who comes to Phoenix has to do the Echo Canyon trail on Camelback and the Summit Hike on Squaw Peak or Piesta Peak. The views of the city, suburbs and surrounding mountains are wonderful from Camelback and Piesta Peak. For more experienced hikers there is the McDowell Mountains in North Scottsdale that has several difficult and strenuous hikes in Tom's Thumb and Bell Pass. Alternatively, you can hike the highest mountain in Arizona. At 12,600 feet Humphrey's Peak is a long and difficult hike.

Alternate Australian Constitutions

Between 2004 and 2009 this site, southsearepublic.org, was a constitutional blog based on scoop which focused on Australian and global constitutional issues. One of the strongest aspects of it was the development of constitutions by those involved in the blog. These constitutions are the outcome: The constitutions were built using principles from Montesquieu's separation of powers, the enlightnment's universal political rights and the ancient Athenian technology of sortition and choice by lot.

Archives For South Sea Republic

South Sea Republic started in 2004 as an Australian constitutional blog in 2004 based on scoop software. It was an immigrative outgrowth of Kuro5hin. The archives for each year since then; The articles are ordered by views.

Who Is Cam Riley

Cam Riley I am an Australian living in the United States as a permanent resident. I am a software developer by trade and mostly work in Java and jump between middleware and front end. I originally worked in the New York area of the United States in telecommunications before moving to Washington DC and working in a mix of telecommunications, energy and ITS. I started my own software company before heading out to Arizona and working with Shutterfly. Since then I have joined a startup in the Phoenix area and am thoroughly enjoying myself.

I do a lot of photography which I post on this website, but also on flickr. I have a photo-journalistic website which lists the modernist and contemporary restaurants in phoenix. I have a site on the Australian Flying Corps [AFC] which has been around since the 1990s and which I unfortunately lost the .org URL to during a life event; however, it is under the www.australianflyingcorps.com URL now. The AFC website has gone through several iterations since the 90s and the two most recent are Australian Flying Corps Archives(2004-2002) and Australian Flying Corps Archives(2002-1999) which are good places to start.

Websites Worth Reading

Websites of friends, colleagues and of interest;