Archive for: May 2013

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

iPad business applications I use–Kindle

I have a lot of printed books, they give me a sense of “paid for something that I really have”. However, I have great technical books, great because their content and great because they are big, with lots of interesting pages. So, what’s the issue here? Carrying books every day in paper its heavy, I can’t put them in my pocket, everyone knows what I’m reading at work, in the train, subway, etc., probably at the end of the day I will let the book on my desk at work, at middle of the day I will remember that at home I have a book that could be very useful at my job.. But it is at my home… well… the ideal was carrying all with me but without the volume!

kindleAgainst my will, at first, I tried to buy digital books. I have an iPad and an iPhone too, which I carry with me most of the time. My books are all inside these too gadgets! Well, they are at Amazon cloud, but I have an offline copy in them. So, when I’m going to work I can choose any book to read, or when at work I can consult any of them. I carry all the books I have, but without the heavy and volume issues!

So, why Kindle? Well, you can buy or rent books. The reading it’s great. You can have your book in 5 different places. Kindle remembers the where you stopped reading and allows you to continue later in any device! It’s very easy to buy a book at amazon.com and after some seconds the books it’s in your iPad (well, could be a financial problem so much easiness!).

I still miss, sometimes, the feeling of the paper in my hands, but the advantages of having in digital format allied with my computer science job, it’s a tradeoff I’m glad to have done.

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 )

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

Hyper Smash