Friday, 19 April 2013

Infamous Java bugs and pitfalls

In year 2000, I was in university and was on the verge of picking a language to build my career on. Java was not yet the mainstream but highly popular and on the spots. Applets were (not yet broken) fancy, shiny when compared to static html pages. Swing was not a bad choice to build desktop apps. J2EE was rising and getting attention.

It has been 13 years since then and Java went mainstream although applets failed miserably, not really considered for desktop apps and J2EE was too complicated to even build simple stuff but still nothing stopped Java from being the most popular programming language.

It was no surprise, Java is beatiful, type safe and easy to learn language. There were many very good implemantation details in Java such the garbage collector, strings (finalized class), collections which offer great implemantations of merge and quicksort, built in hashcode methods and many more. However, still Java is far from being perfect and may introduce some unexpected behaviour.

The abs bug:
Well this is a very minor flaw but there is a probability that Math.abs() function may return negative value. Weird? actually simple, Java integers can get a value between -2,147,483,648 to 2,147,483,647 which clearly shows -2,147,483,648 can not be represented in positive.
So is this a bug? Well the expected value is positive so yes definitely but in the end this is actually an overflow. So how to fix it? One way would be checking Integer.MIN_VALUE before using abs function or using bit operators to manipulate negative sign instead.

Autoboxing the primitives pitfalls:
Autoboxing makes it easy to work with primitive types and their object counterpart. However moving between them may introduce some unexpected behavior. For example Integer i1=6 can not be compared to Integer i2=6 with == operator where int i3=6 can be compared to those with ==. However using equals may not work as expected too. For example Long x=0L; returns true when x.equals(0L) but returns false when x.equals(0). Weird? Not really since x is long where 0 (without L) is int. So those are not even same object types. Also using primitive types with collections may result unexpected behavior. Finally Autoboxing may result problems in overloading. Lets say we have Integer i=6 and call method sum(i); and we have two sum methods like; sum(long val) and sum(Long val). Which one do you think will be called? Again reasonable but not expected to see at first look and may lead problems in your app.

BigDecimal constructor bug:
If you haven't already check Java Puzzlers from Joshua Bloch. If you create two Big decimals using double constructor (x1=new BigDecimal(2.00) and x2=new BigDecimal (1.10)) and use subtract (x1.subtract(x2)) you will end up with 0.8999999999. The double constructor of BigDecimal doesn't work as expected and string constructor needs to be used instead (new BigDecimal("2.00")). This might be a serious problem since BigDecimal is widely used for money calculations!

System.out.println pitfall:
println() is one of the first functions that is tought to cs students. It is easy and used often. Usually quite ok to use when you are trying some logic or debugging some values. However System.out is synchronized so acquires a lock when accessed. So using println can cause your app to run in synchronized context which actually means threads will be blocked when accessing println. Imagine a webserver and an app logging with println and you will end up with thread locks and each request waiting for other. So println is ok and useful but not for real apps and logging!

Map bug:
Again take a look at Java Puzzlers from Joshua Bloch, the fifth puzzle(size matters) introduces a strange behavior between an HashMap and an EnumMap where with same values, one map has a size of 2 where the other is 1. Several Map implementations such as IdentityHashMap, EnumMap may introduce this behavior.
Is this a bug? Well certainly we expect same principles from map implementations but Bloch describes that as the spec was not clear at the time.

Cpu Number bug:
This may not be a huge problem unless you really rely on hardware. To get available processor count Java offers Runtime.getRuntime().availableProcessors() method which returns an int number as the number of the processors available. However you may end up getting unexpected numbers if you give a try. For example on my quad-core i7, I get 8. So this method does not return the number of hardware cpus nor the number of cores but the number of execution engines (virtual cores). In my case because quad-core i7s support hyper treading it actually acts like it has eight cores.
So is this a bug? Definitely not since the hardware and the OS acts as if they have that number of physical cpus but still be careful counting if you rely on solid hardware.

Generic arrays
In Java arrays are created as follows, int[] arr=new int[5]; so if you have a generic type of T, you would expect to create a generic array this way: T[]=new T[5]; but simply you can't. Java does not allow generic array creation and this is actually because generics are implemented in Java using Erasure. Generics are implemented purely in compiler level and actually only one class file is generated for each class. So to create the array we need an ugly cast as follows, T[]=(T[]) new Object[5]; and when you try to compile, the compiler will issue a warning that you are doing an unsafe cast!
Of course this is not bug, it is just an implementation problem given for the sake of simplicity and compability when generics were implemented. But raising a compiler warning on a design issue may confuse someone who faced it for the first time.

So this is definitely not the end of the list but still Java offers a beatiful syntax, type safety and a realiable easy to learn language. And finally no language or implementation is perfect!

Wednesday, 23 January 2013

WindowsPhone8 expects HTML5 apps without Javascript??!?

