A New Try-with-resources Improvement in JDK 9

The JEP 213 - Milling Project Coin is a follow up to the Project Coin additions to Java 7. Note, as the JEP states, this isn't a Project Coin 2.0. It's more of an attempt at smoothing the "rough edges" that came along with these additions. Just as a reminder - with the original Project Coin, among other things, we got:
  • Strings in switch
  • Binary integral literals and underscores in numeric literals
  • Multi-catch and more precise rethrow
  • Improved type inference for generic instance creation (diamond)
  • Try-with-resources statement
  • Simplified varargs method invocation
Try with resources has been a great simplification, especially when working with I/O code. The addition in JDK 9 is an improvement of the standard try-with-resources way of writing code. Previously in Java 7 and 8 we had;


BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Original try-with-resources statement from JDK 7 or 8
try (BufferedReader r1 = reader) {
// use buffered reader
} catch (IOException e) {
// ignoring exceptions because that is how I roll
}


which works just fine, but we still needed to declare a special variable in the try-with section. The cleaner and simpler way in JDK 9 is now;

// The JDK 9 way
try (reader) {
// use the reader
}catch (IOException e){
// ignoring exceptions because that is how I roll
}

This is more "natural" way of writing even though it most use cases we don't need the resource outside the scope of the try block. The restriction is that the reader variable should be effectively final or just final. You can play around with the new way already in the latest JDK 9 snapshot. More info available in Joe Darcy's Oracle Weblog post and the related  JDK bug report.

 Originally published on https://www.voxxed.com/blog/2015/01/new-try-resources-improvement-jdk-9/

Thread Local Storage in Java


This post is part of the Java Advent Calendar, and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, Tweeting, FB, G+, etc!      
It was also republished under https://www.voxxed.com/blog/2014/12/thread-local-storage-in-java/


One of the rarely known features in Java among developers is Thread-local storage. The idea is simple, and the need for it comes in  scenarios where we need data that is, well, local for the thread. For example, if we have two threads that refer to the same global variablem but we want them to have separate values independently initialized of each other.
Most major programming languages have implementations of the concept. For example C++11 has the thread local keyword, and Ruby has chosen an API approach.
Java has also an implementation of the concept with  java.lang.ThreadLocal<T> and with subclass java.lang.InheritableThreadLocal<T> since version 1.2, so nothing new and shiny here.
Let's say that for some reason we need to have an Long specific for our thread. Using Thread local that would simply be:

public class ThreadLocalExample {

  public static class SomethingToRun implements Runnable {

    private ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());

      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
      }

      threadLocal.set(System.nanoTime());
      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());
    }
  }

  public static void main(String[] args) {
    SomethingToRun sharedRunnableInstance = new SomethingToRun();

    Thread thread1 = new Thread(sharedRunnableInstance);
    Thread thread2 = new Thread(sharedRunnableInstance);

    thread1.start();
    thread2.start();
  }

}



One possible sample run of the following code will result in:

Thread-0 null

Thread-0 132466384576241

Thread-1 null

Thread-1 132466394296347

At the beginning the value is set to null to both threads, obviously each of them works with separate values since after setting the value to System.nanoTime() on Thread-0 it will not have any effect on the value of Thread-1 exactly as we wanted, a thread scoped long variable. One nice side effect is a case where the thread calls multiple methods from various classes. They will all be able to use the same thread scoped variable without major API changes. Since the value is not explicitly passed through one might argue it difficult to test and bad for design, but that is a separate topic altogether.

In what areas are popular frameworks using Thread Locals?

Spring, being one of the most popular frameworks in Java, uses ThreadLocals internally for many parts - easily demonstrated by a simple github search. Most of the usages are related to the current user's actions or information. This is actually one of the main uses for ThreadLocals in JavaEE world, storing information for the current request like in RequestContextHolder :
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = 
    new NamedThreadLocal<RequestAttributes>("Request attributes");
Or the current JDBC connection user credentials in UserCredentialsDataSourceAdapter. If we get back on RequestContextHolder, we can use this class to access all of the current request information from anywhere in our code. A common use case for this is  LocaleContextHolder, which helps us store the current user's locale. Mockito uses it to store the current "global" configuration and if we take a look at any framework out there there is a high chance we'll find it as well.

Thread Locals and Memory Leaks

