Oct 31 2014

Java Transient and Volatile Keywords

image_pdf

Transient Keyword:

Transient Keyword marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be ‘serialized’. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

In One word transient keyword is used in serialization process to prevent any variable from being serialized.

Transient keyword provides some control over serialization process and gives flexibility to exclude some of object properties from serialization process.

What kind of variables we can mark as transient?
For example if we have a field called “speed” whose value can be derived from other fields e.g. distance, time then there is no need to serialize it.

we can declare a variable static and transient at same time and java compiler doesn’t complain, but doing that doesn’t make any sense, because transient is to instruct “do not save this field” and static variables are implicitly not saved during serialization.

In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of re-initializing a final variable during deserialization.

 

Volatile Keyword:

Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory.

Java volatile keyword cannot be used with method or class and it can only be used with variable.
So apart from synchronized keyword in java, volatile keyword is also used to communicate content of memory between threads.

volatile keyword in java guarantees that value of volatile variable will always be read from main memory and “happens-before” relationship in Java Memory model will ensure that content of memory will be communicated to different threads.

When to Use:

1) we can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. we can avoid this issue by making long and double variable volatile in Java.

2) Volatile variable can be used as an alternative way of achieving synchronization in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values.

3)volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory.

4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java:
1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.

2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread’s local cache.

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5, changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables / most primitive variables (all types except long and double) even without use of volatile keyword in Java.

7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait.

8. Java volatile variable object reference can be null.

9. Java volatile keyword doesn’t means atomic, its common understanding that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.

Difference between synchronized and volatile keyword in Java:

Volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods.

2. Synchronized obtains and releases lock on monitor’s, java volatile keyword doesn’t require that.

3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java.

4. Synchronized method affects performance more than volatile keyword in Java.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and “main” memory. While synchronized synchronizes the value of all variable between thread memory and “main” memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

6. We can not synchronize on null object but your volatile variable in java could be null.

7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire.

In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is handy and can save performance overhead which comes with use of synchronization in Java.

Sep 15 2014

Configuring two way SSL in Tomcat

image_pdf

Configuring two way SSL in Tomcat :

Setting up Tomcat to provide self-signed SSL certificates allowing secure client/server communication and relatively easy to set up.

Java provides a handy command-line tool called keytool that you can use to generate keystores.

Generate the Client and Server Keystores :

By following the instructions below, you will create two keystores: clientkeystore.jks (for the client to use) and serverkeystore.jks (for the server to use). In order to provide copies of the client’s certificate to the server (and vice versa), you will export public certificates based on the private keys.

Finally, you will install the server’s public certificate in to the client’s keystore and vice versa, allowing both the client and server to properly authenticate and trust each other when a secure connection is established.

keytool -genkeypair -alias serverkey -keyalg RSA -dname "CN=localhost,OU=Organization Unit,O=Organization,L=City,S=State,C=IN" -keypass password -keystore serverkeystore.jks -storepass password

keytool -genkeypair -alias clientkey -keyalg RSA -dname "CN=localhost,OU=Organization Unit,O=Organization,L=City,S=State,C=IN" -keypass password -storepass password -keystore clientkeystore.jks

 

Export the Client’s Public Certificate and Import it in to the Server’s Keystore :

keytool -exportcert -alias clientkey -file client-public.cer -keystore clientkeystore.jks -storepass password

keytool -importcert -keystore serverkeystore.jks -alias clientcert -file client-public.cer -storepass password -noprompt

Important!

# view the contents of the keystore (use -v for verbose output)

keytool -list -keystore serverkeystore.jks -storepass password

 

Export the Server’s Public Certificate and Import it in to the Client’s Keystore :

keytool -exportcert -alias serverkey -file server-public.cer -keystore serverkeystore.jks -storepass password

keytool -importcert -keystore clientkeystore.jks -alias servercert -file server-public.cer -storepass password -noprompt

keytool -list -keystore clientkeystore.jks -storepass password

 

The clientkeystore.jks is of format JKS (Java Key Store).  Firefox and Chrome, both accept keystores of format PKCS12 (Personal Information Exchange Syntax Standard).  To convert clientkeystore.jks, go to the terminal and type:

keytool -importkeystore -srckeystore clientkeystore.jks -destkeystore clientcert.p12 -srcstoretype JKS -srcalias clientkey -deststoretype pkcs12

You will be asked for the keystore password and will also be asked to set a new password.

 

Configuring Tomcat server.xml file :

Update {tomcat.home}/conf/server.xml, substituting the entries forkeystoreFile, keystorePass, truststoreFile, and truststorePass with the appropriate paths/passwords from your implementation. These paths will point to the keystores created earlier in this process.

<Connector
   clientAuth="true" port="443" protocol="HTTP/1.1"
   maxThreads="200" scheme="https" secure="true" SSLEnabled="true"
   keystoreFile="/path/to/your/keystore/serverkeystore.jks"
   keystoreType="JKS" keystorePass="password"
   truststoreFile="/path/to/your/keystore/serverkeystore.jks" truststoreType="JKS" 
   truststorePass="password" SSLVerifyClient="require" sslProtocol="TLS" />

Now you can open Firefox / Chrome / IE and go to Setting/Options –> content / Manage Certificates –> import, select the certificate and import. Give the password when it’s prompted.

In address bar give the path and accept the self-signed certificate,

Now you are able to access secured private connection using SSL.

 

Client Application useing apache’s commons httpclient :

To establish a secure connection to the Tomcat server we can use Apache’s Commons HTTPClient, the system properties defined in the static block, these properties tell the JVM where to find the trust store (which self-signed server certificates it should trust) and the keystore.

import java.io.IOException;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
 
 
public class ClientConnectionTest
{
 static
 {
 System.setProperty("javax.net.ssl.trustStore", "/path/to/your/keystore/clientkeystore.jks");
 System.setProperty("javax.net.ssl.trustStorePassword", "password");
 System.setProperty("javax.net.ssl.keyStore", "/path/to/your/keystore/clientkeystore.jks");
 System.setProperty("javax.net.ssl.keyStorePassword", "password");
 }
 
   public static void main(String[] args) throws HttpException, IOException
   {
      HttpClient client = new HttpClient();
      GetMethod method = new GetMethod();
      //if you are not redirecting you can use port as localhost:8443
      method.setURI(new URI("https://localhost", false)); 
      client.executeMethod(method);
 
      System.out.println(method.getResponseBodyAsString());
   }
}

Aug 28 2014

Java EE 8 Takes Off

image_pdf

Java EE 8 is now officially launched as JSR 366 via the JCP process. As you might have expected the primary focus areas are HTTP 2/HTML 5 support, CDI/managed bean alignment, cloud support and Java SE alignment.

Here is some of the very high level content:

Web Standards

  • HTTP 2
  • Server-Sent Events (SSE)
  • JSON binding
  • Action oriented web framework to complement JSF
  • More support for Hypermedia
  • Enhancements to JSON-P, WebSocket and JAX-RS

Managed Bean/CDI Alignment

  • CDI 2
  • Container services such as EJB style declarative security and scheduling made available to managed beans/CDI generally
  • MDB style CDI based declarative JMS message listeners
  • Pruning some of the older EJB 2/CORBA APIs
  • JAX-RS alignment with CDI

Cloud

  • Configuration
  • Multitenancy
  • Simplified security
  • REST APIs for management and monitoring

Java SE

  • Taking advantage of features available such as repeating annotations, lambda expressions, the Date/Time API, type annotations, Completable Futures and so on.

This of course is just the high level initial plan and there will be many other changes included such as updates to JSF and JMS as well as the addition of JCache/data grids. Do make sure to check out the JSR page on jcp.org for details. Now is the time to start getting involved or at least begin to think about it.

Besides the platform JSR, a number of APIs targeted to Java EE 8 have also now been filed, each under their own JSR. Check out the details on each JSR page:

More Java EE 8 JSRs will be soon to follow.

For more details refer jsr-366, java ee 8 takes off, java ee 8 jsr,

Jul 09 2014

Differences and Similarities between HashSet TreeSet and LinkedHashSet

image_pdf

Introduction:

TreeSet, LinkedHashSet and HashSet are implementation of Set interface from that, they follows contract of Set interface i.e. they do not allow duplicate elements.

