JSESSIONID concept | what is JSESSIONID working concept in J2EE web application | JSESSIONID interview Question

JSESSIONID is generated by server (which contains servlet container) used for session management for web application because we allready know that HTTP protocal is sataless.

Many applications require a series of requests from a client to be associated with one another.Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. 

Java EE (or Web) developer should know, while browsing on a server, it keeps trace of some data about the browsing session in a server-side HttpSession object. For example an ecommerce web application needs to store somewhere the information about the shopping cart of non registered users.
 How the server can associate the remote session data with the specific navigation session? This is done through a cookie (or via a GET parameter in the URL) that gives to the server the session ID value.

In Java EE applications, the cookie name to identify the sessions is JSESSIONID.



Condition where  JSESSIONID created

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session, but not create it if it doesn't exists, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code is in control when the session is created)

Sessions are per-context:


SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.
 
(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates new session if there is no session yet. This can be turned off by session='false' page directive, in which case session variable is not available on JSP page at all.

JSESSIONID and session management very popular J2EE interview question .Apart from What is JSESSIONID interviewer are also interested in below interview question
How do you avoid using jsessionid?

  • Is it possible to disable jsessionid in tomcat servlet?
  • Under what conditions is a JSESSIONID created?
  • how to refresh JSESSIONID cookie after login?
  • How to monitor HTTP request to check JSESSIONID ?

JMS tutorial | Configuration JMS in Weblogic Application Server

steps to configure a sample JMS server that supports JTA. Suppose a weblogic server or cluster has already been created. Let's call it SampleServer.

  •     Create a Non-XA DataSouce
  •     Create a persistent JDBCStore. Use the non-XA DataSource created above. Don't forget to assign the store a prefix name, say 'Example'. A table ExampleWLStore should be created in the database if the configuration will be successful. Target the JDBCStore to SampleServer.
  •     Create a JMS server. Use the JDBCStore created above. Target it to SampleServer
  •     Create a JMS module. Target it to SampleServer
  •     In the JMS module, create subdeployment. Target the subdeployment to the JMS server.
  •     Create a Queue and a Queue Connection Factory in the JMS module and associate them with the subdeployment. Assign a JNDI name to the queue and the factory. Notice that when creating the queue connection factory, the xa-connection-factory-enabled flag should be set to 'true'.


Notes. It may be necessary to create the queue and the subdeployment and to target it to a JMS server. But you do not have to do this for connection factory. In the webblogic10 sample application medrec, you can see from the admin console that three queues are configured. But there is no connection factory. But JMS won't work without a factory. So where is the factory? The medrec source code reveals the secret. It turns out that weblogic has two predefined factories that can be used. The JmsClientImpl.java in medrec defines the following:

private String connectionFactoryName = "weblogic.jms.XAConnectionFactory";

Then the code uses this name as the JNDI name to look up the connection factory. For more information, look at the weblogic document on it.

Junit tutorial | Best Practices to write JUnit test cases in Java | Junit interview question

Introduction to JUnit Test

Uses
A framework for unit test. Used mainly to test individual classes and methods.

JUnit Library
In maven pom.xml:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>

The scope is "test". So the junit.jar will not be packaged into the application for deployment.
Configure Maven for Running JUnit
In maven pom.xml:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!--<skipTests>true</skipTests>-->
<testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>

If skipTests is true, no unit tests will be run.
If testFailureIgnore is true, the tests will be run and the build maven will succeed even if some tests fail.
If testFailureIgnore is false, the tests will be run and build will fail if a test fails.

The test results will go to the directory:
project_base_directory\target\surefire-reports

Traditional JUnit Test
The test class must extend the JUnit class TestCase or its subclasses.

    Use setUp() to initialize resources.
    Use tearDown() to release resources
    Every test method must start with the lowercase "test".

The lifecycle of a TestCase
The lifecycle of a TestCase used by the JUnit framework is as follows:

    Execute setUp().
    Call a test-prefixed method.
    Execute tearDown().
    Repeat these steps for each test method. This will occur even if setUp() or tearDown() throws an exception

Notes:
If setUp() throws an Exception, the test method and tearDown() will not be executed.
If the test method fails and throws an error or exception, tearDown() will still be executed.

Utility Methods from Assert

    assertTrue(String message, boolean condition)
    assertFalse(String message, boolean condition)
    fail(String message)
    assertEquals(String message, Object expected, Object actual)
    assertEquals(String message, String expected, String actual)
    assertEquals(String message, double expected, double actual, double delta)
    assertEquals(String message, int expected, int actual)
    assertSame(String message, Object expected, Object actual)
    assertNotNull(String message, Object object)
    assertNull(String message, Object object)

See the class junit.framework.Assert for more methods.

A Sample Class for Testing

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

public class Sound {
 private Map<String, String> voicemap = new HashMap<String, String>() {
  {
   put("bee", "buzz");
   put("cow", "moo");
   put("dog", "woof");
   put("cat", "meow");
   put("snake", "hiss");
   put("bird", "chir");
   put("goose", "honk");
  }
 };

 public String speak(String animal) throws Exception {
  if (animal == null) {
   throw new Exception("animial is not specified.");
  }
  String name = animal.toLowerCase();
  Set<String> animals = voicemap.keySet();
  if (!animals.contains(name)) {
   throw new Exception("not implemented yet for this animal.");
  }
  return voicemap.get(name);
 }

 public String yell(String animal) throws Exception {
  String sound = speak(animal);
  return sound.toUpperCase();
 }
}


A Sample JUnit Test Class

import junit.framework.TestCase;

public class SoundTest extends TestCase {

/* This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the setUp() method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 @Override
 protected void setUp() throws Exception {
  super.setUp();
  sound = new Sound(); 
 }

 @Override
 protected void tearDown() throws Exception {
  sound = null;
  super.tearDown();
 }

 public void testSpeak() throws Exception {
  String beeSound = sound.speak("bee");
  assertEquals("buzz", beeSound);
  try {
   String temp = sound.speak("fish");
   fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   assertEquals("The sound of goose is not right", "HONK", gooseYell);
  } catch (Exception e) {
   fail("Test failed. This statement should not have been reached.");
  }
 }
}


Run JUnit in Eclipse


Run JUnit Test On CommandLine
JUnit provides the TestRunner classes for running all the tests. The two most popular test runners are a text-based one, junit.textui.TestRunner, and a Swing-based one, junit.swingui.TestRunner

Example:
java junit.textui.TestRunner org.example.SampleTest

TestSuite
JUnit tests can be grouped together by using the TestSuite class.
Example:

import junit.framework.Test;
import junit.framework.TestSuite;

public class GroupTests extends TestSuite {
      static public Test suite() {
            TestSuite suite = new TestSuite();
             suite.addTestSuite(SimpleTest1.class);
             suite.addTestSuite(SimpleTest2.class);
             return suite;
    }
}


When this test is run, both SimpleTest1 and SimpleTest2 will be invoked.

Junit Test Using Annotation in JUnit4

    No need to extend the class TestCase
    No need to use setUp() or tearDown(). Use @Before and @After instead.
    The test method name does not need to start with "test". But you need to put the @Test annotation before each test method.
    Use @Test(expected = YourException.class) to test exception
    Can use @Test(timeout = ?) for performance testing. Here "?" is time in milliseconds.
    Can use @Ignore to ignore a test

Example Using Annotation

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class SoundAnnotationTest {

/** This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the @Before method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 /**
  * The method name does not have to be setUp. You can have multiple such
  * methods with the "Before" annotattion, each of which is run before each
  * test
  */
 @Before
 public void setUp() {
  sound = new Sound();
 }

 /**
  * The method name does not have to be tearDown. You can have multiple such
  * methods with teh "After" annotation, each of which is run after each
  * test.
  */
 @After
 public void tearDown() {
  sound = null;

 }

 @Test
 public void speak() {
  try {
   String beeSound = sound.speak("bee");
   Assert.assertEquals("buzz", beeSound);
  } catch (Exception e) {
   Assert.fail("Test failed.");
  }

  try {
   sound.speak("fish");
   Assert.fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 @Test
 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   Assert.assertEquals("The sound of goose is not right", "HONK",
     gooseYell);
  } catch (Exception e) {
   Assert.fail("Test failed. This statement should not have been reached.");
  }
 }

 @Test(expected = Exception.class)
 // IndexOutOfBoundsException.class
 public void testFish() throws Exception {
  sound.speak("fish");
 }

 @Test(timeout = 700)
 public void testPerformance() throws Exception {
  Thread.currentThread().sleep(600);
 }

 @Ignore
 public void foo() throws Exception {
  for (int i = 0; i < 10; i++) {
   // no-op
  }
 }
}


Use EasyMock in JUnit

    Create Mock object using EasyMock.createMock
    Mock expected results using EasyMock's expect and the andReturn()/andThrow() method
    You can use andReturn to return the value you want.
    You can use andThrow to throw any kind of exception you like.
    Call the EasyMock replay() method.
    Do test and check results.


Example Using EasyMock

(MyServiceEndpointTest)
fooServiceMock = createMock(FooService.class);
barServiceMock = createMock(BarService.class);
endPoint = new MarshallingCommonServiceEndpoint(barServiceMock,
    fooServiceMock);
expect(barServiceMock.getSomeInput(arg1, arg2)).andReturn(Boolean.TRUE);
replay(barServiceMock);
GetBarResponse response = endPoint.getBar(request);
assertTrue("Invalid status", response.isStatus());

IBM DB2 Tutorial : Db2 SQL Replication Steps with example . How to replicate data in db2 step by step

One of the very helpful and important feature in db2 is Replication technique. Replication technique allows you to copy data from one location to another location making the second location data identical to the first location. Data can be copied either in the local or remote machine .Replication is useful1. To consolidate data from multiple sources in a distributed environment
2. to support basic load balancing when your server is running many more read queries (SELECT) than write queries (insert / update / delete) .
3. Makes a backup of data in the local / remote which helps for disaster recovery
4. to reduce delay and bring the data closer to the user.

DB2 Universal Database (UDB), supports two types of replication.
SQL Replication can be done using Control center and Scripting language called ansclp .SQL replication capability is included in the base product. From the Control Center you can access the Replication Center, a graphical interface for the setup of replication. There is also a scripting language for replication called ansclp which allows you to create scripts to automate replication setup.

This tutorial overs that how to setup replication using the the Replication Center . You can access the Replication Center using Control Center -> Tools -> Replication Center.

What happens when we do replication.
Two programs are involved. Capture Program and Apply Program .Capture program capture the data changes in the source table to the CD Table . Changes of data in the source tables are captured in a CD Tables . When we insert new rows in the source table , new rows are captured in the CD Tables with flag "I" . When we update data in the source table , the updated rows are captured in the CD Tables with the flag "U" . SImilarly , When we delete data in the source table , the deleted rows are captured in the CD Tables with the flag "D" . Apply Program , replicate the the data changes captured in the CD table to the target tables.

Major Steps for replication :

1. Create control tables for the Capture program

2. Enable the source database for replication (i.e. to enable logretain on for archival log)

3. Register source tables

4. Create control tables for the Apply program

5. Create a subscription set and member

6. Start the operation to capture and apply

7. Testing the Replication


1. Create control tables for the Capture program
To Create table space and control tables do the following step
1. Right click on the Create Control Servers -> Select Create Capture Control Tables -> Select Custom
2. Select Capture control server (Source database) to create Capture Control Tables
Give user name and password and select Run then OK.

Now Capture control tables are created

2. Enable the source database for replication
Right click on the Source database name (Capture control server ) to enable database for replication . that means to enable archive logging .

Press ok button to set the LOGRETAIN value for the database to RECOVERY and initiate offline backup for the db and take full backup of db


3. Register a replication source

a) Before registering source tables , specify the schema and table name and table space to be used for the CD (Capture Data) tables

