Feb 29, 2016

2015 conference talks

The past 2015 has been very eventful year for me on both professional and private plan. I got married, moved to Sweden, started working for Klarna and did a lot of talks on events around Europe, here are the recordings and summaries of them

JPrime 2015: the core libraries you always wanted

It was a great community event organized by BGJUG. I also got a chance to meet up with some of the friends there. One big highlight of the conf for me was beeing able to meet Bozho, one of the top contributors on StackOveflow. We even got a selfie but after an extensive search I am unable to find it. The team is preparing next year's event and they had few smaller events in the meantime like JProffesionals. In any case here is my talk on goodies from Guava:

Voxxed days Belgrade 2015: Microservice and distributed systems decoupling patterns

A first-time event for the Heap Space community and the best Voxxed event I have been( probably best of them all). Great content, awesome speakers and superb organization. Some photo from the organizers :

Devoxx BE 2015 : Updates to the Java API for JSON Processing for Java EE 8 with Alex Soto

It is one of the best conference in the Java world and I was delighted to have a talk with Alex on the JSR we have been working on. It's the latest additions to the JSON processing for Java EE. One mind blowing thing for me was that in parallel with us there was a talk by Andrew Tanenbaum. And yes it is THE Andrew Tanenbaum. While there were tons of other great stuff during the conference this was my personal highlight.

Same year I also talked on VoxxedDays Istanbul and had a panel on EOUS. I am happy to have taken part in all of these events and hope to have brought value to the folks who listen them. Until next time ...

Feb 26, 2016

JFokus 2016 : Java Awesomeness in the Heart of Scandinavia

Originally published on Voxxed https://www.voxxed.com/blog/2016/02/jfokus-2016-bringing-awesomeness-heart-scandinavia/
After watching many sessions online, this year I was able to attend Jfokus in person for the first time. This was the 10th edition of the event, bringing over 1800 attendees. One other thing to note is that the conference was sold out 2 weeks in advance, which as JFokus main organiser Mattias Karlsson commented, "hasn't happened in several years". This is testament that the Java community is still alive and kicking after all this time.

Amusement park fair party As a prequel to the main conference, there was a JFokus VM Tech Summit chaired by my Klarna colleague Markus Lagergren. Unfortunately, I didn't got visit this part of the event but Simon Ritter has a great write up on the Azul blog. The same day university sessions with 3 hour presentations on topics ranging from Mob Programming to TinkerForge and RXJava. The conference day started off with a great keynote by Brian Goetz on Java's evolution and future evolution.
There were many great talks throughout the day and you can see the speaker lineup as well as some of the presentation slides on the schedule page. I would really like to highlight a few which really got me thinking:
  • 'Git from the Bits Up' by Tim Berglund followed the creation of a git repository and how the information is internally represented by looking at the .git folder.
  • 'From Concurrent to Parallel' by Brian Goetz took me back to the college days of a parallel vs. serial code
  • Making Java more dynamic by Rafael Winterhalter covered the awesome topic of bytecode manipulation and how Byte Buddy can make things more simple.
Throughout the conference, Stephen Chin was live streaming and filming his NightHacking sessions. You can find the recordings on his blog but I would like to recommend the one from Simon Ritter on Struct-Like Performance in Java. The organisation was also excellent - internet at all times and no technical problems. I particularly enjoyed the amusement park-like theme of the party and the Atlassian and Red Hat bars. What followed the conference as a three day speakers (un)conference. Unfortunately this was not open for the general public, but two lucky people were selected to join the speakers in Vemdalen. Having taken part in unconferences before, I do understand the need to keep it small, but I would say that having few more outsiders is always good for the community. Here are few Tweets from behind the scenes:
Last but not least, here is a message from the JFokus team
And a few other images of the event up on the Flickr page,

Feb 4, 2015

HttpClient 4.x Timeout

HttpClient is one of the most versatile Java libraries. Unfortunately, it comes with a lot of configuration options that may be way too cryptic or difficult. While the API for 4.x series has been significantly improved there are still some sharp edges.

The deprecated or 3.x way of setting the timeout.

