Tag: java

Tip: Java 8 Streams flatmap map lists

A little example, I had to develop as a teaching use case, of how to take a map with Integer keys and values with a List as value and find a specific value in any List in the whole map using Java Streams.

boolean b1 returns true because the element exists
boolean b2 is the response to an element that doesn’t exist

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

            System.out.println(“.”);                           

    }

}

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

How to do it?

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

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

Using Double Brace Initialization

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

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:

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.

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

 

 

 

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

 

  • 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:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html

 

  • 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!

 

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:

 

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.











 

 

 

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.

 

 

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:

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!

 

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

Hyper Smash