Right click on the Capture control server and Source database name and select Manage Source Object Profile

You can specify here
i) table schema and table name to be used as the defaults for the CD tables
ii) table space & its properties for the CD tables and naming convention for table spaces
iii) schema and name for the CD table indexes & naming convention for the the index name.


b) To register source tables
1. Select Capture control servers - > Source database -> capture schemas -> schema name.
2. Right click on the schema name and select Register tables
3. Select Retrive All to retrive all source tables and select the table you want to register. Now CD (Capture Data) table name and table space details appeared automatically based on the settings in the previous steps (i.e. 3 a)

4. Then Ok which will run the query .

4. Create control tables for apply program

To create control tables for apply program , Right click on Apply Control Server -> Create Apply Control Tables -> custom

Select the target database where the data to be replicated . Then Ok.

5. Create Subscription Sets
A subscription set defines a relationship between the source database (ORI_DB in our example) and a target database (DUP_DB in our example). A subscription-set member defines a relationship between the source table (SALES) and one or more target tables (TGSALES).

Here you have to specify , set information , source to target mapping , schedule time to replicate data.

Steps to do :
To create subscription sets , Expand Apply control server -> Right click on the newly created Apply control server ( target data base) -> Subscritption sets
Now you have to fill / select all the details like Apply control server , Set Name , Apply Qualifier , Capture control server and target server (Target database)
Check on the activate the subscription set

