Singleton Pattern Example

This is a thread safe, lazy load singleton example:

public class Singleton {
    private Singleton() { // make it private to prevent instantiation from outside
        // some code for the constructor
    }

    private static class InsHolder { // Once getInstance() being called, this class will be loaded (Lazy)
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return InsHolder.INSTANCE;
    }
}

The down side of the above code is you can’t throw exceptions on constructor.

Advertisements

Lambda Expression Examples

Original code to loop through the List<Element> elements:

for(Element e: elements){
// do something with e
}

Use of -> (in case there is no need to declare the type):

elements.forEach(e -> {
// do something with e
});

Use of :: (in case you already have a method to deal, and only deal with e):

elements.forEach(instance::method);

Note: The instance can be a reference, a new statement, or this keyword. If the method is static, the first part of :: can also be the class name.

In some other cases, there might be no parameter, or more than one parameters.

If the interface of the call parameter only needs one parameter:

void call(new Interface(){
    void execute(Object o){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call(e -> { // e represents Object o on above code stub
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call(e -> statement);

Using method delegation:

call(instance::method);
// void method(Object o){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

If the interface of the call parameter needs no parameter:

void call(new Interface(){
    void execute(){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call(() -> { // () is used to indicate there's no parameter
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call(() -> statement);

Using method delegation:

call(instance::method);
// void method(){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

If the interface of the call parameter only needs two or more parameters:

void call(new Interface(){
    void execute(Object o1, Object o2){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call((e1, e2) -> { // (e1, e2) represents o1 and o2 on above code stub
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call((e1, e2) -> statement);

Using method delegation:

call(instance::method);
// void method(Object o1, Object o2){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

Function interface

The only way to use lambda express without a method call is to use functional interface (with @FunctionalInterface annotation). E.g. Function interface.

@FunctionalInterface
public interface Function<T, R> {...}  // T: input type R: return/result type

An example of using Functional interface:

Function<Long, Long> square = x -> x * x;

or

Function<Long, Long> square = instance::method;
// Long method(Long x){return x*x;}

Wrong:

NoneFunctionalClass<Long, Long> square = instance::method; // can not pass compilation

An example of method level generic type usage

This example shows how to use generic type in a design pattern.
The following code will structure a process to separate logic code from routine tasks.

First, create an interface and an unimplemented method, which will be called in Executor class:

public interface Executable<T> { T execute(); }

Second, code the routine tasks, and insert the logic to be execute:

public class Executor {
    public <T> T process(Executable<T> e) {
        //pre execution. e.g.: start transaction
        T t = e.execute();
        //post execution. e.g.: commit transaction, close resource etc.
        return t;
    }
}

Finally, call the Executor to process your task, and code the business logic:

public class Caller {
    public static void main(String args[]) {
        DeterminedType t = new Executor().process(() -> {
            //code to deal with the business logic
            return result; //the type of the result returning here will determine the type of t
        });
    }
}

A summary of Generic Type

There are 2 levels of Generic Type: class level & method level.

Class Level:

public class ExampleClass<T>{}

Method Level:

public <T> ReturnType exampleMethod(ParameterType parameter){return null;}

Generic Type works very much like any kind of variables. You need to declare them before using. The above Generic Type place holders <T> are the only places you can declare generic types. It means any “generic types” appear else where are not declarations, but references of <T>.

For example:
public class ExampleClass<T> extends SuperClass<T>{}
The first <T> is declaration, and the second is just a reference. As an effect, you can’t have something like this:

Wrong:

public class ExampleClass<T> extends SuperClass<T extends Type>{}

because if you want to bound a type parameter on a generic type, you have to do it while it’s declared, like this:

Right:

public class ExampleClass<T extends Type> extends SuperClass<T>{}

Another trick with this example is, if <T> of SuperClass is bounded to a type in its own definition, the <T> of ExampleClass must narrow its type to fit the <T> of SuperClass.

Wrong:

public class SuperClass<T extends Type>{}
public class ExampleClass<T> extends SuperClass<T>{}

Right:

public class SuperClass<T extends Type>{}
public class ExampleClass<T extends Type> extends SuperClass<T>{}

For the ExampleClass<T extends Type>, T can also extend from a subclass of Type since subclass has an “is” relationship to its parent class.

super

super is opposite to extends, and is commonly used with consumer pattern.

Wildcard extends:

List<? extends T>

It indicates each element in the list is an instanceof T.

Wildcard super:

List<? super T>

It means the type of each element equals the type of T, or the types of its parents.

*Search PECS (Producer Extends Consumer Super) for details about its usage.

 

 

 

Unzip JDK from installation package

  1. Create destination folder where you can RWX (e.g. C:\jdk8)
  2. Download jdk exe from Oracle (e.g. jdk-8u72-windows-x64.exe)
  3. Unzip the tools.zip found inside it into the destination folder
  4. Open cmd.exe, run:
cd C:\jdk8
for /r %x in (*.pack) do .\bin\unpack200 -r "%x" "%~dx%~px%~nx.jar"

This solution works for JDK 8 too, without the Admin authority.