Category Archives: Java

String theory – StringBuilder vs. String + String in the great speed debate!

I had a debate a while back about the efficiency of string concatenation using the ‘+’ operator.
This recently came around again  on a Java forum that I had posted on.

I’d seen some code that had concatenated several strings using StringBuffer.

The code was pre-JDK 5 and we were re-using bits of it for a project I was on. Since StringBuffer wasn’t needed
as no synchronization was being performed, the first refactoring prior to migration was changing StringBuffer to StringBuilder.

What struck me as odd was that the (now StringBuilder) object wasn’t being used inside of any sort of loop structure or any other programmatic
structure that would warrant the creation of a StringBuilder object.

The code actually looked similar to this:

public String message1(String value1, String value2) {
     StringBuilder messageBuilder = new StringBuilder();
     messageBuilder.append("Value ")
     .append(value1)
     .append(" is greater than ")
     .append(value2);
     return messageBuilder.toString();
}

Since I thought this to be a bit overkill, I refactored the code to now look similar to this:

public String message1(String value1, String value2) {
     return "Value " + value1 + " is greater than " + value2;
}

Let The Debate Ensue!

This started quite the performance debate. Many of my colleagues on the project were under the impression that StringBuilder concatenation
is ALWAYS faster than String concatenation using the + operator. Many of them also thought it bad practice to use anything but StringBuilder
when concatenating multiple Strings and had gotten in the habit of using Builder’s for all concatenation in all code to “speed things up”.

I will agree that there are certain instances where using StringBuilder performs better than using Strings and +. Loop structures are one such
case. Appending to a String is much faster inside a loop structure with a StringBuilder (provided the builder was created outside the loop
structure where the appending occurs) than using + or +=.

But StringBuilder isn’t a one-stop shop for String performance enhancement by any means.

Used in the above code example it does 2 things:
1. Makes the code uglier. Granted, this is my own opinion and I’m sure that some might disagree. I personally feel
that the chained calls to append() are ugly when used like this. I think that in cases like this, using + to concatenate
Strings is less intrusive and makes the code easier to read.

2. IT ACTUALLY HURTS PERFORMANCE! – This is was the core of the above debate. Many had taken the StringBuilder for performance
pattern as gospel and had never looked into when this is applicable and when it isn’t.

If you don’t believe me, try a simple test of timing the calls of the above methods for yourself ( I recommend using
System.nanoTime() instead of System.currentTimeMillis() ).

If your a bit more curious – take a look at the actual bytecode that is generated from each of the methods using a tool like ASM!
This is where things really get interesting!

2 Comments

Filed under Java

GWT: Unterminated string constant

This is another one of those GWT “gotchas” I came across in Internet Explorer.

I have a JSON object with a field that’s chocked full o’ chars (its a big string 🙂 ) This field is displaying descriptive information on the page in every browser BUT IE (go figure).

When debugging, I got this little bugger:

” com.google.gwt.core.client.JavaScriptException: (SyntaxError): Unterminated string constant number: -2146827273 “

Well that’s helpful! So – I snagged the JSON and loaded it up in the first online JSON parser google gave me. Everything looked fine. Ugh! No errors, everything is hunky dory, but in IE, well…

After a long battle with the browsers and looking at the underlying utility class I was using, I saw that the method I was calling was using the native eval().

The method looked a little something like this:

private static native JavaScriptObject evaluate( String json )/*-{
     return eval("(" + json+ ")");
}-*/;

Aha! – this is where the problem was. Turns out that the String being passed (the JSON object) who’s very descriptive field was chocked full o chars contained some chars that IE wasn’t too happy about.

New line chars! It turns out that if you have any”\r\n” in your JSON, IE tends to get a bit angry and call it quits when eval’ing.

The solution? Well – I threw in some logic to take care of formatting the String for IE. I put the format in its own method in case I have to modify the String in any other way down the road.

Once I popped in the below, everything seemed to work AOK!

public static JavaScriptObject evaluate(String json){
     String formattedJson = formatForCrossBrowserCompatibility(json);
     return evaluateFrom(formattedJson);
}

private static String formatForCrossBrowserCompatibility(String json){
     String formattedJson = json.replace( "\r\n", "\\r\\n" );
     return formattedJson.trim();
}

private static native JavaScriptObject evaluateFrom( String json)/*-{
     return eval("(" + json+ ")");
}-*/;

Leave a comment

Filed under Java

More on Java 7 – Try/Multi-catch!

Rambling on a bit more from my previous post about new Java 7 syntax, I wanted to comment a bit on how happy I am with the spiffy new “multi-catch”!

One thing I REALLY hate to see in code is ugly try catch blocks. What do I mean by ugly? Let me give you an example