Now do the source to target mapping , which maps the source colums to target columns to replicate the data .

Now Set the replication schedule (Time based / event based) , Then Ok.

Now let us Add Members

Right click on the newly created set , select the member information tab and add the member using retrive all option . Use change to do column mapping and etc... Please add the column for index for target table using target table table . Then Ok.

Now the target table is created in the target server where the data to be replicated .

6. Finally Let us start the operation to capture and apply

To start Capture , Expand the operations on SQL replication under Replication center

Right click on the capture control servers and select add and give the capture control server already created (target database) , userid and password which adds capture control servers for operations

Right click on the capture control servers which is added now , then select start capture , then select capture schema , then Ok.
Now give user name and password for the database server to access

Similarly you can stop , resume or suspend capture later.

To start Apply Program
Similarly Expand the apply control servers under operations , Right click on the apply control server -> Apply qualifiers , then refresh .

Now right click on the apply qualifiers already created and the select start Apply , give Host Name or IP Address , then Ok. Now give your target server details by clicking Add New System ..


Similarly you can stop apply , if you need ..


7. Now test the replication ....
Insert any record to the source table

Now the new record is captured in the CD Table (In our example : CDSALES) with the flag (IBMSNAP_OPERATION) with following values

'I' - Insert operation tbe done on the target table.
'U' - Update operation to be done
'D' - Delete Operation to be done