This is done using params. Note that this is still 4.x code but a deprecated one.

DefaultHttpClient httpClient = ...;
HttpParams httpParams = httpClient.getParams();
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000L);
httpParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, 1000L);

Now the part httpClient.getParams() is deprecated since obviously this is a nasty API. You need to keep track of parameters with Enums/constants and their type as well.

The right 4.x way aka the builder way

HttpClient 4 is full of builder for everything. While I often love the Builder patterns in some cases the testing part is really difficult but I guess it is always a tradeoff. This would be the "right way".

public RequestConfig requestConfigWithTimeout(int timeoutInMilliseconds) {
        return RequestConfig.copy(RequestConfig.DEFAULT)

The meaning of the parameters

Notice that we are actually setting 3 different timeouts.
  • Socket Timeout - this is the time of inactivity to wait for packets to arrive
  • Connection Timeout - the time to establish a connection with the remote host
  • Connection Manager Timeout - the time to fetch a connection from the connection pool
The third one costed me dearly, it wasn't until the client was under a high load that issues started happening. The connection pool I was using had 10 connections per route limitation set and the scenario was quite common. As you can see these settings do not provide a mechanism for making an N millisecond hard timeout.

If we were to setup the timeout to 10 seconds on each of this we could end up with a request that lasts 9(sec to get a connection) + 9( sec to open connection ) + 9( sec of inactivity ) = 27 sec.

More info

A bug when setting the ConnectionRequestTimeout
The RequestConfig Javadoc
Apache HttpClient examples

Jan 31, 2015

JavaDay 2014 a leap forward

Java Day is an event that jug.mk organizes for the past 5 years. From the small group of enthusiastic presenters in EU-info center in Skopje to a full 7h filled with lectures at a cinema hall JavaDay has grown to be one of the leading technical events in the area.

What has changed over the years and what the future holds

We started out as a small event with only local speakers in 2009 happening each year since then. In 2013, we had 1 person outside of Macedonia. The need for diversity was becoming more apparent. 2014 was the year we went fully international with 6 speakers coming from Switzerland, Serbia, and Bulgaria. We had participants in the audience from all the neighboring countries.
The Bulgarian JUG presence was a great addition and an awesome connection between our JUGS.

The keynote 

Corsin Decurtins, CTO of Netcetera gave an awesome talk on "how to become a great developer".
To quote the abstract:
At the core, the job of a software developer is and has always been the same: writing good, elegant, sustainable and bug-free software that exceeds the expectations of your clients. But the context in which we do our job is changing and with it the skills required to be a great software developer. In this talk, I want to go through a couple of things that I think make the difference between a developer and a great developer. This includes some technical skills and practices, but also non-technical things that you might not consider relevant for a developer at first.
The talk was extremely well perceived by the audience. This is very visible by the survey where he got the best reviews also by the fact the we were approached multiple times by persons telling us we need more of this.

Why this type of events are important to the community 

Conferences help you get in touch with other like-minded persons. They keep you up to date with modern technologies and interesting concepts.  Also it is great for the companies where it enables them to reach narrowly selected audience, they get to promote himself and be recognizable.

Female participation @ JavaDay

This year we also had our first female speaker Raluca Breaur one of the organizers or the Agile meetups and Java User Group in Iasi, Romania. She had an awesome talk "Caching – oldie but goldie"  with great analogies for caching systems.
It is unfortunate that after so many JavaDay this was our first female speaker especially since the from the side of the attendees we had more than 30%. 
Few weeks later a nice initiative was started by forming a local chapter of JDutchess. Few of them were also involved in the organization and we extremely grateful.
I am just hoping that next years event will have lot more of this group.

What's next 

Hopefully sometime in the near future we are gonna get the video recordings processed and uploaded to Parleys.
We continue next year and try to make the event better. Going bigger is also an option but we are not sure if that is the right direction. We definitely wanna raise the organization level and the quality of the event.
Special thanks to the 7 sponsors that supported up and without them the event could not be free.

We had a little competition about choosing the next name for JavaDay so next year we might be called Javalicious.  
The organizing  team

The survey

Notice the Gaussian distribution for the speaker reviews :) 

