Bill Pugh: Initialization-on-demand singleton in Java

Singleton
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Initialization-on-demand singleton by Bill Pugh
Its one of the concrete way of creating singleton class in Java. We will understand it with example.

Source code
/**
 * Example: Singleton by Bill Pugh.
 *
 * @author javaQuery
 * @date 24th July, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SingletonBillPugh {

    /* private constructor */
    private SingletonBillPugh() {
    }

    /* static inner class */
    private static class LazyHolder{
        private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
    }
    
    /* get instance of SingletonBillPugh */
    public static SingletonBillPugh getInstance(){
        return LazyHolder.INSTANCE;
    }
}
Explanation
Now lets understand why its Initialization-on-demand (Initialize only when we call getInstance() method).

Java Language Specification
12.4.1 When Initialization Occurs (https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.1)
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

12.4.1.1: T is a class and an instance of T is created.
12.4.1.2: A static method declared by T is invoked.
12.4.1.3: A static field declared by T is assigned.
...
When class SingletonBillPugh is loaded by JVM, the class follows initialization process specified in Java Language Specification(12.4.1). Since the class does not have any static variables to initialize(12.4.1.3) the initialization completed.

What happen to class LazyHolder?
According to Java Language Specification (8.1.3) for inner class whose declaration does not occur in a static context of SingletonBillPugh. Inner class LazyHolder is not initialized until it it executed.

Java Language Specification
8.1.3. Inner Classes and Enclosing Instances (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.3)

When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing type declaration, the variable of the corresponding lexically enclosing instance is used.

What happen to method getInstance?
According to 12.4.1.2 A static method declared by T is invoked(called).


12.4.2. Detailed Initialization Procedure (https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2)
In first paragraph "Java Virtual Machine is responsible for taking care of synchronization and recursive initialization"
So when class SingletonBillPugh is initializing through LazyHolder, no other thread can initialize class until previous initialization of class SingletonBillPugh finish. And we marked variable INSTANCE final so other initialization won't happen. SingletonBillPugh class is completely singleton when using Bill Pugh singleton pattern.


Apache HttpPut Example

Apache HttpPut

Following excerpt shows how you can make PUT request using org.apache.http.client.methods.HttpPut.

Source code (HttpPutExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpPut.
 *
 * @author javaQuery
 * @date 26th January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpPutExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare put request */
        HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
        /* Add headers to get request */
        httpPut.addHeader("Authorization", "value");

        /* Prepare StringEntity from JSON */
        StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
        /* Body of request */
        httpPut.setEntity(jsonData);
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpPut, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Related
Apache HttpGet Example
Apache HttpPost Example
Apache HttpDelete Example

Apache HttpDelete Example

Apache HttpDelete

Following excerpt shows how you can make DELETE request using org.apache.http.client.methods.HttpDelete.

Source code (HttpDeleteExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpDelete.
 *
 * @author javaQuery
 * @date 26th January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpDeleteExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare delete request */
        HttpDelete httpDelete = new HttpDelete("http://www.example.com/api/customer");
        /* Add headers to get request */
        httpDelete.addHeader("Authorization", "value");

        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpDelete, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Related
Apache HttpGet Example
Apache HttpPost Example

Apache HttpPost Example

Apache HttpPost

Following excerpt shows how you can make POST request using org.apache.http.client.methods.HttpPost.

Source code (HttpPostExample.java)
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpPost.
 * @author javaQuery
 * @date 23rd January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpPostExample {
    public static void main(String[] args) throws UnsupportedEncodingException {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare POST request */
        HttpPost httpPost = new HttpPost("http://www.example.com/api/customer");
        /* Add headers to POST request */
        httpPost.addHeader("Authorization", "value");
        
        /* Prepare StringEntity from JSON */
        StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
        /* Body of request */
        httpPost.setEntity(jsonData);
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpPost, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Related
Apache HttpGet Example
Apache HttpDelete Example
Apache HttpPut Example

Apache HttpGet Example

Apache HttpGet

Following excerpt shows how you can make GET request using org.apache.http.client.methods.HttpGet.

Source code (HttpGetExample.java)
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example: Apache HttpGet.
 * @author javaQuery
 * @date 22nd January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class HttpGetExample {

    public static void main(String[] args) {
        /* Create object of CloseableHttpClient */
        CloseableHttpClient httpClient = HttpClients.createDefault();

        /* Prepare get request */
        HttpGet httpGet = new HttpGet("http://www.example.com/api/");
        /* Add headers to get request */
        httpGet.addHeader("Authorization", "value");
        httpGet.addHeader("Content-Type", "application/json");
        
        /* Response handler for after request execution */
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                /* Get status code */
                int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
                System.out.println("Response code: " + httpResponseCode);
                if (httpResponseCode >= 200 && httpResponseCode < 300) {
                    /* Convert response to String */
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    return null;
                    /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
                }
            }
        };

        try {
            /* Execute URL and attach after execution response handler */
            String strResponse = httpClient.execute(httpGet, responseHandler);
            /* Print the response */
            System.out.println("Response: " + strResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Related
Apache HttpPost Example
Apache HttpDelete Example
Apache HttpPut Example

Download and Run Amazon DynamoDB on local system

DynamoDB + Amazon Web Services

What is Amazon DynamoDB?
Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models.

Amazon provides application to run DynamoDB on your local system. So you don't have to pay for Amzon DynamoDB service while you are developing your application and works without internet connection.

Download

Installation
Step 1: Extract the downloaded file.

Step 2: Open DynamoDB folder location in command line and execute following command. 
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

E:\Softwares\Database\dynamodb_local_2016-01-07_1.0>java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       true
shouldDelayTransientStatuses:   false
CorsParams:     *
Step 3: Open http://localhost:8000/shell/ in your browser. (Note: DynamoDB works well in Google Chrome and Firefox)


Port 8000
By default DynamoDB uses port 8000. If another application running on same port then it'll throw an exception.
2016-01-21 08:40:10.729:WARN:oejuc.AbstractLifeCycle:FAILED SelectChannelConnector@0.0.0.0:8000: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
        at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:187)
        at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:316)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:265)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at org.eclipse.jetty.server.Server.doStart(Server.java:293)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer.start(DynamoDBProxyServer.java:83)
        at com.amazonaws.services.dynamodbv2.local.main.ServerRunner.main(ServerRunner.java:71)
2016-01-21 08:40:10.731:WARN:oejuc.AbstractLifeCycle:FAILED org.eclipse.jetty.server.Server@7ba18f1b: java.net.BindException: Address already in use: bi
java.net.BindException: Address already in use: bind
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.Net.bind(Unknown Source)
        at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
        at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:187)
        at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:316)
        at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:265)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at org.eclipse.jetty.server.Server.doStart(Server.java:293)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
        at com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer.start(DynamoDBProxyServer.java:83)
        at com.amazonaws.services.dynamodbv2.local.main.ServerRunner.main(ServerRunner.java:71)
