Tag: advanced

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

Java Blocks–Advanced–Part 1

Following a previous post I will deep into the discussion about anonymous blocks mixed with static variables.

Lets see a simple example, and then we will complicate a little bit.

public class TestStaticInitializer {

{
System.out.println(“block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“block 3”);
}

}

You can observe that:
– There is a static variable ‘x’ that its initialized calling a static method.
– There are 3 anonymous blocks.
– The constructor calls the static variable.

The main method references the class.

At first sight we can think the anonymous blocks are called in sequence, which it’s true. Although if there is a static variable initialized in anyway, this initialization runs before any anonymous block.(Why? Because a class is loaded in 2 phases: load class, run class. At load the JVM after some verification, initialized every static variable and runs any static anonymous initializer, and only after runs the class, or our instance.)

You can observe this by looking to the execution output:

static initialization of x
static main block before calling the constructor
block 1
block 2
block 3
static x = 5
static main block after constructor

The anonynous blocks are executed by sequence, but the initialization variable “static initialization of x” runs first, although its declaration is after “block 2”.

The sequence is:

1 – Initialize the static variable x

2 – run main method

3 – initialize the class (because I’m calling the constructor)

4 – run anonymous blocks

5 – runs the constructor (only after the static blocks)

6 – runs the other “main” statements.

You must be wondering why I underlined “The main method references the class” above.

Lets see if I remove (I will just comment it) the call to the class constructor.

public class TestStaticInitializer {

{
System.out.println(“static block 1”);
}

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“static block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
}

{
System.out.println(“static block 3”);
}

}

and the output is:

static initialization of x
static main block before calling the constructor
static main block after constructor

Well, where are the anonymous blocks initializers? Thet are not needed! We haven’t crated any instance of the class, so the JVM just considered the static stuff!

And if a static block references the static variable x?

public class TestStaticInitializer {

{
System.out.println(“block 1”);
x = 7;
System.out.println(“block 1 after x = 7”);
    }

public TestStaticInitializer() {
System.out.println(“static x = ” + x);
}

private static int staticInitialization() {

System.out.println(“static initialization of x”);

return 5;
}

{
System.out.println(“block 2”);
}

static int x = staticInitialization();

public static void main(String[] args) {

System.out.println(“static main block before calling the constructor”);

//TestStaticInitializer test = new TestStaticInitializer();

System.out.println(“static main block after constructor”);
System.out.println(“x = ” + x);
    }

{
System.out.println(“block 3”);
}

}

The output:

static initialization of x
static main block before calling the constructor
static main block after constructor
x = 5

The initialization of “x = 7” in the first anonymous block is simple ignored, because the code was never ran!

static int x;// = staticInitialization();

The output will show you “x = 0”.

I hope this post will help you understand the mix between anonymous and static initialization blocks. In a future post I will bring some class hierarchy to this discussion.

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

Hyper Smash