Configure SSL/HTTPS with CA / ROOT certificate on Apache Tomcat

Configuring Tomcat to use SSL connections can be a bit tricky the first time around, but if you follow this step by step guide, you should it up and running in no time.

Purpose of SSL certificate

An SSL certificate serves two essential purposes: distributing the public key and verifying the identity of the server so users know they aren't sending their information to the wrong server. It can only properly verify the identity of the server when it is signed by a trusted third party.

Certificate Authorities like Verisign.com, Trustcenter.de, Thawte.com etc. exist to verify to clients that your server is who your certificate says it is. If you run an eCommerce site, you would definitely want your server to be registered with a Certificate Authority so that clients know they can trust that your server to be the server they think it is.

What is a certificate authority (CA)?

A Certificate Authority is a trusted third party whose role is to validate information about a web server, including the server’s domain name, its public key, and optionally the name of the company that runs it. Once this and other information is validated, the CA creates a TLS or SSL certificate with the information and digitally signs it using the CA’s private key. The public keys of many CAs (known as “root certificates”) are embedded in user agent software like browsers, enabling the browser to trust any TLS or SSL certificate that cryptographically chains up to one of those trusted roots.

After web server certificates are issued, CAs provide up-to-date status of those certificates so that if one needs to be revoked for whatever reason, browsers can be alerted to the change. Certificate status information is provided either via Certificate Revocation Lists (CRLs) or Online Certificate Status Protocol (OCSP).

CAs are an integral part of the trust model used by browsers and web servers, performing validation of web server details on behalf of end users. This model has permitted secure, authenticated Internet communication between billions of users and millions of web sites.

Setting up SSL for Tomcat can be pided into two main tasks: creating a functional keystore, and configuring the Tomcat connectors and applications. Let's tackle them one at a time.

STEP 1 : Create Keystore

Open command prompt and go to %JAVA_HOME%\bin. Use keytool to create JKS (Java KeyStore) format keystore and a self-signed certificate.

When you type the command, it will ask you some questions. First, it will ask you to create a password (My password is “changeit“) and then some information like given below :

C:\>JAVA_HOME\bin\keytool -genkey -alias TutorialsDesk -keyalg RSA -keystore d:/mykeystore/TutorialsDesk.keystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  Prakash Hari Sharma
What is the name of your organizational unit?
  [Unknown]:  RnD
What is the name of your organization?
  [Unknown]:  TutorialsDesk.com
What is the name of your City or Locality?
  [Unknown]:  Noida
What is the name of your State or Province?
  [Unknown]:  UP
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=Prakash Hari Sharma, OU=RnD, O=TutorialsDesk.com, L=Noida, ST=UP, C=IN cor
rect?
  [no]:  yes

Enter key password for <tutorialsdesk>
        (RETURN if same as keystore password):

C:\>

It will create a TutorialsDesk.keystore file on your d:/mykeystore directory.

Follow below command to check generated keystore:

C:\>JAVA_HOME\bin\keytool -list -keystore d:/mykeystore/TutorialsDesk.keystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

tutorialsdesk, Sep 25, 2014, PrivateKeyEntry,
Certificate fingerprint (MD5): 49:CA:5D:61:14:40:14:2A:5C:54:25:56:40:C2:35:D7

C:\>

STEP 2 : Creating the Certificate Signing Request (CSR)

Now that you've created your keystore, it's time to create a file called the Certificate Signing Request, or CSR, which will be used by the Certificate Authority of your choice to generate the Certificate SSL will present to other parties during the handshake.

You can use the keytool to create this file, as well. To do so, enter the following at the command line:

C:\>JAVA_HOME\bin\keytool -certreq -alias test1 -keyalg RSA -keystore d:/mykeystore/TutorialsDesk.keystore -file d:/mykeystore/TutorialsDesk.csr

keytool will create a file called TutorialsDesk.csr, which you can submit to the CA you've chosen via the process they provide on their website. Using this file, they will generate a custom certificate for your server, which you can download according to the instructions they provide on their website.

STEP 3 : Installing Certificates to keystore

SSL verifies the authenticity of a site's certificate by using something called a "chain of trust," which basically means that during the handshake, SSL initiates an additional handshake with the Certificate Authority specified in your site's certificate, to verify that you haven't simply made up your own CA.

In order to "anchor" your certificate's chain of trust, you have to download an additional certificate, called a "Root Certificate," from your CA, and then import both this certificate and your site's new certificate into your keystore. Your CA should provide information about obtaining a Root Certificate on their website.

Once you've downloaded both your own Certificate and the Root certificate provided by your CA, import them into your keystore with the following commands

import the Root Certificate

C:\>JAVA_HOME\bin\keytool -import -alias root -keystore d:/mykeystore/TutorialsDesk.keystore -trustcacerts -file d:/mykeystore/ROOT.cer

import your new Certificate

C:\>JAVA_HOME\bin\keytool -import -alias test -keystore d:/mykeystore/TutorialsDesk.keystore -file d:/mykeystore/client.cer

STEP 4 : Configuring Tomcat for using the keystore file

Open your Tomcat installation directory and open the conf folder. Inside this folder, you will find the server.xml file.

Search for "Define a SSL HTTP/1.1 Connector on port 8443". Connector configuration will be commented there. Uncomment it.

<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
    maxThreads="150" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
-->


Uncomment it and modify it to look like the following:

<Connector
           protocol="HTTP/1.1"
           port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="${user.home}/TutorialsDesk.keystore" keystorePass="changeit"
           clientAuth="false" sslProtocol="TLS"/>

Note we have added the keystoreFile, keystorePass and changed the protocol declarations.

STEP 5 : Check SSL / HTTPS setup

Start tomcat service and try to access https://localhost:8443. You will see Tomcat’s local home page.
Note : if you try to access the default 8080 port it will be working too: http://localhost:8080

STEP 6 : Configuring your app to work with SSL

To force your web application to work with SSL, you simply need to add the following code to your web.xml file (before web-app tag ends):

<security-constraint>
    <web-resource-collection>
        <web-resource-name>mysecuredapp</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