Finally the changes captured in the CD table is applied in the target table by the apply program.



Note : I have created Capture control server and Apply control server on the same system.

Converting InputStream to String | Java IO tutorial InputStream to String Conversion Example | Java interview topic


Read full Article before leave thr blog.  It will really helpfull for Java Interview on IO topic 


 If you like the post please do comments 
 
Converting InputStream to String in Java has become very easy after introduction of Scanner class in Java 5 and due to development of several open source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String  while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in log file or want to operate on whole String. Before Java 5 you would have to write lots of boiler plate code to read String line by line or byte by byte depending upon whether you are using either BufferedReader or not but as I said since JDK 5 added Scanner for reading input, its fairly easy to convert InputStream into String.


Before Converting any InputStream or ByteStream into String don't forget to provide character encoding or charSet which tells Java Which characters to expect from those streams of bytes. in the absence of correct character encoding you might alter the output because same bytes can be used to represent different character in different encoding. Another thing to keep in mind is that if you don't provide character encoding, Default character encoding in Java will be used which can be specified from System property "file.encoding" or "UTF-8" if file.encoding is not specified. In this Java tutorial we will see 5 different example of converting InputStream to String in Java both by using standard JDK libraries and using open source libraries.

How to convert InputStream to String in Java – 5 Examples
here are different ways to convert InputStream to String in Java, first we will see most simple way of reading InputStream as String.