I am not a huge fan of WindowsPhone8 and Microsoft. In search for a HTML5 mobile framework which works on Windows Mobile, I installed Windows 8 and VisualStudio. Before diving into VisualStudio, I tried few HTML5 frameworks on the mobile ie to see which one(s) seem to be working which I already mentioned in previous post.

Since jQueryMobile was the only working framework on WindowsPhone, I wanted to give a try and dive in to VisualStudio. Unlike android and ios IDEs, Visual Studio had a HTML5 app template which seemed to be a good idea.


I already had a nice app template from adobe which have few pages and a custom style so was perfect for testing.

However, the result was far from being perfect...

Again, I went back to ie10 which seemed to be working fine. So I started with playing the developer tools to see if I could make the webapp fail in similar way. After playing a little with css, I realized turning off the scripts make the page fail in a similar way.



I decided to check the template app in C#. I was thinking this was a desperate effort since this was the HTML5 app template for the WindowsPhone from Microsoft itself. The code block was pretty simple:


<phone:WebBrowser x:Name="Browser"                          HorizontalAlignment="Stretch"                          VerticalAlignment="Stretch"                          Loaded="Browser_Loaded"                          NavigationFailed="Browser_NavigationFailed" />

After playing a while with WebBrowser's properties, I realized there is a property called "IsScriptEnabled". Well that should be nonsense to have this turned off by default, even if it was since this an HTML5 app template from the official IDE it would already been set to true.

It turned out that it wasn't setting this property to true, let the app run as expected.

<phone:WebBrowser x:Name="Browser" IsScriptEnabled="True"                          HorizontalAlignment="Stretch"                          VerticalAlignment="Stretch"                          Loaded="Browser_Loaded"                          NavigationFailed="Browser_NavigationFailed" />



Seriously Microsoft, do you really think an HTML5 app is something without Javascript? I can understand this to be turned out by default for the webbrowser component but I really can not understand how would you not set it on automatically for an HTML5 app template!

Monday, 21 January 2013

HTML5 is there but not sure if WindowsPhone8 is there yet.

Two years ago I was a keen supporter of Native Development since HTML5 but things have changed. Both Mobile browsers and HTML5 move forward. Meanwhile I discovered mGWT which let me code typesafe Java and run highly optimized Javascript with nice well built mobile widgets.
Since then I have been using mGWT for most of my mobile applications and unlike Mark Zuckerberg, I really believe HTML5 is already there.
Last month Sencha released their Facebook application the Fastbook which clearly showed HTML5 was already there but clearly facebook's mobile team was not.

However, when I started to try some apps on WindowsPhone8, even most promising HTML5 frameworks started to fail. Honestly I don't see much future on WindowsPhone but some clients do.

Here are some screenshots from demo applications of the popular HTML5 Frameworks.

Sencha: The creators of the great Fastbook, fails fast on WindowsPhone8. The kithenSink application from sencha, sinks fast and is not usable at all.

mGWT: My favourite mobile framework for mobile web apps also fail fast on WindowsPhone although gwt usually does a great job with ie. The Showcase app seems to be running but not really functioning.

Dojo Mobile: Dojo Mobile Showcase app seems ok at first. However there are major problems with UI (ex buttons). Also scrolling lists may end up pushing the whole list out of the screen which is not a well known experience.

jQuery Mobile: The demo app of jQuery Mobile seems to be the only functioning one above all. The experience is still not as smooth as iOS or Android counterpart but acceptable. Some minor UI failures happen but given WindowsPhone's market share, thats welcome. The widgets are not as shiny as mGWT but again thats ok if WindowsPhone is in the game.

Conclusion: mGWT is still my choice of HTML5 dev environment. I code and debug typesafe Java and get optimized Javascript in return. The widgets are shiny and fast. Styling is peace of cake. However if supporting WindowsPhone is an issue, the only thing I could come up with is using jQuery Mobile. It would be best if Microsoft stops stupid PR campaigns like #androidrage and make themself available for real competition.

But honestly supporting WindowsPhone8? Seriously?!?!

Tuesday, 23 October 2012

JavaEE Revisits Design Patterns: Decorator

This time last year I wrote a series of blog posts on JavaEE implementation of design patterns. Roughly after a year, I realized I missed my favorite pattern, the decorator.

Decorator pattern is basically a way to extend functionality of an object by decorating with other objects which can wrap the target object and add their own behavior to it. If you never used or heard of decorators, I highly recommend reading chapter 3 of Head First Design Patterns.

Pretty much like other patterns mentioned in my posts before, JavaEE has an easy an elegant way to use the decorator pattern. Lets start with a simple stateless session bean.


package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
    
    public void startService(){
        System.out.println("do something important here...");
    }
}

To start implementing the decorator pattern, we need an interface so we can bind the decorators and the object to be decorated together.