The url pattern is set to /* so any page/resource from your application is secure (it can be only accessed with https). The transport-guarantee tag is set to CONFIDENTIAL to make sure your app will work on SSL.

If you want to turn off the SSL, you don’t need to delete the code above from web.xml, simply change CONFIDENTIAL to NONE.


Hope we are able to explain you Configure SSL/HTTPS with CA / ROOT certificate on Apache Tomcat , if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.
Configure SSL/HTTPS with CA / ROOT certificate on Apache Tomcat

Program to calculate Factorial of a number in Java

This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.

import java.util.Scanner;

class Factorial
{
   public static void main(String args[])
   {
      int n, c, fact = 1;

      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);

      n = in.nextInt();

      if ( n < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;

         System.out.println("Factorial of "+n+" is = "+fact);
      }
   }
}

Factorial of a number in Java

if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

What is SSL? SSL Certificate Basics Tutorial

What is SSL? SSL Certificate Basics Tutorial
Secure Socket Layer (SSL) is a protocol that provides security for communications between client and server by implementing encrypted data and certificate-based authentication. Technically, the term "SSL" now refers to the Transport Layer ouSecurity (TLS) protocol, which is based on the original SSL specification.

SSL, or Secure Socket Layer, is a technology which allows web browsers and web servers to communicate over a secured connection. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing. This is a two-way process, meaning that both the server AND the browser encrypt all traffic before sending out data.

SSL is one of the most common ways of integrating secure communication on the internet, as it is a mature protocol that is well-supported by every major browser and a number of well-respected organizations provide third party SSL authentication services.

Why do I need SSL?

If you are transmitting sensitive information on a web site, such as credit card numbers or personal information, you need to secure it with SSL encryption. It is possible for every piece of data to be seen by others unless it is secured by an SSL certificate.

Your customers won't trust your web site without an SSL certificate. According to Gartner Research, nearly 70 percent of online shoppers have terminated an online order because they did not "trust" the transaction. In those cases, 64 percent indicated that the presence of a trust mark would have likely prevented the termination. An SSL certificate and a site seal could stop people from abandoning your website and that means more money for you.

HTTPS vs. HTTP

The most common way that SSL is integrated into Internet communications is through the HTTPS protocol. Calling HTTPS a "protocol" is not entirely accurate, as it is simply a combination of the HTTP and SSL protocols. When we say a message was sent using HTTPS, what we are actually saying is that the message was first encrypted using SSL, transmitted and received using normal HTTP protocol, and then decrypted by the receiver, also with SSL.
  • SSL offers security through encryption
  • the encryption process is made possible through the use of digital certificates verified by a third party Certificate Authority
  • the most common implementation of this process is the HTTPS combination protocol.

SSL Basics

The Secure Socket Layer protocol was created by Netscape to ensure secure transactions between web servers and browsers. The protocol uses a third party, a Certificate Authority (CA), to identify one end or both end of the transactions. This is in short how it works.
  1. A browser requests a secure page (usually https://).
  2. The web server sends its public key with its certificate.
  3. The browser checks that the certificate was issued by a trusted party (usually a trusted root CA), that the certificate is still valid and that the certificate is related to the site contacted.
  4. The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted http data.
  5. The web server decrypts the symmetric encryption key using its private key and uses the symmetric key to decrypt the URL and http data.
  6. The web server sends back the requested html document and http data encrypted with the symmetric key.
  7. The browser decrypts the http data and html document using the symmetric key and displays the information.

What is a certificate authority (CA)?

A Certificate Authority is a trusted third party whose role is to validate information about a web server, including the server’s domain name, its public key, and optionally the name of the company that runs it. Once this and other information is validated, the CA creates a TLS or SSL certificate with the information and digitally signs it using the CA’s private key. The public keys of many CAs (known as “root certificates”) are embedded in user agent software like browsers, enabling the browser to trust any TLS or SSL certificate that cryptographically chains up to one of those trusted roots.

After web server certificates are issued, CAs provide up-to-date status of those certificates so that if one needs to be revoked for whatever reason, browsers can be alerted to the change. Certificate status information is provided either via Certificate Revocation Lists (CRLs) or Online Certificate Status Protocol (OCSP).

CAs are an integral part of the trust model used by browsers and web servers, performing validation of web server details on behalf of end users. This model has permitted secure, authenticated Internet communication between billions of users and millions of web sites.

Private Key/Public Key

The encryption using a private key/public key pair ensures that the data can be encrypted by one key but can only be decrypted by the other key pair. This is sometime hard to understand, but believe me it works. The keys are similar in nature and can be used alternatively: what one key encrypts, the other key pair can decrypt. The key pair is based on prime numbers and their length in terms of bits ensures the difficulty of being able to decrypt the message without the key pairs. The trick in a key pair is to keep one key secret (the private key) and to distribute the other key (the public key) to everybody. Anybody can send you an encrypted message, that only you will be able to decrypt. You are the only one to have the other key pair, right? In the opposite , you can certify that a message is only coming from you, because you have encrypted it with you private key, and only the associated public key will decrypt it correctly. Beware, in this case the message is not secured you have only signed it. Everybody has the public key, remember!

The Symmetric key

Well, Private Key/Public Key encryption algorithms are great, but they are not usually practical. It is asymmetric because you need the other key pair to decrypt. You can't use the same key to encrypt and decrypt. An algorithm using the same key to decrypt and encrypt is deemed to have a symmetric key. A symmetric algorithm is much faster in doing its job than an asymmetric algorithm. But a symmetric key is potentially highly insecure. If the enemy gets hold of the key then you have no more secret information. You must therefore transmit the key to the other party without the enemy getting its hands on it.
As you know, nothing is secure on the Internet. The solution is to encapsulate the symmetric key inside a message encrypted with an asymmetric algorithm. You have never transmitted your private key to anybody, then the message encrypted with the public key is secure (relatively secure, nothing is certain except death and taxes). The symmetric key is also chosen randomly, so that if the symmetric secret key is discovered then the next transaction will be totally different.

Encryption algorithm

There are several encryption algorithms available, using symmetric or asymmetric methods, with keys of various lengths. Usually, algorithms cannot be patented, if Henri Poincare had patented his algorithms, then he would have been able to sue Albert Einstein... So algorithms cannot be patented except mainly in USA. OpenSSL is developed in a country where algorithms cannot be patented and where encryption technology is not reserved to state agencies like military and secret services. During the negotiation between browser and web server, the applications will indicate to each other a list of algorithms that can be understood ranked by order of preference. The common preferred algorithm is then chosen. OpenSSL can be compiled with or without certain algorithms, so that it can be used in many countries where restrictions apply.

The Hash

A hash is a number given by a hash function from a message. This is a one way function, it means that it is impossible to get the original message knowing the hash. However the hash will drastically change even for the slightest modification in the message. It is therefore extremely difficult to modify a message while keeping its original hash. It is also called a message digest. Hash functions are used in password mechanisms, in certifying that applications are original (MD5 sum), and in general in ensuring that any message has not been tampered with. It seems that the Internet Enginering Task Force (IETF) prefers SHA1 over MD5 for a number of technical reasons (Cf RFC2459 7.1.2 and 7.1.3).

Signing

Signing a message, means authentifying that you have yourself assured the authenticity of the message (most of the time it means you are the author, but not neccesarily). The message can be a text message, or someone else's certificate. To sign a message, you create its hash, and then encrypt the hash with your private key, you then add the encrypted hash and your signed certificate with the message. The recipient will recreate the message hash, decrypts the encrypted hash using your well known public key stored in your signed certificate, check that both hash are equals and finally check the certificate.

The other advantage of signing your messages is that you transmit your public key and certificate automatically to all your recipients.

There are usually 2 ways to sign, encapsulating the text message inside the signature (with delimiters), or encoding the message altogether with the signature. This later form is a very simple encryption form as any software can decrypt it if it can read the embedded public key. The advantage of the first form is that the message is human readable allowing any non complaint client to pass the message as is for the user to read,

while the second form does not even allow to read part of the message if it has been tampered with.

In The next posts we will expalin How to import third party certificate in local keystore.


Hope we are able to explain you What is SSL? SSL Certificate Basics , if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Configure SSL/HTTPS with self signed certificate on Apache Tomcat

Configuring Tomcat to use SSL connections can be a bit tricky the first time around, but if you follow this step by step guide, you should it up and running in no time.

Purpose of SSL certificate

An SSL certificate serves two essential purposes: distributing the public key and verifying the identity of the server so users know they aren't sending their information to the wrong server. It can only properly verify the identity of the server when it is signed by a trusted third party.

Certificate Authorities like Verisign.com, Trustcenter.de, Thawte.com etc. exist to verify to clients that your server is who your certificate says it is. If you run an eCommerce site, you would definitely want your server to be registered with a Certificate Authority so that clients know they can trust that your server to be the server they think it is.

Trusted third party certificate can be expensive. What should you do if you just want to make sure that certain communication between a client browser and your Tomcat server is encrypted? A quick solution is to create a 'self-signed' certificate. If you do this, clients can't really trust that you are who you say you are, but communication between a client and your server will be encrypted.

Self signed certificate

A self signed certificate is a certificate that is signed by itself rather than a trusted authority.

Limitations of self signed certificate

Since any attacker can create a self signed certificate and launch a man-in-the-middle attack, a user can't know whether they are sending their encrypted information to the server or an attacker. Because of this, you will almost never want to use a self signed certificate on a public Java server that requires anonymous visitors to connect to your site.

Self signed certificate can be used in such Scenario:

  • An Intranet When clients only have to go through a local Intranet to get to the server, there is virtually no chance of a man-in-the-middle attack.
  • A Java development server There is no need to spend extra cash buying a trusted certificate when you are just developing or testing an application.
  • Personal sites with few visitors If you have a small personal site that transfers non-critical information, there is very little incentive for someone to attack the connection.

Configure Self signed certificate in Tomcat

To configure Self signed certificate in Apache Tomcat you need to simply follow below steps

STEP 1 : Create Keystore and Self-signed Certificate

Open command prompt and go to %JAVA_HOME%\bin. Use keytool to create JKS (Java KeyStore) format keystore and a self-signed certificate.

When you type the command, it will ask you some questions. First, it will ask you to create a password (My password is “changeit“) and then some information like given below :

C:\>JAVA_HOME\bin\keytool -genkey -alias TutorialsDesk -keyalg RSA -keystore d:/mykeystore/TutorialsDesk.keystore
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  Prakash Hari Sharma
What is the name of your organizational unit?
  [Unknown]:  RnD
What is the name of your organization?
  [Unknown]:  TutorialsDesk.com
What is the name of your City or Locality?
  [Unknown]:  Noida
What is the name of your State or Province?
  [Unknown]:  UP
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=Prakash Hari Sharma, OU=RnD, O=TutorialsDesk.com, L=Noida, ST=UP, C=IN cor
rect?
  [no]:  yes

Enter key password for <tutorialsdesk>
        (RETURN if same as keystore password):

C:\>

It will create a TutorialsDesk.keystore file on your d:/mykeystore directory.

Follow below command to check generated keystore:

C:\>JAVA_HOME\bin\keytool -list -keystore d:/mykeystore/TutorialsDesk.keystore
Enter keystore password:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

tutorialsdesk, Sep 25, 2014, PrivateKeyEntry,
Certificate fingerprint (MD5): 49:CA:5D:61:14:40:14:2A:5C:54:25:56:40:C2:35:D7

C:\>

STEP 2 : Configuring Tomcat for using the keystore file

Open your Tomcat installation directory and open the conf folder. Inside this folder, you will find the server.xml file.

Search for Connector port="8443". Connector configuration will be commented there. Uncomment it.

<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
    maxThreads="150" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
-->


Uncomment it and modify it to look like the following:

<Connector
           protocol="HTTP/1.1"
           port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="${user.home}/TutorialsDesk.keystore" keystorePass="changeit"
           clientAuth="false" sslProtocol="TLS"/>

Note we have added the keystoreFile, keystorePass and changed the protocol declarations.

STEP 3 : Check SSL / HTTPS setup

Start tomcat service and try to access https://localhost:8443. You will see Tomcat’s local home page.
Note : if you try to access the default 8080 port it will be working too: http://localhost:8080

STEP 4 : Configuring your app to work with SSL

To force your web application to work with SSL, you simply need to add the following code to your web.xml file (before web-app tag ends):

<security-constraint>
    <web-resource-collection>
        <web-resource-name>mysecuredapp</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

The url pattern is set to /* so any page/resource from your application is secure (it can be only accessed with https). The transport-guarantee tag is set to CONFIDENTIAL to make sure your app will work on SSL.

If you want to turn off the SSL, you don’t need to delete the code above from web.xml, simply change CONFIDENTIAL to NONE.

NOTE : For production application, obtain certificate from certificate authority (like GeoTrust, Verisign, Thawte etc.) and import the same in local keystore.
In The next posts we will expalin How to import third party certificate in local keystore.

Hope we are able to explain you Configure SSL/HTTPS with self signed certificate on Apache Tomcat , if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.
Configure SSL/HTTPS with self signed certificate on Apache Tomcat

Difference between HashMap and Hashtable in java

Difference between HashMap and Hashtable in Java question oftenly asked in core Java interviews to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

Before seeing differences between HashMap and Hashtable, let's see some similarities between these two and why we can use HashMap in place of Hashtable on certain scenario.

Similarities between HashMap and Hashtable

  1. Both Hashtable and HashMap implements java.util.Map interface.
  2. Hashtable and HashMap both are hash based collection and works on principle of hashing.
  3. Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.
  4. Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
  5. From JDK 4 both Hashtable and HashMap are part of Java collection framework.

Difference between HashMap and Hashtable


Now let's see some key difference between HashMap and Hashtable in Java, this will decide when is the right time to use Hashtable over HashMap and vice-versa. Differences are based upon properties like synchronization, thread safety, speed, performance , Fail fast and Null key etc.

Synchronization and Thread-Safetey


One of the major differences between HashMap and Hashtable is that HashMap is non synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.

Null keys and null values


Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.

Performance


Since HashMap is not synchronized it perform better than Hashtable.

fail-fast


First let's understand what is fail-fast? If the collection (ArrayList, vector etc) gets structurally modified by any means, except the add or remove methods of iterator, after creation of iterator then the iterator will throw ConcurrentModificationException. Structural modification refers to the addition or deletion of elements from the collection.

The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.

Super Class and Legacy


Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map" abstract data type.

How to make HashMap synchronized?


HashMap can be synchronized using:
Map map=Collections.synchonizedMap(hashmap) ;

When to use HashMap and when to use Hashtable?

  1. Single Threaded Application
  2. HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .
  3. Multi Threaded Application
  4. We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.
Difference between HashMap and Hashtable

Hope we are able to explain you Difference between HashMap and Hashtable, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Difference between ArrayList and Vector in java

Difference between Vector and ArrayList is the most common Core Java Interview question you will come across in Collection. This question is mostly used as a start up question by the Interviewers before testing deep roots of the Collection.

Before seeing differences between Vector and ArrayList, let's see some similarities between these two and why we can use ArrayList in place of Vector on certain scenario.

Similarities between Vector and ArrayList


  1. Vector and ArrayList are index based and backed up by an array internally.
  2. Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
  3. Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.
  4. ArrayList and Vector also allows null and duplicates.
  5. They both grows and shrinks automatically when overflow and deletion happens.

Differences between Vector and ArrayList


Now let's see some key difference between Vector and ArrayList in Java, this will decide when is the right time to use Vector over ArrayList and vice-versa. Differences are based upon properties like synchronization, thread safety, speed, performance , navigation and Iteration over List etc.

Synchronization and Thread-Safetey


Vector is synchronized while ArrayList is not synchronized. Synchronization and thread safe means at a time only one thread can access the code. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

Data Growth


Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Performance


ArrayList gives better performance as it is non-synchronized. Vector operations gives poor performance as they are thread-safe. thus in ArrayList two or more threads can access the code at the same time, while Vector is limited to one thread at a time.

fail-fast


First let's understand what is fail-fast? If the collection (ArrayList, Vector etc) gets structurally modified by any means, except the add or remove methods of iterator, after creation of iterator then the iterator will throw ConcurrentModificationException. Structural modification refers to the addition or deletion of elements from the collection.

As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator and listIterator returned by ArrayList are fail-fast.

Legacy


java.util.Vector class was there in java since the very first version of the java development kit (jdk). java.util.ArrayList was introduced in java version 1.2 , as part of Java Collections framework. In java version 1.2, Vector class has been refactored to implement the List Inteface .

When to use ArrayList and when to use vector?


It actually depends on our need.Vector is slower than ArrayList as its methods are synchronized so if we don't work in multi threaded environment then ArrayList is better choice.

How to make ArrayList synchronized?



Arraylist can be synchronized using:
List list = Collections.synchronizedList(new ArrayList());


Hope we are able to explain you Difference between Vector and ArrayList, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).
Difference between ArrayList and Vector in java

Please share us on social media if you like the tutorial.

Jersey CRUD RESTful webservice Tutorial with examples

This section creates a CRUD (Create, Read, Update, Delete) restful web service. It will allow to maintain a list of Tasks in your web application via HTTP calls.

Jersey CRUD RESTful webservice

STEP 1 : Create a new dynamic project called TutorialsDesk.Rest.CRUDWebServices and add the Jersey libs.

STEP 2 : Change the web.xml file to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TutorialsDesk.RestHelloWorld</display-name>
 <servlet>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
     <!-- Register resources and providers under com.tutorialsdesk.rest.helloworld package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.tutorialsdesk.rest.resources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 


STEP 3 : Create the following task.java data model and a Singleton which serves as the data provider for the model. We use the implementation based on an enumeration. The Task class is annotated with a JAXB annotation.

package com.tutorialsdesk.rest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Task {
  private String id;
  private String summary;
  private String description;
  
  public Task(){
    
  }
  public Task (String id, String summary){
    this.id = id;
    this.summary = summary;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }
  
  
} 



STEP 4 : Create the following TaskDao.java as below.

package com.tutorialsdesk.rest.dao;

import java.util.HashMap;
import java.util.Map;

import com.tutorialsdesk.rest.model.Task;;

public enum TaskDao {
  instance;
  
  private Map<String, Task> contentProvider = new HashMap<String, Task>();
  
  private TaskDao() {
    
    Task task = new Task("1", "Learn REST");
    task.setDescription("Read http://www.tutorialsdesk.com/2014/09/jersey-restful-webservices-tutorial.html");
    contentProvider.put("1", task);
    task = new Task("2", "Do something");
    task.setDescription("Read complete http://www.tutorialsdesk.com");
    contentProvider.put("2", task);
    
  }
  public Map<String, Task> getModel(){
    return contentProvider;
  }
  
} 



STEP 5 : Create a simple HTML form .
The REST service can be used via HTML forms. The following HTML form will allow to post new data to the service. Create the following page called create_task.html in the WebContent folder.

<!DOCTYPE html>
<html>
 <head>
  <title>Form to create a new resource</title>
 </head>
<body>
  <form action="../TutorialsDesk.Rest.CRUDWebServices/rest/tasks" method="POST">
  <label for="id">ID</label>
  <input name="id" />
  <br/>
  <label for="summary">Summary</label>
  <input name="summary" />
  <br/>
  Description:
  <TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
  <br/>
  <input type="submit" value="Submit" />
  </form>
</body>
</html> 



STEP 6 : Create the following TaskResource.java class which will be used as REST resources .
package com.tutorialsdesk.rest.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.tutorialsdesk.rest.dao.TaskDao;
import com.tutorialsdesk.rest.model.Task;

public class TaskResource {
  @Context
  UriInfo uriInfo;
  @Context
  Request request;
  String id;
  public TaskResource(UriInfo uriInfo, Request request, String id) {
    this.uriInfo = uriInfo;
    this.request = request;
    this.id = id;
  }
  
  //Application integration     
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Task getTodo() {
    Task task = TaskDao.instance.getModel().get(id);
    if(task==null)
      throw new RuntimeException("Get: Task with " + id +  " not found");
    return task;
  }
  
  // for the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public Task getTodoHTML() {
    Task task = TaskDao.instance.getModel().get(id);
    if(task==null)
      throw new RuntimeException("Get: Task with " + id +  " not found");
    return task;
  }
  
  @PUT
  @Consumes(MediaType.APPLICATION_XML)
  public Response putTodo(JAXBElement<Task> task) {
    Task c = task.getValue();
    return putAndGetResponse(c);
  }
  
  @DELETE
  public void deleteTodo() {
    Task c = TaskDao.instance.getModel().remove(id);
    if(c==null)
      throw new RuntimeException("Delete: Task with " + id +  " not found");
  }
  
  private Response putAndGetResponse(Task task) {
    Response res;
    if(TaskDao.instance.getModel().containsKey(task.getId())) {
      res = Response.noContent().build();
    } else {
      res = Response.created(uriInfo.getAbsolutePath()).build();
    }
    TaskDao.instance.getModel().put(task.getId(), task);
    return res;
  }
  
  

} 


STEP 7 : Create the following TasksResource.java class which will be used as REST resources .
package com.tutorialsdesk.rest.resources;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.tutorialsdesk.rest.dao.TaskDao;
import com.tutorialsdesk.rest.model.Task;;


// Will map the resource to the URL tasks
@Path("/tasks")
public class TasksResource {

  // Allows to insert contextual objects into the class, 
  // e.g. ServletContext, Request, Response, UriInfo
  @Context
  UriInfo uriInfo;
  @Context
  Request request;


  // Return the list of tasks to the user in the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public List<Task> getTodosBrowser() {
    List<Task> tasks = new ArrayList<Task>();
    tasks.addAll(TaskDao.instance.getModel().values());
    return tasks; 
  }
  
  // Return the list of tasks for applications
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public List<Task> getTasks() {
    List<Task> tasks = new ArrayList<Task>();
    tasks.addAll(TaskDao.instance.getModel().values());
    return tasks; 
  }
  
  
  // retuns the number of tasks
  // use http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/count
  // to get the total number of records
  @GET
  @Path("count")
  @Produces(MediaType.TEXT_PLAIN)
  public String getCount() {
    int count = TaskDao.instance.getModel().size();
    return String.valueOf(count);
  }
  
  @POST
  @Produces(MediaType.TEXT_HTML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public void newTask(@FormParam("id") String id,
      @FormParam("summary") String summary,
      @FormParam("description") String description,
      @Context HttpServletResponse servletResponse) throws IOException {
    Task task = new Task(id,summary);
    if (description!=null){
      task.setDescription(description);
    }
    TaskDao.instance.getModel().put(id, task);
    
    servletResponse.sendRedirect("../create_task.html");
  }
  
  
  // Defines that the next path parameter after tasks is
  // treated as a parameter and passed to the TodoResources
  // Allows to type http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/1
  // 1 will be treaded as parameter tasks and passed to TaskResource
  @Path("{task}")
  public TaskResource getTask(@PathParam("task") String id) {
    return new TaskResource(uriInfo, request, id);
  }
  
} 


This TasksResource uses the @PathParam annotation to define that the id is inserted as parameter.

Run Your CRUD Web Services : Run you web application in Eclipse and test the availability of your REST service under:
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks
You should see the XML representation of your TASK items.

To see the count of Task items use
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/count
to see an exiting Task use
http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/{id},
e.g., http://localhost:8080/TutorialsDesk.Rest.CRUDWebServices/rest/tasks/1
to see the Task with ID 1.
We currently have only Tasks with the ids 1 and 2, all other requests will result in an HTTP error code.

Please note that with the browser you can only issue HTTP GET requests. In The next posts we will use the Jersey client libraries to issue get, post and delete.
Jersey CRUD RESTful webservice Tutorial with examples

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Web Services in java.

Hope we are able to explain you Jersey CRUD RESTful webservices Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Jersey RESTful Webservices Tutorial with examples

REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis. In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web service clients that want to use these resources access via globally defined set of remote methods that describe the action to be performed on the resource.

It consists of two components REST server which provides access to the resources and a REST client which accesses and modify the REST resources.

REST fundamentals
  • Everything in REST is considered as a resource.
  • Every resource is identified by an URI.
  • Uses uniform interfaces. Resources are handled uing POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
  • Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
  • Communications are done via representations. E.g. XML, JSON RESTful Web Services
    A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service typically defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-defined, ...) and the set of operations (POST, GET, PUT, DELETE) which are supported.

HTTP methods
The PUT, GET, POST and DELETE methods are typical used in REST based architectures.
The following table gives an explanation of these operations.
  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
  • PUT creates a new resource. It must also be idempotent.
  • DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
  • POST updates an existing resource or creates a new resource.
JAX-RS
JAX-RS is an annotation-based API for implementing RESTful web services, based on HTTP, in Java. Essentially, classes and methods are annotated with information that enables a runtime to expose them as resources. A runtime that implements JAX-RS mediates between the HTTP protocol and the Java classes, taking into account URIs, requested and accepted content types, and HTTP methods.
Jersey framework implemented JSR-RS(JSR-311) reference APIs. In addition to Jersey various other implementation are available such as Retlet, JBOSS RESTeasy, Apache CXF etc.
Download the Jersey distribution as zip file from the Jersey download site.

Jersey
Jersey contains having following major parts:
  • Core Server: To build RESTful web services based on annotation include key libraries such as : jersey-core.jar, jersey-server.jar, jsr311-api.jar, asm.jar
  • Core Client: The Jersey client API helps you to easily communicate with REST services include libabry ersey-client.jar
  • JAXB support: (Used in the advanced example) jaxb-impl.jar, jaxb-api.jar, activation.jar, stax-api.jar, wstx-asl.jar
  • JSON support: (Used in the advanced example) jersey-json.jar
  • Integration: Jersey also provides libraries that can easily integrate with Spring, Guice, Apache Abdera, and so on.
Create your first Hello World RESTful Webservice
We have used jersey jaxrs-ri-2.12 and apache-tomcat-7.0.55 to run below example.
STEP 1 : Create a new Dynamic Web Project called TutorialsDesk.RestHelloWorld.

STEP 2 : Copy all JARs from your Jersey download into the WEB-INF/lib folder.

aopalliance-repackaged-2.3.0-b10.jar
asm-debug-all-5.0.2.jar
hk2-api-2.3.0-b10.jar
hk2-locator-2.3.0-b10.jar
hk2-utils-2.3.0-b10.jar
javassist-3.18.1-GA.jar
javax.annotation-api-1.2.jar
javax.inject-2.3.0-b10.jar
javax.servlet-api-3.0.1.jar
javax.ws.rs-api-2.0.1.jar
jaxb-api-2.2.7.jar
jersey-client.jar
jersey-common.jar
jersey-container-servlet.jar
jersey-container-servlet-core.jar
jersey-guava-2.12.jar
jersey-server.jar
org.osgi.core-4.2.0.jar
osgi-resource-locator-1.0.1.jar
persistence-api-1.0.jar
validation-api-1.1.0.Final.jar

STEP 3 : Create the following HelloWorld.java class.

package com.tutorialsdesk.rest.helloworld;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// Plain old Java Object it does not extend as class or implements 
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/helloworld")
public class HelloWorld {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello World REST Web Services !";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello World REST Web Services !" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello World REST Web Services !" + "</title>"
        + "<body><h1>" + "Hello World REST Web Services !" + "</body></h1>" + "</html> ";
  }

} 


This class register itself as a get resource via the @GET annotation. Via the @Produces annotation it defines that it delivers the text and the HTML MIME types. It also defines via the @Path annotation that its service is available under the hello URL.

The browser will always request the HTML MIME type. To see the text version, you can use tool like curl.
Define Jersey Servlet dispatcher

STEP 4 : You need to register Jersey as the servlet dispatcher for REST requests. Open the file web.xml and modify it to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TutorialsDesk.RestHelloWorld</display-name>
 <servlet>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
     <!-- Register resources and providers under com.tutorialsdesk.rest.helloworld package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.tutorialsdesk.rest.helloworld</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>REST Web Services Hello World</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 


The parameter jersey.config.server.provider.packages defines in which package Jersey will look for the web service classes. This property must point to your resources classes. The URL pattern defines the part of the base URL your application will be placed.

Run your rest service
You should be able to access your resources under the following URL: http://localhost:8080/TutorialsDesk.RestHelloWorld/rest/helloworld

This name is derived from the "display-name" defined in the web.xml file, augmented with the servlet-mapping URL-pattern and the helloworld @Path annotation from your class file. You should get the message "Hello World REST Web Services !".

This is a basic Hello World example of RESTful Web Services, Keep visiting TutorialsDesk for more tutorials and practical programming examples on Web Services in java.

Jersey RESTful Webservices Tutorial with examples
Hope we are able to explain you RESTful Web Services Hello World Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Web Services Tutorial With Examples

Many organizations use multiple software systems for management. Different software systems often need to exchange data with each other, and a web service is a method of communication that allows two software systems to exchange this data over the internet. The software system that requests data is called a service requester, whereas the software system that would process the request and provide the data is called a service provider.

Web Services

Web services are client and server applications that communicate over the World Wide Web’s (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML. Web services can be combined in a loosely coupled way to achieve complex operations. Programs providing simple services can interact with each other to deliver sophisticated added-value services.
Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language. For example, Java can talk with Perl, Windows applications can talk with UNIX applications.

Advantages Of Web Services

  • Reuse already developed(old) functionality into new software.
  • Web Services allow the business logic of many different systems to be exposed over the Web.
  • Web Services are virtually platform-independent.
  • Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas.
  • Ease of Integration
  • Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well defined protocol in the Web Services protocol stack.
  • Web Services uses HTTP protocol for the communication, so you can use your existing low cost internet for implementing Web Services.

Web Services Components

Web service has three main components:
  1. SOAP
  2. Simple Object Access Protocol (SOAP) is a communication protocol that communicates between applications without understanding the configuration and programming of any operating system and programming language. A program from one computer system can communicate with other program on another computer system within and beyond network using SOAP protocol on the Internet.
  3. WSDL
  4. Web Services Description Language (WSDL) is used to describe a web service in an XML file. It covers all the aspects of a web service like what is the message format, communication protocol, endpoint, security etc. This is a standard provided by W3C consortium and widely accepted for web services description. A wsdl xml file for a web service is generally expected to be published publicly so that parties seeking to utilize its services can understand the nature of service and consume it accordingly.
  5. UDDI
  6. UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery

Web service design approaches

There are two approaches in implementing a web service and they are bottom-up and top-down.

Bottom Up Approach

A developer using a bottom-up model writes implementing classes first (in some programming language), and then uses a WSDL generating tool to expose methods from these classes as a web service. This is simpler to develop but may be harder to maintain if the original classes are subject to frequent change.

Top Down Approach

A developer using a top-down model writes the WSDL document first and then uses a code generating tool to produce the class skeleton, to be completed as necessary. This model is generally considered more difficult but can produce cleaner designs and is generally more resistant to change. As long as the message formats between sender and receiver do not change, changes in the sender and receiver themselves do not affect the web service. The technique is also referred to as contract first since the WSDL (or contract between sender and receiver) is the starting point.

Web Services Tutorial With Examples
This is a basic theoretical explanation of Web Services, We will explain how to implement Web Services in java in next posts, Keep visiting TutorialsDesk for latest tutorials and practical programming examples on Web Services in java.

Hope we are able to explain you Web Services, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Java Atomic Operations And Nonblocking Algorithms Tutorial With Examples

Atomic operation

An operation during which a processor can simultaneously read a location and write it in the same bus operation. This prevents any other processor or I/O device from writing or reading memory until the operation is complete.

In Java, the reading and writing of 32-bit or smaller quantities are guaranteed to be atomic. By atomic we mean each action takes place in one step and cannot be interrupted.
For example, the following code is thread safe:
 
public class Counter
{
    private int x = 0;
    public void value()
    {
         return x;
    }
}
However, we should be careful to note that the guarentee applies only to reading and writing. For eg. check the following code snippet:
 
public void increment()
{
        ++this.value;
}

Although the above snippet looks to be atomic operation, it is not. The above instruction actually consists of three instructions:
  1. Read current setting of 'value'.
  2. Increment the setting.
  3. Write the new setting back.
Thus, the above code is not thread-safe. To add to the problem, this mistake is not very easily caught during testing due to two reasons:
  1. Threading bugs are difficult to detect and are time consuming.
  2. This code snippet might translate into a single instruction on some CPUs and thus work correctly. The problem might arise when tested with other JVMs.
Since Java 1.5 the java language provides atomic variables, e.g. AtomicIntegeror, AtomicLong which provide methods like getAndDecrement(), getAndIncrement() and getAndSet() which are atomic.

Atomic Variables

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables. To see how this package might be used, let's return to the Counter class:
 
public class Counter
{
    private int x = 0;

    public void increment()
    {
        ++this.value;
    }
    public void decrement()
    {
        --this.value;
    }
    public void value()
    {
         return x;
    }
}
One way to make Counter safe from thread interference is to make its methods synchronized, as in SynchronizedCounter:

 
public class SynchronizedCounter 
{
    private int x = 0;

    public synchronized  void increment()
    {
        ++this.value;
    }
    public synchronized  void decrement()
    {
        --this.value;
    }
    public synchronized  int value()
    {
         return x;
    }
}

For this simple class, synchronization is an acceptable solution. Now Counter is thread-safe, but the need to use a lock irks some developers because of the performance cost involved.

Nonblocking algorithms

Java 5.0 provides supports for additional atomic operations. This allows to develop algorithm which are non-blocking algorithm, e.g. which do not require synchronization, but are based on low-level atomic hardware primitives such as compare-and-swap (CAS). A compare-and-swap operation check if the variable has a certain value and if it has this value it will perform this operation.
Non-blocking algorithm are usually much faster then blocking algorithms as the synchronization of threads appears on a much finer level (hardware).

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
    private AtomicInteger c = new AtomicInteger(0);

    public void increment() {
        c.incrementAndGet();
    }

    public void decrement() {
        c.decrementAndGet();
    }

    public int value() {
        return c.get();
    }

}

java.util.concurrent.atomic package

All java.util.concurrent.atomic package classes have the "atomic" prefix in their names. There are different types of atomic variables available in the java.util.concurrent.atomic package, including:
  • AtomicBoolean
  • AtomicInteger
  • AtomicIntegerArray
  • AtomicIntegerFieldUpdater
  • AtomicLong
  • AtomicLongArray
  • AtomicLongFieldUpdater
  • AtomicReference
In the Java language, synchronization coordinates access to shared thread fields and only allows threads holding locks to access and modify variables protected by the lock. This thread’s modifications are visible to the thread that follows, but only after the thread releases the lock. An example is a scenario where thread A holds a lock. A is only able to access and make changes to variables protected by this lock. If thread B holds this lock after A, then only B can view A’s changes on the variables protected by that particular lock. The main problem with locking occurs when B attempts to acquire a lock held by A. In this case, B is blocked to wait until the lock is available. Nonblocking algorithms resolve this problem.
The main purpose behind building atomic classes is to implement nonblocking data structures and their related infrastructure classes. Atomic classes do not serve as replacements for java.lang.Integer and related classes. Most java.util.concurrent package classes use atomic variables instead of synchronization, either directly or indirectly. Atomic variables also are used to achieve higher throughput, which means higher application server performance.

Hope we are able to explain you java Atomic Operations, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Design Patterns Tutorial With Examples

Design patterns are a popular topic in software development. A design pattern is a common, well-described solution to a common software problem. Sensible use of design patterns results in increased code maintainability, since in addition to being a good solution to a common problem, design patterns can be recognized by other developers, thus reducing the learning curve when dealing with a particular piece of code.
Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.
Design patterns are proven solutions approaches to specific problems. A design pattern is not a framework and is not directly deployed via code.
Java Design Patterns

Design Pattern have two main usages:

  • Common language for developers: They provide developers a common language for certain problems. For example if a developer tells another developer that he is using a Singleton, the another developer (should) know exactly what this means.
  • Capture good practices: Design patterns capture solutions which have been successfully applied to problems. By learning these patterns and the related problem, an unexperienced developer learns a lot about software design.

Advantages of using design patterns are:

  1. Design patterns help you analyze the more abstract areas of a program by providing concrete, well-tested solutions.
  2. Design patterns help you write code faster by providing a clearer picture of how you're implementing the design.
  3. Design patterns encourage code reuse and accommodate change by supplying well-tested mechanisms for delegation and composition, and other non-inheritance based reuse techniques.
  4. Design patterns encourage more legible and maintainable code by following well-understood paths.
  5. Design patterns increasingly provide a common language and jargon for programmers.

Types of design patterns

Design Patterns can be divided into three categories – creational, structural, and behavioral design patterns.

Creational Design Patterns

There are five types of Creational Patterns.
  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Builder Pattern
  4. Prototype Pattern
  5. Singleton Pattern

Structural Design Patterns

There are seven structural patterns described. They are as follows:
  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

Behavioral Design Patterns

The behavioral patterns are:
  1. Chain of Resposibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Momento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern

Hope we are able to explain you Design Patterns, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Java Multi Threading Tutorial With Examples

Concurrency

Concurrency is the ability to run several programs or several parts of a program in parallel. If a time consuming task can be performed asynchronously or in parallel, this improve the throughput and the interactivity of the program.
A modern computer has several CPU's or several cores within one CPU. The ability to leverage these multi-cores can be the key for a successful high-volume application. Processes and Threads In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important.

Processes

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.

Threads

Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Java Multithreading

Every java application has at least one thread – main thread. Although there are so many other threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first thread and we can create multiple threads from it.
Multithreading refers to two or more threads executing concurrently in a single program. A computer single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different processes and threads.

Advantages of Using Threads

  • PerformanceThreads improve the performance (throughput, computational speed, responsiveness, or some combination of these) of a program.
  • Shared Resources An advantage of using multiple threads over using separate processes is that the former share a single address space, all open files, and other resources.
  • Potential Simplicity Multiple threads can reduce the complexity of some applications that are inherently suited for threads.

How to create Thread in java

Java provides two ways to create a thread programmatically.
  1. Implementing the java.lang.Runnable interface.
  2. Extending the java.lang.Thread class.

Java Thread Example by implementing Runnable interface

One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.

The procedure for creating threads based on the Runnable interface is as follows:

  1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
  2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
  3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
  4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
class MyThread implements Runnable {
  int count;

  MyThread() {
    count = 0;
  }
  public void run() {
    System.out.println("MyThread starting.");
    try {
      do {
        Thread.sleep(500);
        System.out.println("In MyThread, count is " + count);
        count++;
      } while (count < 5);
    } catch (InterruptedException exc) {
      System.out.println("MyThread interrupted.");
    }
    System.out.println("MyThread terminating.");
  }
}

class RunnableDemo {
  public static void main(String args[]) {
    System.out.println("Main thread starting.");
    MyThread mt = new MyThread();
    Thread newThrd = new Thread(mt);
    newThrd.start();
    do {
      System.out.println("In main thread.");
      try {
        Thread.sleep(250);
      } catch (InterruptedException exc) {
        System.out.println("Main thread interrupted.");
      }
    } while (mt.count != 5);

    System.out.println("Main thread ending.");
  }
}

Java Thread Example by extending Thread class

The procedure for creating threads based on extending the Thread is as follows:
  1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
  2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
  3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

class MyThread extends Thread {
  int count;

  MyThread() {
    count = 0;
  }

  public void run() {
    System.out.println("MyThread starting.");
    try {
      do {
        Thread.sleep(500);
        System.out.println("In MyThread, count is " + count);
        count++;
      } while (count < 5);
    } catch (InterruptedException exc) {
      System.out.println("MyThread interrupted.");
    }
    System.out.println("MyThread terminating.");
  }
}

public class Main {
  public static void main(String args[]) {
    System.out.println("Main thread starting.");
    MyThread mt = new MyThread();
    mt.start();
    do {
      System.out.println("In main thread.");
      try {
        Thread.sleep(250);
      } catch (InterruptedException exc) {
        System.out.println("Main thread interrupted.");
      }
    } while (mt.count != 5);
    System.out.println("Main thread ending.");
  }
}



Once we start any thread, it’s execution depends on the OS implementation of time slicing and we can’t control their execution. However we can set threads priority but even then it doesn’t guarantee that higher priority thread will be executed first.
Run the above programs multiple times and you will see that there is no pattern of threads start and end.

Difference between implementing Runnable and extending Thread?

One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.

A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target.

In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
When there is a need to extend a superclass, implementing the Runnable interface is more appropriate than using the Thread class. Because we can extend another class while implementing Runnable interface to make a thread. But if we just extend the Thread class we can't inherit from any other class.

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

Java Multi Threading
Above-mentioned stages are explained here:
  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
  • Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.

Hope we are able to explain you Java Multi Threading, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Synchronization and Thread Safety Tutorial with Examples in Java

We need to think about various issues that fall under the broad description of thread safety. Generally, we need to take steps to make sure that different threads don't interact in negative ways:
  • if one thread is operating on some data or structure, we don't want another thread to simultaneously operate on that same data/structure and corrupt the results;
  • when Thread A writes to a variable that Thread B accesses, we need to make sure that Thread B will actually see the value written by Thread A;
  • we don't want one thread to hog, take or lock for too long a resource that other threads need in order to make progress.
Code that is safe to call by multiple threads simultanously is called thread safe. If a piece of code is thread safe, then it contains no race conditions. Race condition only occur when multiple threads update shared resources. Therefore it is important to know what resources Java threads share when executing.

Local Variables

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.

Local Object References

Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads.

The only exception is of course, if one of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.

Object Members

Object members are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object members, the method is not thread safe.

How to make a method thread-safe in Java?

There are basically below approaches to make an object thread safe in java :
  • Using Synchronized keyword
  • Make it immutable
  • Use a thread safe wrapper
  • Using Concurrency Locks
  • Using volatile keyword

Thread Safety using Synchronized keyword

The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements.

Synchronized Methods

To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter {
    private int c = 0;
    public synchronized void increment() {
        c++;
    }
    public synchronized void decrement() {
        c--;
    }
    public synchronized int value() {
        return c;
    }
}

If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}


In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();
    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }
    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}


Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields.

Thread Safety using Immutable Objects

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.
Since the state of the immutable objects can not be changed once they are created they are automatically thread-safe.

How to create an immutable class?

To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private<\li>
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
public final class FinalPersonClass { 
      private final String name; 
      private final int age; 
      public FinalPersonClass(final String name, final int age) { 
            super(); 
            this.name = name; 
            this.age = age; 
      } 
      public int getAge() { 
            return age; 
      } 
      public String getName() { 
            return name; 
      }       
}


Thread Safety Using a Thread Safe Wrapper

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.
public static <t> Collection<t> synchronizedCollection(Collection<t> c);
public static <t> Set<t> synchronizedSet(Set<t> s);
public static <t> List<t> synchronizedList(List<t> list);
public static <k> Map<k> synchronizedMap(Map<k> m);
public static <t> SortedSet<t> synchronizedSortedSet(SortedSet<t> s);
public static <k> SortedMap<k> synchronizedSortedMap(SortedMap<k> m);


Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection. To guarantee serial access, all access to the backing collection must be accomplished through the returned collection. The easy way to guarantee this is not to keep a reference to the backing collection. Create the synchronized collection with the following trick.

List<type>>list = Collections.synchronizedList(new ArrayList<type>());

A collection created in this fashion is every bit as thread-safe as a normally synchronized collection, such as a Vector.

In the face of concurrent access, it is imperative that the user manually synchronize on the returned collection when iterating over it. The reason is that iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation. The following is the idiom to iterate over a wrapper-synchronized collection.
Collection<type> c = Collections.synchronizedCollection(myCollection);
synchronized(c) {
    for (Type e : c)
        foo(e);
}

Thread Safety using Concurrency Locks

A java.util.concurrent.locks.Lock is a thread synchronization mechanism just like synchronized blocks. A Lock is, however, more flexible and more sophisticated than a synchronized block.

Java Lock Example

Since Lock is an interface, you need to use one of its implementations to use a Lock in your applications. Here is a simple usage example:
Lock lock = new ReentrantLock();
lock.lock();
//critical section
lock.unlock();


First a Lock is created. Then it's lock() method is called. Now the Lock instance is locked. Any other thread calling lock() will be blocked until the thread that locked the lock calls unlock(). Finally unlock() is called, and the Lock is now unlocked so other threads can lock it.

Java Lock Implementations

The java.util.concurrent.locks package has the following implementations of the Lock interface:
  • ReentrantLock

Main Differences Between Locks and Synchronized Blocks

The main differences between a Lock and a synchronized block are:
  • A synchronized block makes no guarantees about the sequence in which threads waiting to entering it are granted access.
  • You cannot pass any parameters to the entry of a synchronized block. Thus, having a timeout trying to get access to a synchronized block is not possible.
  • The synchronized block must be fully contained within a single method. A Lock can have it's calls to lock() and unlock() in separate methods.

Thread Safety using volatile keyword

What is the Java volatile keyword?

Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
Declaring a volatile Java variable means:
  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

Differences between synchronized and volatile are:

  • a primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
  • an access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
  • because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
  • a volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).
Attempting to synchronize on a null object will throw a NullPointerException.

Hope we are able to explain you java synchronization and thread safety, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Synchronization and Thread Safety Tutorial with Examples in Java