JAVA_OPTS, how to use them

For most of you this is probably a very silly post, but after five years of experience I was still shocked by something about the infamous JAVA_OPTS, also known as the “-D” system properties… -Dkey=value

JAVA_OPTS is only the name under which some applications, servers, etc… group a few of these -Dkey=value properties to be passed into Java when it gets executed.

You can always pass them directly from the command-line or whatever script you’re using to trigger the execution of your program. Even combine some of them inside a JAVA_OPTS environment variable and some others outside of it.

But there are certain rules you must respect when using them, as I learnt today. I wrote a silly Java class which prints out the values for three properties that it expects with certain names, and I called this class on many different manners.

This is the (simplest) class (ever):

public class JavaOpts101 {
    public static void main(String[] args) {
        System.out.println("Property 2: " + System.getProperty("property1"));
        System.out.println("Property 2: " + System.getProperty("property2"));
        System.out.println("Property 3: " + System.getProperty("property3"));
    }
}

These are the results:

Doing it right, using JAVA_OPTS:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3"
computer$ java $JAVA_OPTS JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

Doing it right, without grouping them in JAVA_OPTS:

computer$ java -Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3 JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

Doing it right, grouping two and passing the third one:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2"
computer$ java $JAVA_OPTS -Dproperty3=value3 JavaOpts101
Property 1: value1
Property 2: value2
Property 3: value3

So how do you do it wrong?
Basically, you need to be passing the properties in the wrong place, like this:

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2"
computer$ java $JAVA_OPTS JavaOpts101 -Dproperty3=value3
Property 1: value1
Property 2: value2
Property 3: null

Even if they are grouped on JAVA_OPTS, they won’t be correctly passed unless they go before the class name…

computer$ JAVA_OPTS="-Dproperty1=value1 -Dproperty2=value2 -Dproperty3=value3"
computer$ java JavaOpts101 $JAVA_OPTS
Property 1: null
Property 2: null
Property 3: null

A little bit of documentation:

If you do man java on your command-line and have a read, apart from discovering a new spelling for impletmentations (sic), you’ll get something along this:

SYNOPSIS
  java [ options ] class [ argument... ]

  java [ options ] -jar file.jar
    [ argument... ]
...
...
OPTIONS
...
...
  -Dproperty=value
    Sets a system property value.

A couple of caveats:

Notice that you only need to use the quotes when you group the system properties under an environment variable (in these examples, JAVA_OPTS), but you don’t need to use the quotes when the properties are passed directly on the command line.
It may be worthy to note here: the order in which the properties are passed among themselves is irrelevant.

The code is on Github, even if it’s completely silly :/

AngularJS fundamentals

If you’re a backend focused developer as I’ve been in the last few years, but you can never get rid of that “I know too litle about frontend development” feeling from time to time, I guess it would be as good for you as it’s been for me to watch this video on Angular JS:

Sometimes it’s not even about the message, but about the messenger. In the case of this video, both message and messenger are really clear and easy to follow. I had no clue about Angular JS before I watched this video, and I probably still have no clue about what real life development cycle or day to day basis is working with it, but I understand now the efforts the frontend developers go through in order to do their work, and how frameworks like Angular JS may alleviate some that pain.

Gauge vs Counter

Let’s say you need to keep track of certain values on your application, to decide whether is under-performing or achieving any given intended goal, etc… so you think about what you need to measure and decide to insert some KPI’s in your codebase.

gauge

Now think about what you need to measure… is it something that increments in time, or is it something that may increment and decrement? is it something which value depends on previous values, or is it something where we only care about the value on the moment of measurement, which won’t very likely be related to its value maybe a couple of minutes before?

In the first case you will need a counter. In the second, a gauge. Why do I make this distinction?, why is it important?, why are you probably reading this?, basically because any single monitoring software I’ve used make this distinction when creating a metric or defining an alarm. Zenoss, when defining a MIB; Nagios, when specifying the data source type

Ok, yeah, very nice. But very theoretical. Give me some examples so I can understand this better.

There you go then. Examples:

- Number of concurrent visitors in a website: that’d be a gauge, we’re only interested in the number of visitors now browsing a website; grab it, record it, keep moving.

- Number of visitors in the last five minutes in a website: that’d be a counter, plus some basic arithmetics (current value – value five minutes ago).

- Memory use: gauge. We’ll send info on % of memory use at the time when the info is requested.

- CPU use: gauge, as the previous one.

- Number of requests: counter.

There is a bit of complication when you want to measure how many times something happens in certain amount of time, since you need a counter to track down the number of occurrences of the event, but you need to keep track of the previous value of the counter when the time interval comes to an end. To make your life easier, some libraries written to help you track down values for your KPI’s contemplate a third type of metric, called, precisely, meters… but that’s getting out of the scope of the present post.

 