InputStream to String -  Using Java 5 Scanner
Convert InputStream to String in Java - 5 Example tutorialjava.util.Scanner has constructor which accept an InputStream, a character encoding and a delimiter to read String from InputStream. Here we have used delimiter as "\A" which is boundary match for beginning of  the input as declared in java.util.regex.Pattern and that's why Scanner is returning whole String form InputStream. I frequently use this technique to read input from user in Java using System.in which is most common example of InputStream in Java, but as demonstrated here this can also be used to read text file in Java.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Java program example to demonstrate How to convert InputStream into String by using JDK
 * Scanner utility. This program will work Java 5 onwards as Scanner was added in Java 5.
 */       
public class InputStreamTest {

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);
    }
}

Output:
This String is read from InputStream by changing InputStream to String in Java.

If you want to see how an incorrect character encoding completely changes the String just change the character encoding form "UTF-8" to "UTF-16" and you see Chinese(may be) characters instead of English.

Output:
?????????????!???????????!??????^(4)????????

Convert InputStream to String - Plain old JDK4 Example
If you still need to do it on plain old Java on JDK4 without including any additional dependency in your PATH and Classpath than here is quick example using BufferedReader in Java, Remember you can also do this by reading byte by byte from InputStream but that's very slow so consider using BufferedReader for better performance even if you code on JDK4 . For more performance tips see my post 4 JDBC performance tips in Java program. Let’s see example of converting InputStream to String using BufferedReader in Java.

/**
 * Java program to demonstrate How to read InputStream as String
 * using BufferedReader and StringBuilder in Java.
 * This is old and standard way of converting an InputStream into String in Java
 */
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        String line = bufferedReader.readLine();
        while(line != null){
            inputStringBuilder.append(line);inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        System.out.println(inputStringBuilder.toString());

}
Output:
This String is read from InputStream by changing InputStream to String in Java.
second line


This is good plain old Java method of converting InputStream to String without adding any extra dependency but remember its converting \r to \n because we are reading line by line, which in most cases fine.

Read InputStream to String - Using Apache IOUtils library
As I said earlire there are many open source library in Java which makes coding lot more easier than any other language. Here is code example for How to convert InputStream to String in Java using Apache IOUtils

/**
 * Example of How to read InputStream into String by using Apache IOUtils library.
 * Nice and clean way of getting InputStream as String in Java
 */

FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);

Isn't it a compact way of converting InputStream to String in Java, just one line of code and that does take care of character encoding as well..

InputStream to String - Using Google's guava-libraries
Google has open source its own set of Java libraries they use for Java development inside Google. it has lots of utility function and also complements Apache commons package. Here is a quick way of converting InputStream to String using Google libraries:

String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));

Regarding dependency, You need to include guava library i.e. guava-11.0.1.jar in your project classpath. here is full code example:

import com.google.common.io.CharStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * How to convert InputStream into String in Java using Google's Guava library
 */
public class InputStreamToString{

    public static void main(String args[]) throws UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
        System.out.println(stringFromStream);
    }   
}