Could not start server on port 8000: Address already in use: bind
To use another port for DynamoDB use -port option in command line to run DynamoDB.
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -port 8001

Command line options

  • -cors value — Enable CORS support (cross-origin resource sharing) for JavaScript. You must provide a comma-separated "allow" list of specific domains. The default setting for -cors is an asterisk (*), which allows public access.
  • -dbPath value — The directory where DynamoDB will write its database file. If you do not specify this option, the file will be written to the current directory. Note that you cannot specify both --dbPath and --inMemory at once.
  • -delayTransientStatuses — Causes DynamoDB to introduce delays for certain operations. DynamoDB can perform some tasks almost instantaneously, such as create/update/delete operations on tables and indexes; however, the actual DynamoDB service requires more time for these tasks. Setting this parameter helps DynamoDB simulate the behavior of the Amazon DynamoDB web service more closely. (Currently, this parameter introduces delays only for global secondary indexes that are in either CREATING or DELETING status.)
  • -help — Prints a usage summary and options.
  • -inMemory — DynamoDB; will run in memory, instead of using a database file. When you stop DynamoDB;, none of the data will be saved. Note that you cannot specify both --dbPath and --inMemory at once.
  • -optimizeDbBeforeStartup — Optimizes the underlying database tables before starting up DynamoDB on your computer. You must also specify -dbPath when you use this parameter.
  • -port value — The port number that DynamoDB will use to communicate with your application. If you do not specify this option, the default port is 8000.
  • -sharedDb — DynamoDB will use a single database file, instead of using separate files for each credential and region. If you specify -sharedDb, all DynamoDB clients will interact with the same set of tables regardless of their region and credential configuration.

Stop DynamoDB
To stop DynamoDB, press Ctrl+C in the command prompt window.

Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP: '20160114T083022Z' != '20160114', from '20160114T083022Z'.

I got this response message while working around AWS Version 4 Signing ProcessThere ain't much to explain. Just add 

  • x-amz-date header with date format yyyyMMdd'T'HHmmss'Z'
  • And use yyyyMMdd date format in StringToSign and Credential parameter of Authorization header.

Related
Authorization header requires 'Credential' parameter.
Authorization header requires 'Signature' parameter.
Authorization header requires 'SignedHeaders' parameter.