Category: Architecture & Developing

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(“.”);                           

    }

}

Great Technical Books I have read in the last months

transferirAs a software architect I must have a broad knowledge of several subjects so I can have several tools in my brain to create the better solutions with the right tools. I’ve read (and still reading!) a lot of books, so this post will show some of my last readings with some comment on each of the books.

In future posts I will show other interesting books, sometimes not directly related with software but they gave me another way of thinking about systems, patterns and algorithms that helped me to be a better professional, as a technician and leader whenever necessary.

Hope it can be helpful to your tech and soft improvement in the software industry.

If you know others books you have read who can enrich my knowledge, I will appreciate your comment!

How many methods you have in your classes with: Logging, transaction, validation, exception management? How about remove the code from those methods, write it in another class(es) and add just attributes (or java annotations) and surprise! Your code its so much cleaned! This book has improved the quality of my code, architecture and thinking about applications!
Dependency Injection its about building great software architectures. Its about building software like a house, its about decoupling and loosely couple. Its about building testable software, its about software with quality.
A great book about NoSql! Not too deep, but with the enough information to understand the NoSql world. Even with years in database systems I’ve learned new ways of thinking in this book.
The reference for programming windows, now for windows 8. You can’t go wrong with this book.
You want to know about SCRUM, agile and how it works, this is a very good book to start.
Best book for android development.
I know C, C# and C++. With this book from these guys, I added Objective C to the Cs languages list!
Great book about iOS development. Starts from the basis and then develops some applications and of course your knowledge.

Learning Node.Js – Using MySql

nodejs-380x300So much buzz about Node.Js I had to give it a try, and let me tell you, I was impressed by the fast results and applicability of this framework (I know… there is a lot of debate about what Node.Js is).

I will not introduce Node.Js or give a tutorial about it, you must know a little about JavaScript and know about request, response and HTTP codes.

This example shows how easy is to develop a http Node.Js server and I can you start using it to access MySql databases with just a few lines of code.

Preparation:

1) Download and install Node.Js (its very simple, download and unzip, that’s it!). http://nodejs.org/download/

2) Install the MySql package to access a MySql database.

I’ve used Windows for my learning but it will work for sure in Linux and other platforms.

Just write “npm install mysql”, and the rest speaks for itself. (npm it’s a package manager easily install “add ons” to Node.Js)

D:\node>npm install mysql
npm http GET
https://registry.npmjs.org/mysql
npm http 304 https://registry.npmjs.org/mysql
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/require-all/0.0.3
npm http 304 https://registry.npmjs.org/bignumber.js/1.0.1
npm http GET https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
npm http 200 https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
mysql@2.0.0-alpha8 node_modules\mysql
├── require-all@0.0.3
└── bignumber.js@1.0.1

3) Now we are ready to develop our first web server in JavaScript (don’t worry about being JavaScript, it is written in C/C++ and its very fast. I’ve made simple tests with 500 request per second on my laptop without any flaw).

var http = require('http');
var mysql = require('mysql');

// Create a connection to MySql Server and Database
var connection = mysql.createConnection({
  host : '101.129.108.171',
  port : 3306,
  database: 'mb',
  user : 'user',
  password : 'pass'
});

// Create a simple Web Server to respond to requests
http.createServer(function(req, res){

    // RECEIVED A REQUEST!

    // for this example respond with a HTTP 200 OK
    res.writeHeader(200);

    res.write('Connect to mySql\n');

    // Connect to mySql (if there is an erro, report it and terminate de request)
    connection.connect(function(err){
        if(err != null) {
            res.end('Error connecting to mysql:' + err+'\n');
        }
    });


      // Query the database to some data 
    connection.query("SELECT * from mb.g WHERE ref = '806787088'", function(err, rows){

        // There was a error or not?
        if(err != null) {
            res.end("Query error:" + err);
        } else {
            // Shows the result on console window
            console.log(rows[0]);
            res.end("Success!");
        }

        // Close connection
        connection.end();
    });


// The server will be listen on port 8080 
}).listen(8080);

4) Open a command prompt (console) window and run node for this JavaScript:

D:\node>node testaMySql.js

5) Use a browser or use curl to test it! (If you use curl you simple open another console window)