How to read InputStream into String with IOUtils.copy and StringWriter class
java.io.StringWriter is another convenient way of reading writing Strings and by using IOUtils.copy() you can copy contents form InputStream to reader, Here is a complete code example of reading InputStream as String using StringWriter:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;

/**
  * Java Program to demonstrate reading of InputStream as String
  * using StringWriter and Apache IOUtils
  */
public class InputStreamToStringConversion{

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringWriter writer = new StringWriter();
        String encoding = "UTF-8";
        IOUtils.copy(fis, writer, encoding);
        System.out.println(writer.toString());
    }
}

That's all on converting InputStream to String in Java by using standard core java library and by using open source Apache commons IOUtils and Google's guava libraries. Don't forget Character encoding when converting bytes to String which is case here also make a convenient choice as sometime adding additional library for one functionality is not the best option. let us know if you know any other way of converting InputStream to String in Java.

Core concept of Volatile keyword in java multithreading | Java concurrency tutorial

Read full Article before leave thr blog.  It will really helpfull for Java Interview on multithreading topic

First, you have to understand a little something about the Java memory model. I've struggled a bit over the years to explain it briefly and well. As of today, the best way I can think of to describe it is if you imagine it this way:


  •     Each thread in Java takes place in a separate memory space (this is clearly untrue, so bear with me on this one).

  •     You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.

  •     Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication, you can't guarantee which writes get seen by other threads, or even the order in which they get seen.

The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

At this point, I usually rely on a visual aid, which we call the "two cones" diagram, but which my officemate insists on calling the "two trapezoids" diagram, because he is picky. ready is a volatile boolean variable initialized to false, and answer is a non-volatile int variable initialized to 0.




The first thread writes to ready, which is going to be the sender side of the communications. The second thread reads from ready and sees the value the first thread wrote to it. It therefore becomes a receiver. Because this communication occurs, all of the memory contents seen by Thread 1, before it wrote to ready, must be visible to Thread 2, after it reads the value true for ready.

This guarantees that Thread 2 will print "42", if it prints anything at all.

If ready were not volatile, what would happen? Well, there wouldn't be anything explicitly communicating the values known by Thread 1 to Thread 2. As I pointed out before, the value written to the (now non-volatile) ready could "leak through" to Thread 2, so Thread 2 might see ready as true. However, the value for answer might not leak through. If the value for ready does leak through, and the value for answer doesn't leak through, then this execution will print out 0.

We call the communications points "happens-before" relationships, in the language of the Java memory model.

