Tag: java

Managers, it is always about people!

types-of-exerciseAfter years of developing, team leader and project management experience I realized that all good decisions, even the technical ones must include all the people. Well, “everybody” knows this, every project manager, team leader, manager,etc. Really?

Lets focus on the team developers.

Imagine you have a project to develop, a software product. You have a team leader and some developers that you will assign to the project. You want to use the new technologies like HTML5, JavaScript and lets add Java, the software product will be an Android app.

The typical decision will be something like this:

1) I have developers and a senior developer team leader

2) They all know Java

3) They all know about HTML5 and JavaScript, because “everybody” knows about HTML and JavaScript. Right?

4) They all know about java and that is the language of the android, and know what is an Android phone, it will be a challenge!

Lets remake the decision looking from outside:

1) You have developers and at least one of them it’s a Senior.

– Great!

2) They all know Java.

– The problem starts here. What they know about Java? The language and some algorithms (even with some years of experience), or they understand how to apply Java in the context of mobile Applications? If this is the first time they will develop mobile applications, they don’t understand the architecture of these applications, how to develop the components, the events, actions, how the hardware responds and send events to the application. The thing here its not the details of the mobile android development, it’s the lack of “mind set” the team will need before start to code, and the result will be most certain a bad quality product, who will need a lot of fixes and rebuilding. (been there)

3) Yes, every developer who have developed before web applications knows about HTML and JavaScript, everybody knows WHAT IS, and the syntax and some tricks, but few, very few understands the JavaScript paradigm and good HTML. Be aware of this before anyone tells that he knows about this subjects. It was only in the least 2-3 years that the JavaScript boom has started seriously, and Senior JavaScript programmers are a very small team. Before this language was only used for events in the HTML, now we have frameworks developed in JavaScript, we even can use JavaScript to create servers like “Node.js”!

4) It will be a challenge!

– No, it will be a disaster for the company and/or for the customers! The lack of know how in the middle of the project will arise and show all the architecture problems not prevented in the analysis phase or by the Senior. And here you will have 2 options: Remake the whole product from the start, which sometimes its not a bad idea (only for project managers), because the team already acquired the know how and know how to develop in a better way and know what to develop. Or fix the architecture, and this for me it’s the real challenge and here I thing “It will be a challenge” makes all sense! Its like trying to fix an already built house into other blueprint, good luck! (you will see its better to destroy and build again)

What’s my point, here?

This was just a simple example, to show that the most common way of thinking can lead to big problems, which by the way are always happening.

Before a great decision to be made in the software industry, first take in consideration the people you will choose. They are people with a specific know how and mind set, and to change that it takes time and it is a process you must consider. You can say, you will put them all in training classes. Great, but don’t expect that some dozen hours will create a miracle and prepare them for big projects. Training just gives you an overview sometimes shallow, other times deep, but after the training the people must play for some time before entering the “competition”. You can see this in sports teams. They are professionals, they play for many years, but when something changes, like others players, tactics (projects), coacher (team leader) they need to practice before the real competition to be successful, or you will ear from supporters “they had no time to practice that’s why they are playing so bad”. Probably you say the same about your sports team. Remember those words in your company and your team.

Once someone said, that 80% of the quality of a product comes from management, not the workers, because they need conditions to develop a quality product or project. These conditions include human resources management, understanding human behavior and acting accordingly!

What to do?

I will not give you a magical solution, from years of experience as a developer, trainer, team leader, architect and project manager, I can help you to take a decision involving all these variables, but as a manager, project manger or whatever manager you must open space for your developers talk about the difficulties and frustrations they have, and not throwing a “it’s a challenge for you guys” like a magic sentence that in the future will bring its fruits (demotivation and consequently quitting), and I will not talk here how much it costs to bring a new member to a team (think about a new player in a team, even expensive he need time paid by the sports team to adjust to the new environment).

If you are a developer, be more open to your managers, and ask them time to practice, to develop small “challenges” besides the training and before starting a big project, it will give you know how, confidence and experience for a bigger project. Your company its not wasting money its an investment. I think it will cost more to rebuild or fix a bad product than to spend time before doing some “virtual work” and then do the real work. A soccer team plays 1-2 times a week, and receive money from the public, but during the week they spend money training.

An Infinite loop in Java, but not to everyone!

One of the things, after all these years, that keeps me fascinated about coding, it’s finding curiosities in a few lines of code that make me think for a while!

public class JavaPearls {