Jan 21, 2015

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/

Dec 18, 2014

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 variable 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 a 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();

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

      try {
      } catch (InterruptedException e) {

      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);



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

Thread-0 null

Thread-0 132466384576241

Thread-1 null

Thread-1 132466394296347

In 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 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


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 the 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 in 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 in 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 a 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 the 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 of 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 the 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 variant 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 the error 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 solutions 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 over this idea for a long time, when, a few years back, I realized 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 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:


Nov 25, 2014

Java2Days 2014: From JavaSpaces, JINI and GigaSpaces to SpringBoot, Akka – reactive and microservice pitfalls

This my 5-th year in a row where together with jugmk attend Java2days, a conference in Sofia, Bulgaria. While not so obvious from the name it is a 2-day java conference and currently the biggest one near us that we can take a bus to go to.
This year I had a talk titled "From JavaSpaces, JINI and GigaSpaces to SpringBoot, Akka – reactive and microservice pitfalls."
or buzz words and hate words all in one.

About the topic 

My talk this year was about microservices even though it had a long title with lots of strange words it was more of a concepts talk.
I gave a basic introduction into what reactive programming means for different people, the reactive manifesto and of course Microsoft Excel.
Long title = crowds of attendees
Next part was to define what microservies are and what they can be for different organization.
The Unix aspect of microservices had to be covered so I did just that.

My goal with the talks was not really to compare frameworks for this or that, but I just gave a short overview of what ideas are behind the development of some libraries.

The last major section was the real conclusion phase called how not to fail at microservices.
I gave some  recommendations from my personal experience as well as references to important books on the subject.
One of them available on early access:

And also the famous Release It book which covers some of the scenarios that are essential for microservice development.
My main take out from the talk was:
 Don't fall for the hype and make sure you start small and then grow. If your team and operations can  handle it then increase the granularity. 

Here are the full slides of the talk:

Microservice pitfalls from Mite Mitreski

The conference 

As for the full conference it was great  to meet up with BG-JUG folks like Ivan St. Ivanov, Mihail Stoynov, Martin Tosev  and improve the cooperation between JUGMK and BG-JUG.
 There were also the  standard visitor's Josh Long and Andrew Lombardi who are there to stay :

I got to meet with John Davis and learn how others use archaic tuple space technologies and how the banking world functions. Overall it was a great experience and even though at time some of the conference topics were overly light or outdated for my taste but the social aspect of it was more than sufficient to cover any shortcomings on the technical side.
For example Mani Sarkar had a great talk on "Learning the two Ts", it was great to meet up with him as well.

One other positive trend that is happening this year is we had record number of JUGMK speakers and participants on Java2Days. The same trend is also on other conferences and is a great thing to see.

The JUG Factor

I know I'm forgetting someone to mentions, but overall an interesting social experience and a great meetup. 

Apr 13, 2014

Virtual Java User Group - simple concept with quality content

Virtual JUG is a simple concept based on the idea to organize a group that would generate quality content.
It is simpler to get technical leaders from around the world to present online and there are no travel cost concerns.  The intent is not to replace local JUG's but rather increase their value and also represent a sort of global JUG. Additionally it enables developers without an access to a local jug with a means to connect with many developers around the world.

Live sessions are streamed online and as chat ##virtualJUG on Freenode is used. But you don't have to trust my word for the quality of the content, here is a list of the past sessions: 

Many thanks to Simon Maple the organizing team Anton ArhipovGeert BevinJames GoughOliver White. Keep up the good work. 

Apr 9, 2014

*nix for developers

Unix and Linux in their various forms are everywhere. Werther you are working on some server-side application or mobile app at any stage it is very likely that it will use Unix at some point.
That is why at our company we decided to have a small introduction demo/discussion on some useful concepts and command line tools.
We also went through a high-level overview starting with initial with run level and job control.
While most of the demoing is not visible via the slides I decided to share the slides anyway:

2015 conference talks

The past 2015 has been very eventful year for me on both professional and private plan. I got married, moved to Sweden, started working f...