Now in this post we will see the difference between HashSet, TreeSet and LinkedHashSet on different points like ordering elements, allowing null and performance ..etc.

Details of HashSet TreeSet and LinkedHashSet:

Main feature of HashSet is storing unique objects, Main feature of TreeSet is ordering, and LinkedHashSet is insertion order.

  • HashSet has backing HashMap instance and default initial capacity (16) and load factor (0.75).
  • LinkedHashSet is Hash table and linked list implementation of the Set interface, with predictable iteration order. It maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. [An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.] default initial capacity (16) and load factor (0.75).

Similarities between HashSet TreeSet and LinkedHashSet:

  • Not allowed to store duplicates.
  • Not Thread-safe need external synchronization.
  • Fail-fast iterator and throw ConcurrentModificationException.

Difference between HashSet TreeSet and LinkedHashSet:

Ordering Performance Null Internal Implementaion
HashSet Doesn’t Maintain Fastest O(1) Allow backing of HashMap
LinkedHashSet Insertion Order Fastest O(1) (Similar to HashSet) Allow backing of HashSet and LinkedList
TreeSet Sorting order of elements Slower O(log(n)) (slow due to sorting) Doesn’t Allow backing of NavigableMap and TreeMap

Please refer HashSetTreeSet, and LinkedHashSet for more details.

Mar 13 2014

HTTP status codes and associated messages might returned from the Web Servers

image_pdf

List of HTTP status codes and associated messages that might be returned from the Web Servers:

Code Message Description
100 Continue Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request
101 Switching Protocols The server switches protocol.
200 OK The request is OK
201 Created The request is complete, and a new resource is created
202 Accepted The request is accepted for processing, but the processing is not complete.
203 Non-authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices A link list. The user can select a link and go to that location. Maximum five addresses
301 Moved Permanently The requested page has moved to a new url
302 Found The requested page has moved temporarily to a new url
303 See Other The requested page can be found under a different url
304 Not Modified
305 Use Proxy
306 Unused This code was used in a previous version. It is no longer used, but the code is reserved.
307 Temporary Redirect The requested page has moved temporarily to a new url.
400 Bad Request The server did not understand the request
401 Unauthorized The requested page needs a username and a password
402 Payment Required You cannot use this code yet
403 Forbidden Access is forbidden to the requested page
404 Not Found The server cannot find the requested page.
405 Method Not Allowed The method specified in the request is not allowed.
406 Not Acceptable The server can only generate a response that is not accepted by the client.
407 Proxy Authentication Required You must authenticate with a proxy server before this request can be served.
408 Request Timeout The request took longer than the server was prepared to wait.
409 Conflict The request could not be completed because of a conflict.
410 Gone The requested page is no longer available.
411 Length Required The “Content-Length” is not defined. The server will not accept the request without it.
412 Precondition Failed The precondition given in the request evaluated to false by the server.
413 Request Entity Too Large The server will not accept the request, because the request entity is too large.
414 Request-url Too Long The server will not accept the request, because the url is too long. Occurs when you convert a “post” request to a “get” request with a long query information.
415 Unsupported Media Type The server will not accept the request, because the media type is not supported.
417 Expectation Failed
500 Internal Server Error The request was not completed. The server met an unexpected condition
501 Not Implemented The request was not completed. The server did not support the functionality required.
502 Bad Gateway The request was not completed. The server received an invalid response from the upstream server
503 Service Unavailable The request was not completed. The server is temporarily overloading or down.
504 Gateway Timeout The gateway has timed out.
505 HTTP Version Not Supported The server does not support the “http protocol” version.

 

Refer w3c Web Site for detailed description of status codes.

Mar 09 2014

How to re-load properties files without restarting server in java

image_pdf

Re-load properties files without restarting server in Java:

Use Apache Commons Configuration to resolve this issue,

PropertiesConfiguration propertiesConfig = new PropertiesConfiguration("yourProps.properties");
propertiesConfig.setReloadingStrategy(new FileChangedReloadingStrategy());

For this need to use commons-configuration dependency / jar.

<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>20041012.002804</version>
</dependency>

you can find further details in the java-doc,

This will Re-load properties files without restarting server.