Ceki Gulku on SLF4J and logback

I suppose you all know who Ceki Gulku is, but you may not have seen him explaining some aspects about some of his creations. I quite liked this talk, even if it’s five years old… after all, it’s not like logging frameworks have evolved too much anyway since then.

Log4j 2.0 seems to be gaining followers even if it’s still a beta… but for me, SLF4J with Logback still makes the trick, and this guy was massively involved on both projects.

If you feel like the topic deserves an hour of your time, don’t think it twice. Enjoy.

 

Updating your old SCJP X to the new shiny OCPJP 7

As you can read here, the only thing you need to do (if you have one of the old SCJP’s) is an upgrade exam (1Z0-805), focused mostly on the new bits added on Java 7. I’ve created a repository on Github with code examples that I’ve been gathering during my preparation.

upgrade Path

upgrade Path

I’ll upload as well at some point a pdf with some study annotations that I think may be useful to others.

I know plenty of you are very sceptical about certifications but I still think they are quite useful. If not per se, the process (meaning the study + work) you need to go through to get them it certainly is. I’ll be writing a post on this at some point as well.

Java 7 try-with-resources explained

While it is widely accepted than checked exceptions on Java wasn’t the brightest idea, when Java 7 came out there were a couple of things added regarding them that supposedly were going to make our lives easier. Catching multiple exceptions at the same time is easy enough, and I definitely think it is a straight forward and direct improvement. The other bit added, try-with-resources, looked like a good idea to me too, but I didn’t really know much about it until very recently, when I had a more careful look at the existent documentation an tried to get my head over it. In order to do that, I quickly wrote a few classes to illustrate the different possible scenarios depending on the place where an exception can be thrown.

Let’s have a look at the simplest scenario, where no exceptions are thrown.

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As you see, now you can declare and initialize some resource when writing your try. In this case, I am creating a resource of a custom class MyResource (which we’ll see in a moment), doing something with it, anyGivenAction(), and closing it. Before we get into many details, let me tell you the first bit I didn’t like about this: it was easier to refer to the different elements of an exception code snippet before… you could say the try, the catch or the finally and everybody would know what you’re talking about. Now it is a little bit more complicated: whereas the catch and the finally remain unaltered, the try now has two different “locations”: the resource area and the body of the try, the classic try, let’s say… no big deal, really, but still, old way of naming comes a bit short. For example, the connotations of an exception being thrown on the resource initialization area or on the body of the try are quite different.

But it gets worse. Let’s have a closer look to the resource area of the try…

   ...
        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
   ...

The only requisite for a resource to be declared there, as described on official Oracle documentation:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Let’s have a look at MyResource class:

class MyResource implements AutoCloseable {

    private boolean throwOnInitResource;
    private boolean throwOnAction;
    private boolean throwOnCloseResource;

    MyResource(boolean throwOnInitResource, boolean throwOnAction, boolean throwOnCloseResource) throws InitResourceException {
        this.throwOnInitResource = throwOnInitResource;
        this.throwOnAction = throwOnAction;
        this.throwOnCloseResource = throwOnCloseResource;
        if (this.throwOnInitResource) throw new InitResourceException();
        System.out.println("Resource opening, no exception.");
    }

    public void anyGivenAction() throws ActionException {
        if (this.throwOnAction) throw new ActionException();
        System.out.println("Any given action happening, no exception.");
    }

    public void close() throws CloseResourceException {
        if (this.throwOnCloseResource) throw new CloseResourceException();
        System.out.println("Resource closing, no exception.");
    }
}

It implements AutoCloseable interface as it implements the close() method specified by it. The other methods on the class are the constructor and anyGivenAction(), a dummy example of specific business logic for the class. The three boolean flags received on the constructor will control if an exception is thrown on any of the three methods of the class: while constructing, while executing anyGivenAction() or while closing the resource respectively. Every exception thrown is named after the place where it is thrown. This will be useful later on.

So why did I say it gets worse?… well, the finally section is intended to be used to close any resource open after the code that can thrown an exception uses it. But in the new try-with-resource, closing the resources happen automatically if they were declared on the resource area. So the resource area contains an implicit finally now, apart from being used to declare and initialized the resources to be used on the body of the try. You can have, also, an explicit finally in which wrap up anything not explicitly declared or initialized on the resource area of the try. See?, it got worse.

Let’s revisit the simplest case, where no exception is thrown anywhere:

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As the class is initialized with three false flags, no exception will be thrown within any of the three methods of MyResource. Let’s see the output of this program when run:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally

The catch is not visited, obviously, and the explicit finally is happening in the end, as expected. MyResource object declared on the resource area gets initialized and closed automatically, and in between, anything on the body of the try will happen. In this case, anyGivenAction(). Expected behaviour so far, nothing strange.

If an exception is thrown now by the code inside the catch, it would make no difference, since that section wouldn’t be visited. What happens if an exception is thrown inside the explicit finally, though?

public class OnlyFinally {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output would be:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.OnlyFinally.main(OnlyFinally.java:17)

Nothing unexpected here either. But let’s have a look at the different cases of an exception being thrown while inside MyResource, and see how they combine with exceptions being thrown on the catch and the explicit finally. It can get really funny, bear with me here…

The simplest case is when we get an exception while initializing MyResource:

public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(true, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

The first true argument when building MyResource will trigger the exception on construction. In that case the exception is caught in the catch:

Catching class trywithresources.exceptions.InitResourceException
At the finally

What happens if the exception is thrown within the body of the try, though?

public class OnlyAction {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

In this case an exception is thrown on anyGivenAction(), have a look at the second argument true on MyResource construction. The output would be:

Resource opening, no exception.
Resource closing, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Before we get into the catch code that will handle the exception, try-with-resource ensures that the resource is closed. The implicit finally code has executed before the catch, as expected, same as in Java 6.

What if an exception is thrown on the implicit finally, when closing the resource then?

public class ActionAndClosing {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

When run, the output would be:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Wait, what?! Didn’t you just say that we were going to throw an exception while closing the resource?, yes. Doesn’t that happen after we throw the exception on the body of the try, but before it gets treated on the catch?, yes. Isn’t it supposed to be treated on the catch, instead of the ActionException thrown on anyGivenAction() then?, well, you would think so… but no. The CloseResourceException thrown on the implicit finally gets suppressed. When confronted with more than one exception being thrown, the compiler is able to distinguish the important one, let’s say… the one that happened during the business logic being executed within the body of the try, instead of the one being thrown within the implicit finally of the try-with-resources, where you are just closing the resource. If you still want to know about the suppressed exceptions, you can get them from the one that was finally thrown:

public class ActionAndClosingSuppressedInfo {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception exceptionThrown) {
            System.out.println("Catching " + exceptionThrown.getClass());
            for (Throwable exceptionSuppressed: exceptionThrown.getSuppressed()) {
                System.out.println("Suppressed: " + exceptionSuppressed);
            }
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

Output of this:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
Suppressed: trywithresources.exceptions.CloseResourceException
At the finally

It kind of makes sense than the exception officially being thrown is the one happening on the body of the try, instead of the one happening on the implicit finally. The problem is that this behaviour is completely opposed to the one we got if the exception is being thrown on the explicit finally area. As you may remember from Java 6 lost exception problem, when an exception is thrown in there, it doesn’t really matter if you had an exception or not being thrown in the body of the try, or even in the catch for what it’s worth, the only and final exception being thrown would be the one on the explicit finally. So, for example, in the scenario where you have an exception being thrown on anyGivenAction(), while closing the resource, even when catching the exception and on the explicit finally:

public class AllButOpening {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
            throw new CatchException();
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output is:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.AllButOpening.main(AllButOpening.java:19)

A behaviour which is consistent with the Java 6 exception treatment but it’s opposed to what Java 7 does on try-with-resources implicit finally.

I suppose that what they’ve tried to do with the suppressed exceptions is precisely fix Java 6 problem when you literally lose an exception if another is thrown on the explicit finally.

It seems to me a half-way solution for a problem that should never has been there anyway, quite incoherent with the previous version of the language to say the least.

I’m really sorry about the extension of the post, but certain level of detail was necessary to illustrate the different outcomes of the possible cases. I hope you found it useful.

Ways to check if a String is null and if it’s not, if it’s blank

Quick clarification: the empty String is “”. ” ” is not considered an empty String, but it’s a blank one. If it contains nothing but whitespace characters, it’s a blank String.

If you don’t want to use any third-party libraries, you should do it the long way:

if((s != null) && (!s.trim().equals(""))

If you don’t mind bringing over a third party library into your project classpath, you have a couple of clear options.

With Apache Commons Library:

if(StringUtils.isEmpty(s))

Or:

if(StringUtils.isBlank(s))

The difference between the first and the second being in the fact that isEmpty(s) will return false if s is a String composed of spaces, like “   “, whereas isBlank(s) will detect that case and return true for it. Doing isEmpty(s.trim()) would skip that problem, but it would create a new (and unnecessary) String object.

With Guava:

if(Strings.isNullOrEmpty(s.trim()))

In this case, doing trim() is necessary, since the method isNullOrEmpty does not return true if it does not receive the empty String.