    public static void main(String… args){

        Integer a = new Integer(10);

        Integer b = new Integer(10);

        for(;a<=b && b <= a && a != b;)




A bet you don’t know about these in Java!

Double Brace Initialization

Probably a lot of time you whish to initialize a collection in Java with default values at construction time, but without doing the sequence stuff like this one (too many statements):

// Initialize a cars collection
List cars = new ArrayList<>();

// call the method

How to do it?

Using a static method asList (probably you know about this one!)

Functional style, fewer lines, very precise, and clear!

// Initialize the collection (fewer statements!)
List cars = new ArrayList<>(Arrays.asList("Volvo", "BMW", "Ferrari"));

// call the method

Using Double Brace Initialization

If you think a little about it you will see nothing knew, but may surprise you this way of initialization!

// Initialize the collection
List cars = new ArrayList(){{

// Call the method

Is this a hidden feature in Java? No!

If you know something about anonymous classes and anonymous constructors, nothing here is new!

The first “{“ is creating an anonymous subclass of ArrayList, and the second “{“ is used to create an anonymous constructor.

Let me put the code in another way:

// The collection creation!
trickList cars = new ArrayList()
        // The anonymous subclass 
            // The anonymous constructor

// The method call

More clear now?

Java has some hidden gems that they deserve to be found!

del.icio.us Tags: ,
Technorati Tags: ,
43 Things Tags: ,

Five advanced Java Synchronizers you probably don’t know

Besides the common synchronize which is based in the lock bit that every Java object has, you have more sophisticated synchronizers in java, such as:

  • Semaphore – Use the concept of a permit to indicate a max number of allowed threads in a place. When you use the value 1, the behavior its similar to synchronize, also called binary semaphore. There is however a big difference here, you acquire a permit on the semaphore, not a locking object, its just a variable to count when a thread acquires a permit and when a thread releases a permit, some kind of a counter. The only thing you really have are threads locking until a permit be available. In the example below, we define 3 as the number of permits, so after 3 acquires the 4 thread will wait for a release before continue its execution.
// Define the semaphore to control 3 permits. 
// 3 Threads can acquire the mySemaphore 
Semaphore mySemaphore = new Semaphore(3, true);

// 3 threads can execute this line of code. The 4 thread must wait for a release

// .. somewhere in the code a thread releases the mySemaphore, 
// and now the next waiting thread can acquire
    • CountDownLatch – Initialize this class with a number (to countdown), and when reaches 0 the thread waiting unblocks and follows its way. (After the await the latch cannot be reused)

// Initializes a countdown starting from 3
CountDownLatch latch = new CountDownLatch(3);

// ... other threads are running... 

// Some thread blocks and waits for the latch countdown 
// to reach "0"

// ... code, methods, other objects... etc...

// ... at some place the OTHER threads do the countdown, 
// decrementing the latch.. when it reachs 0 
// the blocked thread with the "await()" follows its way

  • CyclicBarrier  – This class behaves somehow as the inverse of the CountDownLatch. After N await() the threads blocked can follow their way. (A CyclicBarrier can be reused)
// 3 threads must await before can unblock
CyclicBarrier barrier = new CyclicBarrier(3);

// threads they block here until the 3 is reached

// after 3 threads in await this code will run!
System.out.println("Thank you to the 3 friends who awaited for me!”);

  • Phaser – Very complex synchronizer, a mix of CountDownLatch and CyclicBarrier, with lots of customized options. If you need a behavior similar to 2 previous synchronizers but they were not enough you want to deep into this one. It behaves like a CyclicBarrier but you can register a set of threads and at any time deregister, achieving a level of customization not possible with the other synchronizers. Think about the need to wait for threads to arrive before you can continue or start another set of tasks. More information about this at Oracle website:


void runTasks(List tasks) {
   // Initialize the phaser, "1" to register self
   final Phaser phaser = new Phaser(1); 
   // create and start threads
   for (final Runnable task : tasks) {

     // register here
     new Thread() {
       public void run() {

         // await all creation

   // allow threads to start and deregister self

  • Exchanger – The best explanation comes from Oracle doc itself: “A synchronization point at which threads can pair and swap elements within pairs”. One thread wants to send information to other thread and blocks awaiting to send the data, and in EXCHANGE receives what the other thread wants to send too! This behavior happens to both sides!
// Create the exchanger. 
// We choose String as the data datatype 
Exchanger ex = new Exchanger();

// .... Somewhere at Thread 1, 

// I will block until I can send str1 to Thread 2, and receive a value too!
String str1 = "value to send from Thread 1 to Thread 2";
String valueReturnedFromThread2 = ex.exchange(str1);

// ... Somewhere at Thread 2,

// I will block until I can send str2 to Thread 1
// I will receive a value from Thread 1 too!
String str2 = "value to send to Thread 1 from Thread 2";
String valueReturnedFromThread1 = ex.exchange(str2);

photo credit: My Buffo via photopin cc

Do you have architects or senior developers?

Why there are very few good Java Architects?

Well, most people will say to me, that this isn’t true, they have Java Architects in their team. I believe, but most of them are Senior Programming Developers with some experience, but not real Architects! Sorry.

As a Java and J2EE trainer I have a lots of students learning Java, Java Programming, EJB, Servlets, JSF, JSP, Web Container, JPS, ORM, along the year. But in the last 2 years I have taught only one time a course about IT Architectures! Even people with 3-5 years of experience they became to my classes learning about Java Programming, some of them team leaders, “experienced” team leaders! After some questions about patterns, cohesion, density, coupling, etc.… 99% of them they just… ahhnn?? That’s when I know, that most of the team leaders are just Senior Developers!

modern-architecture-2A good final Java Product its about thinking in commercial aspects like: audience, final stakeholders, customers, commercial sensibility; and technical like: Load Balancing, Patterns, the 3 dimension of an architecture, density, cohesion, coupling, security, layers, tiers (which its different than layers, by the way), scaling, sessions, performance, etc.. Not only programming! Programming are the bricks, it doesn’t matter how knowing how to put bricks if they aren’t in the right place and in the right way, with a specific commercial goal in mind!
Poor decisions at the start of development will reflect in a weak product which probably will need maintenance in the future! Then the company will train or consult real Java Architects, or sometimes they just keep pushing the “Senior Developers” to try to increase the quality of the product…

So, if you are a company developing Java Products, besides people know about Java, train them in topics like:

– Patterns

– Architectures

These topics are not about Java, but they really improve the quality and the performance of any product development, including Java! And then you will have better Senior Developers, with some commercial sensibility (yes, architectures it’s about commercial sensibility too, one of the most important aspects in most cases), and after a while you probably have Java Architects, and you will have a great team to develop great products! (Well, there are the human factor to consider here.. .but that’s another story )

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!

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!

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

Hyper Smash