try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException e0){
     logGnarlyException(e0);
}catch(GnarlySyntaxException e1){
     logGnarlyException(e1);
}catch(IOGnarlyOpenException e2){
     logIOException(e2);
}catch(IOGnarlyCloseException e3){
     logIOException(e3);
}

I’ve seen a lot of code that looks very similar and in my honest opinion, it’s a bit of an eyesore. We have 4 unique catch blocks performing 2 unique actions. Now, since it would appear (from my very contrived example) that we’re doing nothing more that logging here, there are several ways around this. In fact, I’d argue that there are several ways to re-factor this and make it a little more “pretty”. But that, my friend, is a different post for a different day (probably a day in the very near future – I’ve been reading “Uncle Bob” Martin’s Clean Code and have quite a bit to say…)

What I’m here to write about now is the spiffy new multi-catch in Java 7.

Multi-catch allows you to place more than one exception within one catch block, separating each with the “|” character!

So, I can take the above code and modify the try/catch to look like this:

try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException|GnarlySyntaxException e0){
     logGnarlyException(e0);
}
catch(IOGnarlyOpenException|IOGnarlyCloseException e1){
     logIOException(e1);
}

Just a little FYI – the Exceptions are “caught” from left to right in a block like this, just like they’re caught top down. That is, lets suppose that IOGnarly* Exception both extend IOException.

Lets also spoz that we’d like to handle a general IOException as well. If we were handling each with it’s own catch block it’d be a syntax no-no to put IOException in a block above the other two. You’re compiler would yell, kick, and scream, tell you to fix your code and send an email to your boss and all of your co-workers.

It gets just as angry if you try to do something like this ” catch(IOException|IOGnarlyOpenException e)”so don’t do that ! Good stuff to remember if you plan on taking an OCJP 7 exam 😉

Leave a comment

Filed under Java

Java 7 and ARM – no need for close!

If you haven’t seen them yet, there are some pretty nifty new language enhancements coming (er… here) in Java 7!

One such feature allows you to remove your close!!!

No, not clothes, .close()! Lets take a look…

Spozing’ you have a nifty little method that’s in charge of writing every object in a list to an ObjectOutputStream. If one were in a hurry one might write something that went a little like this:

try{
     ObjectOutputStream objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Now, ignoring the fact that I’m catching any old error here, do you see anything else wrong with this picture?… Take a good look… Do ya see it?…

Aha! I’ve got no close() !

Having caught the issue one might decide to modify the code a little bit and do something like the following:

ObjectOutputStream objectOutput = null;
try{
     objectOutput = getDefaultObjectOutputStream();
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}finally{
     objectOutput.close();
}

But that’s ugly! I’ll have to modify the method this is in to throw IOException (since I’m not handling it in the finally) and I might want to check that objectOutput isn’t null before calling close (just in case something went awry in getDefaultObjectOutputStream(), which I didn’t do!).

Thanks to some nifty new features in Java 7, I don’t have to remember my close() anymore! Java remembers my close() for me!

Applying the new fanciness to the above, I can go ahead and do this:

try(ObjectOutputStream objectOutput = getDefaultObjectOutputStream();){
     List bars = getBars();
     for(Bar bar : bars){
          objectOutput.writeObject(bar);
     }
}catch(Exception e){
     logError(e);
}

Thanks Java 7!

If your curious about this, take a gander at ARM (automatic resource management)…

If you want to check some of the new stuff out yourself in the comforts of a reasonably friendly IDE, I’d check out the Netbeans beta! Eclipse hasn’t added support for the new JDK 7 so unfortunately, I wasn’t able to play around in my IDE of choice 😉

There’ll be more posts from me on the way, but right now I want to play! Hooray Friday!

Leave a comment

Filed under Java

Hey .intern() … get me a String!

A lot of us that work in Java take Strings for granted. Some of us toss them around like primitive types paying little regard to what they represent or how they should be used. Because of this, some classic problems like “==” vs. “.equals()” arise. Just in case you don’t know what I’m talking about here, in Java using == to test for equality between two objects (let’s call them A and B), results in a comparison  of the reference to which A and B refer, NOT the value to which they refer. Notice that I said OBJECTS. Thats the key word here. I’m not talking about primitive types like int, short, char, boolean, etc… I’m talking about OBJECTS. Sometimes, people forget about Strings being objects so you’ll see something like if ( A == B ){ … I recently ran into a bug in a piece of code that was caused by just that. It actually went a little something like if( “VALUE” ==  srt ) { …

If you read the above and scratched your head in confusion, I suggest taking some time to learn a little bit more about Strings, comparison operators, and a little bit more about Java in general before continuing onward.

If you’ve read the above and I’ve bored you, GOOD! This NEXT section is a little more interesting…

AND NOW, HERE’S WHERE THE WHEELS FALL OF THE CART!

There are times, in Java land, if you REALLY, REALLY, REALLY, know what you’re doing, when you CAN use == to evaluate 2 Strings. I’m going to warn you though – I don’t think I’d ever even use what I’m about to talk about unless I ABSOLUTELY HAD TO for some reason or another and ONLY after thorough testing.

And so, I introduce…

String.intern()

Since String objects are immutable in Java land, there are tons of little things you can do to produce all sorts of new String objects during runtime. Take for example, the following code:

String x = “FOO”;

….

public String bar(String z)

{

return z+z;

}

String y = bar(x);

So now, our variable y is assigned the value “FOOFOO”. What if, however, somewhere out in our program we had another variable w. And, lets just pretend that our variable w was assigned the value “FOOFOO” during runtime. Since Strings are immutable, we could have just used y to point to our w reference since we could, for all intents and purposes, consider them in this case to be equal.

Enter String.intern().  So, in a nutshell, .intern() is basically your way of saying “Hey… if there’s already a String out there in Java land, point my value to that guy instead. I know he’s not changing. I’ll just use him!”

Under the hood, your JVM keeps a little pool of unique Strings floating around and happy for just this occasion.  If you call .intern(), the JVM lifeguard takes a gander into that pool to see if you look like anyone in there. If you do, he points you to that guy. If you don’t, he throws you into that pool.

All of your String literals and compile time constants are in here. Runtime strings aren’t. Not unless you invoke .intern().

So, that being said, if you use this method consistently throughout your program, you COULD replace your .equals() evaluations with ==.  Why would one do such  a thing?

Take a look at the String.equals() source (right around line 854). There’s actually a LOT going on here. Especially down in that for loop! Using == might be a bit faster for evaluating equality in this case!

Here’s the catch – you incur some up front loss in performance for some gains later on down the road. Calling .intern() isn’t free OR cheap. In fact, you might see some people out there writing about how using if ( s0.intern() == s1.intern() ){…  is faster than if (s0.equals(s1)){…

I’ve run a few performance tests. Nothing too in depth (I was just curious to see for myself) but in most simple cases, the second evaluation is your safer bet. I encourage you to try it out for yourself! If you’re really curious, take a look at the byte code! In some not-so simple cases however, you MAY achieve some performance gains. I wouldn’t recommend s0.intern() == s1.intern() for evaluation, but rather s0 == s1 IF AND ONLY IF you have guaranteed that these Strings have been intern() ‘d !

 

3 Comments

Filed under Java

What Happens when you mix Internet Explorer, Microsoft Office, and Coldfusion 9? A whole lotta yuck.

So things started off bad… I’m fighting a gnarly cold and keep coughing up some gnarlyness making me grumpy and discontent. Then this:

I’ve been working on a recent migration of some (shudders as I say this) Coldfusion 8 applications to Coldfusion 9 to support  Office 2007 document types. This is in no way shape or form “glamorous” work.  First off, I hate being this high up in the stack – way too many layers of abstraction here, and way too many places for things to go wrong in some black box that nobody can see inside (small rant).

So – I make a few changes to the code and use the shiny new <cfspreadsheet> tag CF9 provides, and ship it off to QA for testing in it’s spify new Coldfusion 9 home in QA.

All goes well in Firefox and all seems calm on the homefront… Then IE rolls into town.

Within the application is a directory with a few .xls, .doc, and .pdf files. The application has a few links so the user can grab these files from the server. Firefox handled that no problem. It saw the extension, and passed it along to MS Office.

Internet Explorer, Well… it decided that it thought it was man enough to display the file on its own. It couldn’t. Instead it just barfed up the file in the browser leaving only chunks somewhat readable.

After a little digging and some HTTP Header recording user the Live HTTP FF plugin, it was apparent that the MIME type wasn’t defined.  There wasn’t any Content-Type coming back when the URL to the Office files were hit!

This is no bueno. Firefox can man up and has a stronger stomach. IE? well… No MIME type means no worky.

So here’s the problem, I have an Office Document ( .xls , .doc , etc…) sitting in a directory of a Coldfusion 9 application being served up by a Coldfusion 9 Server (yuck!) which is Java based and runs in a Java Container (in my case Weblogic) running on top of a JVM on top of a well… no need to go this far down (for this anyway).

So who or what do I tell to whom so that someone knows what MIME type they’re getting if they ask for above mentioned file???

Here’s the solution – tell Coldfusion’s web.xml file.

As it turns out, the MIME type info isn’t specified in the web.xml file out of the box. Go ahead and edit web.xml and add the following lines:

<mime-mapping>
     <extension>xls</extension>
     <mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
    <extension>doc</extension>
    <mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>

Of course, if there are other MIME types that need defining you’d better go ahead and add those too.

Go ahead and restart the CF server and presto-chango! Things should be AOK.
Good Luck!

1 Comment

Filed under Java, Rants

int i = 0; i = i++; /* How to Make Your Friends and Co-workers Scratch Their Heads in Less than 2 lines of Code */

Looking for a great way to kill productivity? Want to stump that developer who thinks they’ve seen it all? Well then have I got the code snippet for you!
(sorry – I felt the need to sound like an info-mercial salesman there for no good reason)…

Don’t ask how this problem came up… It was one of those things that started off as a joke, but then got people thinking and scratching their heads…

Consider the following code snippet:

int i = 0;
i = i++;
/* output 1 if Java use System.out.println(i); if C/C++ use printf(%d,i); */
i = ++i;
/* output 2 if Java use System.out.println(i); if C/C++ use printf(%d,i); */

Seems pretty simple doesn’t it? I bet though, that if you ask a handful of developers what the output on 1 & 2 would be, that you’d get some pretty interesting answers. This tiny little code snippet turned into a long discussion on more than one occasion. When actually run, most assumptions were wrong and many were stumped.
I suggest trying it yourself in your language of choice if your curious! You might be surprised too!… The TRULY surprising part might be that your language of choice might provide you with one answer when compiled with one compiler version, and another result when the same code is compiled using a different version.

Since this all came about in a Java shop, I immediately went ahead and ran it –
0 , 1 (yeah – I spoiled the surprise… sorry)
Wishing to get some clarification on what was going on, I surfed the web and found some help here.

It seems like (under the hood), that this:
int i = 0;
i = i++;

basically translates to this:
int i = 0;
int temp = i;
i++;
i = temp;

that is, since we’re post incrementing on the right hand side of the above, that the expression is evaluated and stored in “temp”, i is incremented, then the assignment occurs to the initially stored value… (thats what the above link seemed to point out…)

This seemed logical and explained the resulting values.

So I tried it out in C. I went ahead and wrote up the snippet and compiled with GCC version 3.something or other.
output- same as Java. 0,1.

So, I took the above explanation as a decent one that seemed to be applicable to both Java and C/C++…
Then the wheels fell off of the wagon. A buddy of mine and I were chatting when I brought up the above mentioned problem. Being the curious chap he is, he went and tried the same.
In C, using GCC, but this time version 4.2.something or other.
output… TOTALLY DIFFERENT! 1,2.

So I let out a big sigh. Back to finding answers…

The jury’s still out on this one for me. Now on my TODO list is trying to determine where and how this is defined (or if it is!).
I recently came across a site that might point to this being undefined in C/C++ (found here)
But since you can’t trust everything you read on the internet (except the stuff I write 🙂 ) I’d like to find a “more offical” source if I can.

I know its a trivial thing, but its one of those trivial things thats gotten under my skin and that I now want to know the answer to.
I know the code looks trivial too… but there is some pretty gnarly looking code out there in the wild and who know’s if anyone is doing something like this (or similar):
i = (someCrazyFunction() + 1) / i++; /* threw in the 1 for good measure! */

I guess the best thing I’ve gotten out of this is that… just because you think you know what the compiler is going to do, doesn’t mean that the compiler is going to do that. So often we take whats going on under the hood for granted. Abstraction is a great thing and helps us crank out code faster and build bigger and better (okay… thats arguable) things. If we’re going to operate within an abstraction though, we should have an understanding of not only what that abstraction provides us but also its limitations…

2 Comments

Filed under C/C++, Java, Rants

“HTTP/1.0 407 Proxy Authentication Required”

Java IO exceptions got you down? Ran a little bit of code lately that returned a runtime exception that went a little something like this:

java.io.IOException: Unable to tunnel through proxy. Proxy returns “HTTP/1.0 407 Proxy Authentication Required”

Yeah… me too. So here’s what I encountered:
The code:

//more code preceding…
final URL url = new URL(myURL);
final URLConnection urlConn;
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, portNumber));
urlConn = url.openConnection(proxy);
urlConn.setDoOutput(true);
//more code proceding…

All looks fine and dandy but if you’re like me and your proxy requires authentication, the above won’t fly.
Luckily, there’s a pretty simple fix… as always, this is just one way I found to get the job done. If you’ve come across another, post it!

Begin by making yourself a simple proxy authenticator class like this one:

import java.net.PasswordAuthentication;

public class SimpleProxyAuthenticator extends java.net.Authenticator{

private String username;
private String password;

public SimpleProxyAuthenticator(String username, String password){
this.username = username;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(this.username, this.password.toCharArray());
}
}

In the original code, import java.net.Authenticator

and modify the code needing authentication:

//more code preceding…
Authenticator.setDefault(new SimpleProxyAuthenticator(proxyUsername , proxyPassword)); //added this line!
final URL url = new URL(myURL);
final URLConnection urlConn;
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, portNumber));
urlConn = url.openConnection(proxy);
urlConn.setDoOutput(true);
//more code proceding…

Good luck!

5 Comments

Filed under Java