(Minor niggle: The read of ready doesn't just ensure that Thread 2 sees the contents of memory of Thread 1 up until it wrote to ready, it also ensures that Thread 2 sees the contents of memory of any other thread that wrote to ready up until that point.)



With this in mind, let's look at the Double-Checked Locking example again. To refresh your memory, it goes like this:


class Foo {
  private volatile Helper helper = null;
  public Helper getHelper() {
    if (helper == null) {
      synchronized(this) {
        if (helper == null) {
          helper = new Helper();
        }
      }
    }
  return helper;
}

The object of the double-checked locking pattern is to avoid synchronization when reading a lazily constructed singleton that is shared between threads. If you have already constructed the object, the helper field will not be null, so you won't have to perform the synchronization.

However, this is only part of the solution. If one thread creates the object, it has to communicate the contents of its memory to another thread. Otherwise, the object will just sit in the first thread's memory. How do we communicate the contents of memory to another thread? Well, we can use volatile variables. That's why helper has to be volatile -- so that other threads see the fully constructed object.

Locking in Java also forms these "happens-before" communication points. An unlock is the sender side, and a lock on the same variable is the receiver side. The reason that doesn't work for (non-volatile) double-checked locking is that only the writing thread ever performs the locking. The whole point of the idiom is that the reader side doesn't do the locking. Without the explicit communication in the form of the volatile variable, the reading thread will never see the update performed by the writer thread.

Java concurrency tutorial : CountDownLatch Example in Java - Concurrency Tutorial | Java multithreading tutorial

Java CountDownLatch Example
CountDownLatch in Java is a kind of synchronizer which allows one Thread  to wait for one or more Threads before starts processing. This is very crucial requirement and often needed in server side core Java application and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. In this Java concurrency tutorial we will  what is CountDownLatch in Java, How CountDownLatch works in Java, an example of CountDownLatch in Java and finally some worth noting points about this concurrent utility. You can also implement same functionality using  wait and notify mechanism in Java but it requires lot of code and getting it write in first attempt is tricky,  With CountDownLatch this can  be done in just few lines. CountDownLatch also allows flexibility on number of thread for which main thread should wait, It can wait for one thread or n number of thread, there is not much change on code.  Key point is that you need to figure out where to use CountDownLatch in Java application which is not difficult if you understand What CountDownLatch do and How CountDownLatch works.


How CountDownLatch works in Java
CountDownLatch Example in Java 5 6 7CountDownLatch works in latch principle,  main thread will wait until Gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Any thread, usually main thread of application,  which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such requirements.

CountDownLatch Exmaple in Java
In this section we will see a full featured real world example of using CountDownLatch in Java. In following CountDownLatch example, Java program requires 3 services namely CacheService, AlertService  and ValidationService  to be started and ready before application can handle any request and this is achieved by using CountDownLatch in Java.

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How to use CountDownLatch in Java. CountDownLatch is
 * useful if you want to start main processing thread once its dependency is completed
 * as illustrated in this CountDownLatch Example
 *
 *
 */
public class CountDownLatchDemo {

    public static void main(String args[]) {
       final CountDownLatch latch = new CountDownLatch(3);
       Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
       Thread alertService = new Thread(new Service("AlertService", 1000, latch));
       Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
    
       cacheService.start(); //separate thread will initialize CacheService
       alertService.start(); //another thread for AlertService initialization
       validationService.start();
    
       // application should not start processing any thread until all service is up
       // and ready to do there job.
       // Countdown latch is idle choice here, main thread will start with count 3
       // and wait until count reaches zero. each thread once up and read will do
       // a count down. this will ensure that main thread is not started processing
       // until all services is up.
    
       //count is 3 since we have 3 Threads (Services)
    
       try{
            latch.await();  //main thread is waiting on CountDownLatch to finish
            System.out.println("All services are up, Application is starting now");
       }catch(InterruptedException ie){
           ie.printStackTrace();
       }
    
    }
 
}

/**
 * Service class which will be executed by Thread using CountDownLatch synchronizer.
 */
class Service implements Runnable{
    private final String name;
    private final int timeToStart;
    private final CountDownLatch latch;
 
    public Service(String name, int timeToStart, CountDownLatch latch){
        this.name = name;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }
 
    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println( name + " is Up");
        latch.countDown(); //reduce count of CountDownLatch by 1
    }
 
}

Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now

By looking at output of this CountDownLatch example in Java, you can see that Application is not started until all services started by individual Threads are completed.
When should we use CountDownLatch in Java :
Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete, before its start doing processing. Classical example of using CountDownLatch in Java  is any server side core Java application which uses services architecture,  where multiple services is provided by multiple threads and application can not start processing  until all services have started successfully as shown in our CountDownLatch example.


CountDownLatch in Java – Things to remember
Few points about Java CountDownLatch which is worth remembering:

1) You can not reuse CountDownLatch once count is reaches to zero, this is the main difference between CountDownLatch and CyclicBarrier, which is frequently asked in core Java interviews and multi-threading  interviews.

2) Main Thread wait on Latch by calling CountDownLatch.await() method while other thread calls CountDownLatch.countDown() to inform that they have completed.

That’s all on CountDownLatch example in Java. This is a very useful concurrency utility and if you master when to use CountDownLatch and how to use CountDownLatch you will be able to reduce good amount of complex concurrency control code written using wait and notify in Java.