package com.devchronicles.decorator;

/**
 *
 * @author murat
 */
public interface ServiceInterface {
    public void startService();
}

The interface has the method which the decorators will add functionality on. Next we need some changes on our existing EventService bean to make it decoratable.


package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService implements ServiceInterface{
    
    public void startService(){
        System.out.println("do something important here...");
    }
}


Now we are ready to add as much as decorator we need. All we need to do is to annotate our class, implement the ServiceInterface and to inject our service delegate.


package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator //declares this class as a decorator
public class DecoratorService implements ServiceInterface{ //must implement the service interface
    
    @Inject //inject the service
    @Delegate //and annotate as the delegate
    ServiceInterface service;

    @Override
    public void startService() { //implement the startService method to add functionality
        System.out.println("decorating the existing service!");
        service.startService(); //let the execution chain continue
    } 
}

Several decorators can be using the service interface.


package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator
public class Decorator2Service implements ServiceInterface{
     @Inject
    @Delegate
    ServiceInterface service;

    @Override
    public void startService() {
        System.out.println("decorating the service even further!!!");
        service.startService();
    }
}

Most of the configuration can be done via annotation in JavaEE6. However we still need to add some xml configuration to make decorators work. It might seem disappointing since we already annotated our decorators but still the configuration is pretty simple and needed in order to declare the order of execution. Add the following lines to the empty beans.xml.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
           <decorators>
               <class>com.devchronicles.decorator.DecoratorService</class>
           <class>com.devchronicles.decorator.Decorator2Service</class>
           </decorators>
</beans>

When the startService method of our EventService is executed, the decorators will decorate the ejb and add their own behavior to the execution.

...

INFO: WEB0671: Loading application [Decorator] at [/Decorator]
INFO: Decorator was successfully deployed in 2,534 milliseconds.
INFO: decorating the existing service!
INFO: decorating the service even further!!!
INFO: do something important here...
...





Monday, 22 October 2012

JavaOne 2012: The Good, The Bad and The Ugly...

Just like last year JavaOne was prior to fleet week and the weather was great. It is always great to visit San Francisco and see some 'regular' JavaOne friends like Van Riper and Yakov Fain.

This was Oracle's third JavaOne and there is no more JavaOne 2.0 posts anymore. So seems like everybody already get used to the new JavaOne.

JavaOne 2012, The Good...
Although my first intentions were pretty negative against Oracle's Sun buyout and the first JavaOne which Oracle organized, it is obvious that Oracle is doing great with Java. They might still lack at understand the community but they are doing ok. Oracle is really committed to development of Java. JavaEE6 is doing great and if JavaEE7 can show a similar fast adoption, it would definitely rock. JavaEE has never been so fast, lightweight, robust and productive so Oracle really succeeded in enterprise.
JavaSE is also doing great. JavaSE8 will be introducing a variety of new concepts to Java programmers, including default methods and lambda. Oracle is really committed to the time plan so they did not hesitate to drop out features which seem to be late. This schedule commitment is good for all vendors and the community so again well done Oracle.
Java on desktop has been dead for long. Honestly I wasn't really expecting a keen support from Oracle but they are also doing good with JavaFX. I really appreciate Oracle for hiring JavaFX professionals such as Stephen Chin and giving them appropriate responsibilities. JavaFX might not be a real -strike back- but it is a good effort and the community is happy to see Oracle's commitment.
Finally it was great to see James Gosling back on the stage for the keynote.

The Bad...
JavaME is dead and finally Oracle seems to accept the fact. The mobile content was very poor. Since the Google-Oracle war on Android is over, it might be wise for Oracle to act as a step-father for Android else next year JavaOne will have no mobile content. Project Jigsaw has been left out from JavaSE8 to catch up the release date but being left to JavaSE9 clearly mean it would be too late. Again it might be wise to adopt OSGi and bundle it with JavaSE8.

and The Ugly...
The conference is getting worse in terms of content. I didn't really see as great sessions as previous years. Lack of former Rock Stars is pretty obvious. Since the Google-Oracle war is over, it would be wise to get some Google content like android and gwt. At worst since Joshua Bloch left Google, he might be back on stage next year.
The venue is getting worse. Kicking out JavaOne from Moscone and spreading the conference into three hotels was a bad idea but it is getting worse with another venue getting involved for sunday keynote. Why not using Moscone for the sunday keynote? Oracle has Moscone South, North and West where Apple and Google only rent Moscone West to perform their annual conferences. Why not sharing venues for at least the sunday keynote than sending hundreds of developers to somewhere else?  I don't really understand why Oracle insists on same dates for Oracle Open World and JavaOne.
If Oracle can not bring the old JavaOne spirit and content back, they may not find many developers to pay +$1500 to attend a conference in the following years. Honestly I wouldn't if I didn't have a session.