Now that we've learned about this awesome little feature, let's use it all over the place! Well, we can do that, but if you try a few Google searches, you'll find that most posts out there claim that ThreadLocal is evil. That's not exactly true. It's a nice utility, but in some contexts,  you could easily accidentally create a memory leak.
“Can you cause unintended object retention with thread locals? Sure you can. But you can do this with arrays too. That doesn’t mean that thread locals (or arrays) are bad things. Merely that you have to use them with some care. The use of thread pools demands extreme care. Sloppy use of thread pools in combination with sloppy use of thread locals can cause unintended object retention, as has been noted in many places. But placing the blame on thread locals is unwarranted.” - Joshua Bloch
It is very easy to create a memory leak in your server code using ThreadLocal if it runs on an application server. ThreadLocal context is associated to the thread where it runs, and will be garbaged once the thread is dead. Modern app servers use pool of threads instead of creating new ones on each request, meaning you can end up holding large objects indefinitely in your application.  Since the thread pool is from the app server, our memory leak could remain even after we unload our application. The fix for this is simple - free up resources you do not need. One other ThreadLocal misuse is API design. Often I have seen use of RequestContextHolder(that holds ThreadLocal) all over the place, like the DAO layer, for example. Later on, if one were to call the same DAO methods outside a request, for instance and scheduler, he would get a very bad surprise. Even though the variables in ThreadLocal are local to the thread they are very much global in your code. So, if you want to avoid maintenance developers hunting you down and taking their revenge, make sure you really need this thread scope before you use it.

More info on the topic

http://en.wikipedia.org/wiki/Thread-local_storage
http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/
https://plumbr.eu/blog/how-to-shoot-yourself-in-foot-with-threadlocals
http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable
https://plumbr.eu/blog/when-and-how-to-use-a-threadlocal
https://weblogs.java.net/blog/jjviana/archive/2010/06/09/dealing-glassfish-301-memory-leak-or-threadlocal-thread-pool-bad-ide
https://software.intel.com/en-us/articles/use-thread-local-storage-to-reduce-synchronization



How to Not Hate JavaScript: Tips from the Frontline


This article was originally published on voxxed under, https://www.voxxed.com/blog/2014/11/how-to-not-hate-java-script-tips-from-the-frontline/


In my work assisting teams with JavaScript related problems, I’ve noticed some common issues. If you're experiencing frustrations with the language too, this article might be of some assistance. Disclaimer: a few of my tips might be obvious to some of you, but hopefully you’ll find at least some useful nuggets of information here! These pointers are especially useful when dealing with enterprise applications and CMS solutions. This is where we have our code, the CMS code, the code from that team nobody wants to mention...and of course, all of them are loaded asynchronously.

The Debugger Statement


This is one of the most underused features when dealing with JavaScript, especially since it’s supported by the majority of browsers. The debugger statement was part of the first edition of ECMA Script so it's been here for quite some time.

Fundamentally it’s a simple way of adding a breakpoint. If we have code where we loop over an element list and then process the elements...



...we can add the debugger statement inside the loop so that we have a breakpoint on each iteration:



The triggering of the breakpoint happens when the execution of the code is done in the place where we have added it. In cases where there is no debugger handler - for example in most browsers without dev tools - this statement has no effect.

On the dev tools side it will appear as if we have manually placed the breakpoint.



Of course, this is not for code you want to leave in production, but it is an extremely useful feature during the development period. It has been a life changing feature for me, especially when dealing with vendor based JavaScript and a whole lot of callbacks.

Use the Console Luke!


Most of the developers use the console.log in for debugging purposes, but did you know about console.warn, console.error, and console.info? :




All of these support C style formatted output like:

console.log("Hello %s", "Brian");

There are also plenty of JS logging frameworks. Proper logging is essential in most programming languages, and JavaScript is no exception to this. Note that not all logging functions are standardized, and you might need to provide fallback for certain browsers. For reference, there is a more extensive article regarding logging in the real world here.

Overview of JS objects using Console.table()


Often we load data from various services and want have a nice view of it on our console - especially when the data is represented as a list of objects. For example, if we were to load a list of beers from openbeerdatabase.com (yes this database exists, and it is awesome). Using the HTTP GET beers http://openbeerdatabase.com/documentation/beers-get call we receive a list of objects. After receiving the list we just print it out using console.log :




The resulting list is difficult to navigate within the console. It’s tricky to get a clear picture of what the data represents. Even if we were to loop through the data, it would still be tedious. Same goes for any large JavaScript object or a list.

If we were to replace the console.log with console.table and make the call again we'd get this:


Obviously, the data is shown in a table and it is now sortable using the attributes of the objects. This makes the navigation easier. For example, this is a simple way to visually compare two arrays :

console.table([[1,2,3], [2,3,4]]);

would result into more clear version, especially if we had more sub-arrays :


Getting the Call Trace


Sometimes we want to know the call trace, aka "Who called my function". This is often visible when we get failure - but even on success, we could get the call trace using console.trace :


Note that console.trace is a non-standard functionality and is not something you should have in production. It is, however, supported by major desktop browsers.
Async Call TraceConsole.trace works just fine for normal function calls. In most developer tools we get the same call trace when we stop on breakpoint. When the call is async(callback) this information is not available because the scope of the closure(callback function) is limited to the data that it holds. Fortunately, in the newer version of Chrome dev tools we have the flag async. So what previously would have been a portion of the call information...



...now becomes a full call trace containing the scope of the caller and the callback :



Most definitely an essential feature in today's asynchronous world, in my opinion. For an extensive explanation on how the async call trace works, I recommend this HTML5rocks article.

Who’s Changing My Object?: Objects.observe + console.trace

Sometimes objects get some of their properties changed, but we cannot figure out the cause. In this case, objects.observe comes to the rescue. Let's say we want to check for all changes to our person object :



Since we have combined this with console.trace, we can also see the call trace. Awesome right?

Well not so much, since at the time of writing only Chrome supports this and it is a non-standard functionality. Fortunately, it is proposed as part of ECMAscript 7. There is also a similar internal varient for this in Gecko based browser object.watch. Then again, when it comes to debugging, anything we can get is useful. Note that Objects.observe primary function is not debugging, but it is a great side effect.

Who’s Changing My DOM/HTML Element - Aka, Who’s F***ing Up My Code ?


In complex applications, we may end up in a situation where we do not know how a certain HTML element got changed, moved, added, or had some of it's attributes modified. One way to figure out is to attach the now deprecated mutation event listeners. The API for this is far from ideal, and there are other shortcomings. The newer browser version comes with an object called MutationObserver, which enables us to watch a certain DOM element.

Suppose we wanted to list all mutations on the entire document, where the document can also be any DOM element selected :



There is also the non programmable solution we can use in Chrome called DOM breakpoints which still uses mutation events in the background.

Server Side Logging of Client Side Errors


As simple as that, just add onerror handler to the window object and you're done with the client side. The handler can then make an AJAX request to a REST endpoint which will store the error information on your server. You might find out that a client using IE 8 has a lot of issues this way, because IE versions predating 9 have no string.trim(). I guess string trim is just not that essential.

Anyway, this what the most basic server side logging of client side errors might look like:


Of course, this is the most basic of solution you can have. There are tons of better solutons out there like http://www.stacktracejs.com/ or http://jsnlog.com/ and a more extensive article on Mozilla hacks. There is also a great Hacker News discussion on this topic, but hey, this is certainly a good start!
Use Google Or Other Analytics Tools to Store Data



I know you are way too busy to be writing any backend code. so why not just store the data in Google Analytics?



You can certainly do this, but note that this is a hack, and there are a lot of better commercial options out there like http://usersnap.com if you want to be really thorough - but even a hack is better than no information, which is what most people have.

So, You Don’t Think JavaScript is “Real” Code?



I had been mulling on this idea for a long time, when, a few years back, I realised that I was making a huge mistake in my approach to JavaScript. You should take it just as seriously as Java, C# or Ruby .

Diseases are something you pick up, JavaScript is something you have to learn.

Just like other programming languages, you need a book, programming exercises and multiple projects. JavaScript also needs coding style guides, testing frameworks and code analysis, and so on. Basically everything that you have for a "real code". There are complete solutions like Yeoman and JHipster that will help you with full integration.

Unless you do this, you will always end up hating JavaScript - which is a shame considering that JavaScript is all around you! If you follow best practices, most of the time you won't be debugging any code nor resorting to clever tricks. Unless you’re Chuck, that is.

More Resources:

https://github.com/DeveloperToolsWG/console-object/blob/master/api.md
https://developer.chrome.com/devtools#debugging-JavaScript
https://developer.mozilla.org/en-US/docs/Tools/Debugger
http://msdn.microsoft.com/en-us/library/dd565625%28v=vs.85%29.aspx
https://developer.mozilla.org/en-US/docs/Web/JavaScript
www.HTML5rocks.com