Archive for: December 2012

Effort, control and stress in your projects!

In all projects there is stress. It is up to each of us, control it and reduce it. There are people who only know how to work under stress, and that, damages his/her health, it is scientific and is well known. What to do to reduce stress? This question answers itself with two questions: What level of enlightenment have you about the project you’re involved in? And as a consequence, how much do you think you can “control” the future?

The stress comes from the lack of control of the future, and this happens for 2 reasons: The first is lack of project planning in a clear way for all team members, along with the confidence of the leader who will not “persecute his team developing members” if they cant comply with the impossible tasks times! A well developed project plan, along with a risk plan is a relief for all stakeholders of the project. I think just reading this gives psychological relief and reduces stress!

The second reason is the balance between control and energy expended for such control. A few years ago someone showed me the following drawing:


In this picture, the circle in the center indicates what we control, and the energy we spend on that control. When we move away from the center (things which aren’t in our control, such as other people decisions and acts), the less control we have and we can only hope for influence, that will vanishes the more we move away from the center.

In the center we spent little energy to control things, like our decisions, but when we try to influence, or moving away from the center, we must spend much more energy, like trying to convince others for some decision or trying to control other’s things. If we try to influence things that are very far away from the center we have to spend a huge quantity of energy, raising our stress and causing damage to our health (body and mind).

small_394435153So if you are a project manager, and you really want to manage healthy your team so you can have a very successful project in every way, learn to manage well your energy and of your team, it will give you in a long run a successful personal, professional and social life. Let me say to you some Christian advice “love thy neighbor as thyself”.

If you are one of the team developers, you are not obliged to accept whatever the project manager gives to you, if there’s one thing I’ve learned is: it is harder to say “no”, and is easier to say “yes”, but it is the “no” that define your life. Do not be confrontational, present alternatives, discuss your point of view, if the project manager don’t accept it and the right its on your side, well probably the company is not for you!

This way of seeing things applies to all our life.

photo credit: via photopin cc

Android SDK Tips

Little simple things where I lost some time finding out the resolution when developing for Android.

Emulator with PANIC error:

PANIC: Could not open: C:\Users\

This error happens all the time in windows environment. The most cause is because your username has some non-english characters like “éáç…”, and Android SDK uses your home folder in the operating system as a default to create the emulators.

Possible solution:

make a copy of the avd folder and configure the ini file to point to the new folder.

  1. Go to the emulator folder (for instance: c:\users\usernamewithnonenglishlike-áéíç\.android\avd\)
  2. Copy the “avd” folder to another folder without non-english characters (c:\myAvds\…")
    1. Don’t remove the original
  3. In the original folder open the “init” file: (for instance: c:\users\usernamewithnonenglishlike-á\.android\avd\AVD_for_2_7in_QVGA.ini)
  4. Change the path value to the new folder:
    1. path=newFolderWithoutNonEnglishCharacters\avd\AVD_for_2_7in_QVGA.avd
  5. Start the emulator, it must work now!

PS: Another way is creating manually the AVD and place it in a custom folder:

android create avd -n myVirtualDevice -t 2 -p customfolder\avd

Associate the resource layout (xml file) with the Activity java class:

In the activity java file just add a line to link to the resource file.

Create your resource file or “design file” at res\layout\your_resource.xml

    1. use only lowercase characters combined with numbers and “_”
  1. In the Activity Java Class, in the “onCreate” method, use “setContentView(R.layout.your_resource) like the code below.
public void onCreate(Bundle savedInstanceState) {


        // Your xml resource file!



Can’t configure Android SDK in IntelliJ 12 when creating a new project

Intellij doesn’t have configured any jdk, so we must configure at least one!

  1. Create the project without the Android SDK configured.
  2. Add some jdk (1.5, 1.6, 1.7) in File->Project Structure
  3. Then choose Android SDK for your project!

Singleton Pattern without explicit “if” and initialization!

One of the most elegant features of Java are the anonymous initializers! They came in two flavors, static and instance. These kind of initializers are anonymous because they are run by the JVM, at “load byte code” time for static initializers, and at “construction time” for the instance initializer.

The Singleton pattern its very easy to implement, we just have to hide the default constructor (writing it as private) and create a way to call it, usually using a public static method which verifies with a local field if it has already created an instance or not. If so, then ignores the creation, else it creates the instance and returns it. With this, we have only one instance possible in all the application.

Well, with static initializer you don’t need to verify the construction of the object, lets give this job to the JVM at load time! The static anonymous block runs when the JVM loads the class, which is the perfect time to create the instance! After this initialization, when calling any method of this class we are certain the instance already exists and we don’t have to develop any “if” to verify that.

An example of a very simple singleton below.

public class Singleton {


    private static Singleton instance;


    // Initialized at JVM Load Time!

    static {

        instance = new Singleton();



    private Singleton() {}


    public Singleton instance() {

        return instance;



There are other ways to create the object without using the “if” (sometimes called lazy instantiation), like declaring the static field with an instance of the class:

private static Singleton instance = new Singleton;

but this solution doesn’t allowing me (in a elegant way) to run any other code at “load byte time”, so I really prefer the “static initializer way”.

Shared or Static – Visual Basic vs Java?

MP900386814 In Java there are 2 fundamental concepts that any developer should know: instances and classes. Class its the base of your code, your specification about an entity, like Account, Customer or Supplier. Instance its what you get after a “new ” (an object in the heap). So you have at maximum 1 class and N instances of that class.

Although a class its just the specification, in Java a class could have state and behavior like an instance, but with the condition “There could be only one” shared for all instances! Everything that are declared as static are executed(static blocks for instance)/initialized at class load time by the JVM, the rest (instances) are executed/initialized in runtime, after load time.

This word, static comes from very long time, since C, C++, C# and others, but Visual Basic uses other word “shared which somehow implies the behavior of the fields declared as static(java) or shared(visual basic) after a Class “is running”! After the JVM has loaded your class, every static(java) field are shared(visual basic) between all instances, so the question is:

What of these words captures better this behavior (of static) “static” vs “shared”?

So, although I really like a lot languages like C++, Java and C#, I must admit Visual Basic its somehow more expressive and more closely related with the true meaning of “shared” fields!

The not so ACID transaction properties

If you work with Database Servers you know that ACID its not implemented/active by default! And if you have it implemented you have a really poor performance on your database server!

Lets examine each one of these properties:

A = Atomicity

Definition by wikipedia: “Atomicity requires that each transaction is “all or nothing”: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes.


– “… and the database state is left unchanged“. Unless you configure your database server with ISOLATION LEVEL SERIALIZABLE this is not true. By default most SGBD are configured with Read Commited, with allows some changes like phantom reads.

C = Consistency

Definition by wikipedia: “The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including but not limited to constraintscascadestriggers, and any combination thereof.”

RIGHT for schema state, WRONG for value state (explained in atomicity above)

I = Isolation

Definition by wikipedia: “The isolation property ensures that the concurrent execution of transactions results in a system state that could have been obtained if transactions are executed serially, i.e. one after the other. Each transaction has to execute in total isolation i.e. if T1 and T2 are being executed concurrently then both of them should remain unaware of each other’s presence

WRONG! Only in dreams! its possible, yes, but in the way you encounter DEADLOCKS and Poor performance. If you want a performance database server you must drop the isolation to the lowest level possible! Its the price to pay for having fewer locks in the middle of your transactions.

D = Durability

Definition by wikipedia: “Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter).”

RIGHT! Well, I give this one, and I’m glad I could, what was a database server without it! 😉 However, actual high performant database servers have some kind of memory cache where there is a risk of loosing data, but, as far as my knowledge goes, it only happens in some NoSql databases… I hope…

What I dont like about Java Application Servers

I have a lot of experience with Java Application Servers, from Weblogic to jBoss 5,6,7 and Glassfish. I’m a Java and J2EE Trainer too. So, I’m not here to make an argument against the use of Java Application Servers, I use them every day, however I must say some things that I really dont understand (from a user/developer perspective) about Java Application Servers:

Why Java Application Servers don’t isolate a deployed application? How many times are you deploying an application and you have to configure, customize, remove jars, add another’s jars, create additional files just because the application server already has some of the jars you use in your application? For instance, in my team, we are migrating sites and web services from weblogic and its a nightmare, jboss already have some of the jars, and at deployment time throws exceptions that are not so easy to understand at first sight. (like logging jars – in our case slf4g with logback) If an application could be isolated like a file system application its isolated in an operating system like linux or MAC OS these problems dont even existed! I just wanted to deploy my application with the jars I need, and don’t think about what jars the application already have.

I have experienced deploying applications in Microsoft IIS and in Java application servers. Using Microsoft Servers its much more easy than using similar java products. Usually, when starting and developing Microsoft products I spend 80% of the time focused in developing and  testing the product, and the other 20% finishing configuring and deployment. With Java Application Servers, first you must study the application server, know about several XML files with specific names, to configure datasources, jms queues, etc. Then you hope that exists some eclipse plugin or netbeans plugin that really works. I have experienced plugins for weblogic and jboss but sometimes when you deploy an application its just a view for your eyes, the application doesnt get really deployed to the application server, so I have to go to the localhost website, and deploy it. The inverse its also true. So, 80% configuring and preparing, learning and training and the rest 20% of time developing.

Don’t get me wrong, my experience its divided between these two worlds (Microsoft and Java), I like Java, after all the configuration its done everything will work as expected, but its a really tough job to put everything to work at first in Java Application Servers World!

Do you know ForkJoinPool Java 7?

Java 7 brings and/or improves thread management to handle heavy and complex tasks.

You can use threads, ExecutorServices and this: ForkJoinPool.

There is an increasing developers movement to coding in a functional state of mind, using Ruby, Scala, Clojure and other similar programming languages. Java 8 will follow this path too, with lambdas. If you are not using a functional approach in programming, I invite you to do so, its a very different way of thinking where the “divide to conquer” its a must!

In Java 7 you can use this way of thinking to resolve complicated problems, the ones where its necessary to think recursively where you can split a heavy task in simples ones, like when you are sorting a big list using quick sort, transverse a file system including every folder and file, etc. These are problems that seems complicated at first, but thinking recursively it turns out to be very simple tasks.

The main algorithm to implement a recursively task its always something like:

  1. What is the stop condition? (Here you return a “real” value)
  2. Call the method recursively calling it itself with some sort of improvement in the parameters, like if you are in a for.. loop.

For instance, long factorial(long n)

  1. stop condition: if( n <= 1) return 1;
  2. calling recursively like a loop: return n * factorial(n-1)

Has you know by now, the factorial(n-1) will have to stop in the future, because n-1 its decreasing until it reaches n <= 1, and then n * will be really calculated!

In Java 7 you have a Class ForkJoinPool that automatically handle threads to execute the smaller tasks like the above: n and factorial(n-1).

The recursively method will always be the protected Long compute(), which must be an @override because the class will extend: RecursiveTask, where will be the return value of the compute method!

In the example below, I have implemented a very simple example to calculate the sum between 2 numbers, using recursive smaller tasks.

I start with some range, if the stop condition (end – start), its below 10, then I return the sum between the start and end, otherwise I split the range in 2 parts, the first one executes concurrently (using fork witch puts the thread in the ForkJoinPool) the second half of (end – start) and the first one computes the sum delegating its execution to the compute method (itself!), or the other half.

Observe the last return: return t2.compute() + t1.join(); where the second thread calls the compute and then waits for the fork previously executed as the first thread!

import java.util.concurrent.ForkJoinPool;

import java.util.concurrent.RecursiveTask;


 * Calculates a Big Sum recursively using RecursiveTask and ForkJoinPool

 * @author JoseCruz



class BigSUM extends RecursiveTask {

    private final long start;

    private final long end;


    BigSUM(long s, long e) {


        this.start = s;

        this.end = e;



    // compute sum


    protected Long compute() {


        // Is it is small enough just for one thread I will handle it!

        if(end - start < 10) {


            long localSoma = 0;

            for(long s = start; s <= end; s++) {

                localSoma += s;



            // The main point of return for the recursive "loop"

            return localSoma;



        // Lets split the effort!

        BigSUM t1 = new BigSUM(start, (end-start)/2+start);

        BigSUM t2 = new BigSUM((end-start)/2+start+1, end);

        // like cloning..!



        return t2.compute() + t1.join();



    public static void main(String...args) {


        // You can get the available processores and use it to initialize the ForkJoinPool

        int processors = Runtime.getRuntime().availableProcessors();

        ForkJoinPool jfp = new ForkJoinPool(processors);


        // a big number...

        BigSUM t = new BigSUM(0, 10_000_000L);


        // calculate the sum using lots of threads

        Long result = jfp.invoke(t);


        System.out.println("And the sum is " + result);




I think the code its very clear and simple, if you have questions or comments don’t hesitate to post them!

This Is a very useful tool to resolve complex problems that I really invite you to learn and use it!

Gamification in the family

One of these days I went out to lunch with my family. My daughter does not like to eat, it is complicated to sit an entire meal just to eat. But there’s something she likes, games, play them on my wife’s iPad, on my iPhone, Laptop, etc.. Why not apply gamification with my daughter, since I am a gamification evangelist? She was eating steak with chips and a juice that she likes a lot. The juice was already halfway. So I proposed the following game: For every 5 chips and 3 pieces of steak she could drink a sip of juice. It worked, ate almost everything!
The meat and potatoes were the points, my daughter was the player whose behavior I wanted to change, the juice was the package of rewards!
One of these days I’ll play another … several meals completed, and give her a “Badge” (probably a Winx doll or other toy that she can show to her friends as a prize!)

Bad Behavior has blocked 93 access attempts in the last 7 days.

Hyper Smash