D:\node>\tools\curl.exe http://localhost:8080

6) And you will see the output in the 2 console windows:

The console output goes to windows which started node. The res calls in the JavaScript goes to the browser or the console running the curl.

This is just a start with some “tutorial” example to access a mysql database. Of course you can increase the quality of the code and implement the web server to listen as a  “REST”/HTTP solution.

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

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<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ferrari");

// call the method
someMethod(cars);

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
someMethod(cars);

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(){{
            add("Volvo");
            add("BMW");
            add("Ferrari");
        }};

// Call the method
someMethod(cars);

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
            {
                add("Volvo");
                add("BMW");
                add("Ferrari");
            }
        };

// The method call
someMethod(cars);

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
mySemaphore.acquire();

// .. somewhere in the code a thread releases the mySemaphore, 
// and now the next waiting thread can acquire
mySemaphore.release();
    • 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"
latch.await();

// ... 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
latch.countDown();

  • 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
barrier.await();

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

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

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
     phaser.register();
     new Thread() {
       public void run() {

         // await all creation
         phaser.arriveAndAwaitAdvance(); 
         task.run();
       }
     }.start();
   }

   // allow threads to start and deregister self
   phaser.arriveAndDeregister();
 }

  • 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

NDepend – You must have this tool!

I’m a .NET developer since v1.0 at 2002, and as you may guess, I’ve used a lot of tools to help me doing my job. How many times you realize that you are always doing the same thing over and over, in the same way, and sometimes you don’t even notice that you are letting some “little” bugs or “little” bad practices that in the long run will damage your code? And, how about projects with lots of assemblies, methods, complex behaviors, is this familiar to you? If it is, you want to check this tool NDepend

The first thing you probably note it’s the name, which lead us to think that this tool its about dependencies between components, assemblies, methods. Well, its true! But its much more than that! How many of us don’t need to visualize the dependencies from all angles in our project? How much do you value seeing the relations between your classes, assemblies, methods? How great its to know which method it’s the more complex, or more used, or more critical? Probably this “.net method” should be the more unit tested and optimized! In a team, a tool like this has great value, either for developers either for team leaders who want to know how the technical aspects of the project are going.

But this tool, its not only about dependencies, its about code complexity, metrics and very good warnings and advices to improve your code quality, too. In some tests I’ve made with this tool in one of my projects, I discovered that some of my code should be improved (almost saying fixed!), NDepend has show where there was some source code problems and why they were problems! I’m learning from this tool, besides my senior professional experience as a team leader, developer and Certified Trainer!

In NDepend you will find a lot of interactive visual graphs, matrix, trees of your code and its relationships, but besides the visual features of this tool, which are great, you have access to an advanced tool CQLinq(Code Query Linq) which allows you to build Linq queries to query YOUR CODE! Yes, querying your code!

I think it’s a beautiful feature, and a pertinent add-on to any tool which aspires to analyze code.

An example:

from m in Application.Methods  
where m.NbLinesOfCode >  30  && m.IsPublic 
select m

A Linq query to return all my public methods with more than 30 lines of code!

You can use all the Linq operators, such as Take, Except, and have access to a very rich API to query your code by a lot of different metrics, such as:

What are the 10 most complex methods?

(from m in Methods  
orderby m.CyclomaticComplexity 
select new { m, m.CyclomaticComplexity }).Take(10)

As a first experience with this tool, I was very impressed, it’s a very productive tool, improves the quality of my code and of my team developers too. This tools its used by a lot of great companies like: ThoughtWorks, Microsoft, HP, Siemens, Google, Redgate and hundreds of others, they are not wrong about choosing it!

I’ will keep exploring this tool for my projects, my first impressions were great, so, why stop? If you are a professional developer I think you should give yourself an opportunity to improve the quality of your projects trying this wonderful tool! You can use it as either a Visual Studio Extension or as an Application outside Visual Studio.

For now I’m really enjoying what I have seen so far. In the future, I will certainly dig more deeply in specific features of this tool and post about my experiences,

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

        super.onCreate(savedInstanceState);


        // Your xml resource file!

        setContentView(R.layout.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.

WRONG!

– “… 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…

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

Hyper Smash