Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, December 3, 2016

Static Keyword in Java


The main purpose of static keyword in java is  memory management.
 The  static keyword can be used  in each of the  five cases.

  1.  static variables
  2.  static methods
  3.  static block
  4.  static nested class
  5.  Interface  static method(java 8 onward)

  • STATIC VARIABLES


In Java Variables can be declared with the “static” keyword.When a variable is declared with the keyword static, its called a class variable. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create an instance.

Example: static int i = 0;

ADVANTAGE OF STATIC VARIABLE

It makes your program memory efficient (i.e it saves memory).
now let us execute a program without static variable.
Suppose there are 1500 students in a college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.if we don't  use static keyword at the variable college  then for all 1500 students the huge amount of memory space will be used which is not a good programming practice.
    class Student{
         int rollno;
         String name;
         String college="XYZ";
    }
program using static variable

package com.brainatjava.test;

public class Student {

   static String college ="XYZ";   int rollno;   String name;
  Student(int r,String n){   rollno = r;   name = n;   }
void display (){
System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){ Student s1 = new Student(10,"Rabi"); Student s2 = new Student(20,"Rohit");
s1.display(); s2.display(); } }
OUTPUT
10 Rabi XYZ
20 Rohit XYZ


  •  STATIC METHOD


Static Methods can access class variables without using object of the class. It can access non-static methods and non-static variables by using objects. Static methods can be accessed directly in static and non-static methods.

EXAMPLE OF STATIC METHOD
public class Test1 {
static int i =10;

 //Static method
 static void display()
 {
    //Its a Static method
    System.out.println("i:"+Test1.i);
 }

 void foo()
 {
     //Static method called in non-static method
     display();
 }
 public static void main(String args[]) //Its a Static Method
 {
     //Static method called in another static method
     display();
     Test1 t1=new Test1();
      t1.foo();
  }
}

OUTPUT
i:10
i:10

STATIC BLOCK


   It is used to initialize the static data member.It is executed before main method at the time of classloading.A class can have multiple Static blocks, which will execute in the same sequence in which they have been written in the program.

EXAMPLE  OF SINGLE STATIC BLOCK

public class ExampleOfStaticBlock {
static int i;
  static String str;
  static{
     i =30;
     str = "welcome to BrainAtJava";
  }
  public static void main(String args[])
  {
     System.out.println("Value of i="+i);
     System.out.println("str="+str);
  }
}
OUTPUT
Value of i=30
str=welcome to BrainAtJava

EXAMPLE OF MULTIPLE STATIC BLOCK


public class ExampleOfMultipleStaticBlock {
static int i1;
static int i2;

  static String str1;
  static String str2;

  //First Static block
  static{
     i1 = 70;
     str1 = "Hello";
 }
 //Second static block
 static{
     i2= 55;
     str2 = "java";
 }
 public static void main(String args[])
 {
 System.out.println("Value of i1="+i1);
 System.out.println("Value of str1="+str1);

          System.out.println("Value of i2="+i2);
     System.out.println("Value of str2="+str2);
 
   
  }
}
OUTPUT
Value of i1=70
Value of str1=Hello
Value of i2=55
Value of str2=java

Static Nested Class:

A static nested class in Java is simply a class scoped within another class.
We can think of it as the static members of the enclosing class.
We can access it without creating an instance of the outer class.Simple it can be accessed by outerclass.innerclass.We can follow the below example.

A static nested class in Java serves a great advantage to namespace resolution.  For example, if we have a class with an  common name, and in a large project, it is quite possible that some other programmer has the same idea, and has a class with the same name you had, then we  can solve this  name clash by making our class a public static nested class. And our class will be written as outer class, followed by a period (.) and then followed by static nested class name.

Let's take an example

 class Outernormal
{
    private int var = 20;
    private static int staticVar = 50;
    public static void staticmethod(){
   System.out.println(var);//Error: Cannot make a static reference to the non-static field mem
   System.out.println(staticVar);
    }
    static class InnerStatic
    {
        public void getFields ()
        {
            System.out.println(var); //Error: Cannot make a static reference to the non-static field mem
            System.out.println(staticVar);
        }
    }
}

public class StaticClassDemo
{
    public static void main(String[] args)
    {
        OuterStatic.InnerStatic is = new OuterStatic.InnerStatic();
        is.getFields();
    }
}

Interface  static method(java 8 onward):

 In Java8 onwards , we can define static methods in interface ,but we can’t override them in the implementation classes.

This  helps us in avoiding undesired results in case of wrong implementation of interface.

It is good for providing utility methods,for example any precondition  check.

It provides security by not allowing implementing classes to override them.

Let's see code sample below.
public interface MyInf {

 static boolean checkIfNull(String str) {
  System.out.println("Interface Null Check");

  return str == null ? true : false;
 }
}

Wednesday, June 15, 2016

Usage of Java streams

In part1 of these series we saw basics of java stream.Now we discuss how to use the streams along with some important operations on it. Now let's see different ways to create streams.

Create streams from existing values:

There are two methods in stream interface to create stream from a single value and multiple values.

Stream stream = Stream.of("test");
Stream stream = Stream.of("test1", "test2", "test3", "test4");

Create empty stream :


Stream stream = Stream.empty();

Create Stream from function:

We can generate an infinite stream from a function that can produce infinite number of elements if required.There are two static methods iterate and generate in Stream interface to produce infinite stream.

 Stream iterate(T seed, UnaryOperator f)
 Stream generate(Supplier s);
The iterator() method takes two arguments: a seed and a function. The first argument is a seed that is the first element of the stream. The second element is generated by applying the function to the first element. The third element is generated by applying the function on the second element and so on.

The below example creates an infinite stream of natural numbers starting with 1.


Stream<Integer> naturalNumbers = Stream.iterate(1, n -> n + 1);
The generate(Supplier<T> s) method uses the specified Supplier to generate an infinite sequential unordered stream.Here Supplier is a functional interface, so we can use lambda expressions here.Lets see the below example to
generate an infinite stream of random numbers.Here we use method reference to generate random numbers.Please follow the series method reference( double colon perator) if you are not aware about it.

Stream.generate(Math::random).limit(5).forEach(System.out::println);

Create Stream from Collections:

Collection is the data-source we usually use for creating streams.The Collection interface contains the stream() and parallelStream() methods that create sequential and parallel streams from a Collection.

Example

Set nameSet = new HashSet<>();

//add some elements to the set

nameSet.add("name1");

nameSet.add("tes2");

//create a sequential stream from the nameSet

Stream sequentialStream = nameSet.stream();

// Create a parallel stream from the  nameSet

Stream parallelStream = nameSet.parallelStream(); 

Create Streams from Files:

Many methods are added to classes in java.io and java.nio.file  package in java 8 to facilitate IO operations by using streams.Let's see the example to read the content of the file using stream.

Path path = Paths.get(filePath);

Stream lines = Files.lines(path);

lines.forEach(System.out::println);
the method lines() added in Files class in java  1.8.Read all lines from a file as a Stream.

Stream Operations:

Now we will go through with some commonly used stream operations and their usage.
  1. Distinct
  2. filter
  3. flatMap
  4. limit
  5. map
  6. skip
  7. peek
  8. sorted
  9. allMatch
  10. anyMatch
  11. findAny
  12. findFirst
  13. noneMatch
  14. forEach
  15. reduce
Operations 1 to 8 are intermediate operations and 9 to 15 are terminal operations.  As some of the operations are self explanatory , so we discuss about those which are not trivial.

 

Map Operation:

                                                              

A map operation applies a function to each element of the input stream to produce another stream ( output stream ).The number of elements in the input and output streams are same. So this is a one to one mapping.The above figure shows the mapping.It take the element e1 and  apply function f on it to get f(e1) and so on.But  the type of elements in the  output stream may be different from  the type of elements in the input stream.Let's take an example.                                                                                                                         


Suppose  we have 1000 keys with values in redis data store and we want to fetch all the values of those keys and then we will perform some operation on them.We want to do it with future object,So how will we do it parallely with java  Stream.We will use thread pool service here to fetch the data from redis.Suppose our uniqueItemids List contains the list of keys.             

HashOperations redisHash=redisTemplate.opsForHash();

ExecutorService threadPoolService=Executors.newFixedThreadPool(10);

uniqueItemIds.

stream().

parallel().


map(itemId-> threadPoolService.submit(new Callable()) .forEach(future->{


try {


return future.get();


} catch (Exception e) {


e.printStackTrace();


return null;


}
Here the code in the callable's call method will be to fetch the data from redis with the specified item id.As we know the submit will return us the future object ,so map operation here takes an itemid which is of type long and return us an object of type future.Here I am emphasizing the point that  "the type of elements in the  output stream returned by the map operation may be different from the  type of elements in the input stream"

flatMap Operation:     

Unlike the map operation ,the Streams API  supports one-to-many mapping   through the flatMap.The mapping function takes an element from the input stream and maps the  element to a stream. The type of input element and the elements in the mapped    stream may be  different.This step produces a stream of streams.If the input stream is a Stream<T>  then the
mapped stream will be  Stream<Stream<R>> But which is  not   desired.Assume we have a map with below structure.

Map>> itemsMap = new ConcurrentHashMap<>()

//Now let's fill the map with some values.

itemsMap.put(2,  new ConcurrentHashMap<>());

itemsMap.put(3, new ConcurrentHashMap<>());

itemsMap.get(2).put(1L, Arrays.asList("abc","cde","def","rty"));

itemsMap.get(2).put(2L, Arrays.asList("2abc","2cde","2def","2rty"));

itemsMap.get(2).put(3L, Arrays.asList("3abc","3cde","3def","3rty"));

itemsMap.get(3).put(1L, Arrays.asList("abc3","cde3","def3","rty3"));

Now our aim is to get all the lists of strings in a stream.How can we achieve it?

A immediate solution comes to mind   is to write like below.

itemsMap.values().stream().parallel().map(m->m.values().stream()).forEach(System.out::println);

 Now we get the output as follows

java.util.stream.ReferencePipeline$Head@4eec7777
java.util.stream.ReferencePipeline$Head@3b07d329

We are expected to see list of strings in the output.But we don't find that.This is because of inside the map Stream of String is produced and we give Stream<Stream<String>> as the input to foreach.So we get the result.

Now our next attempt like this


itemsMap.

values().

stream().

parallel().

map(m->m.values().

stream()).

forEach(e->e.forEach(System.out::println));
And the output is   :

[abc, cde, def, rty]
[2abc, 2cde, 2def, 2rty]
[3abc, 3cde, 3def, 3rty]
[abc3, cde3, def3, rty3]

We are able to find all our Strings together but observe that they are still Stream<Stream<String>>  .Just we managed to write it in a different way in the for each loop.

The correct approach to our problem is


itemsMap.

values().

stream().

parallel().

flatMap(m->m.values().

stream()).

forEach(System.out::println);
So here comes the flatMap to the rescue.It flattens the Stream<Stream<String>>  and convert it into Stream<String>    .So make sure to use flatMap when you get Stream<Stream<T>>                     

We will discuss some other important operation in series 3.

Monday, June 13, 2016

Java URL Connection Timeout (http,ftp,scp etc) setting in system level

Sometimes we face issues like the thread , which trying to connect the url ,hangs for infinite time. The connection may be over http,ftp or scp protocol.But really it is painful to debug the issue.But there are some system level configuration provided by java, so that we can  we can solve this problem.

So lets start with some simple definitions.

ConnectionTimeOut:


The timeout (in milliseconds) to establish the connection to the host.For example for http connections it is the timeout when establishing the connection to the http server. For ftp connection it is the timeout when establishing the connection to ftp servers.For scp connection it is the time out for establishing the scp connection.

The property provided by sun for connectionTimeOut is

sun.net.client.defaultConnectTimeout (default: -1)

Note that here -1 means infinite timeout.

ReadTimeOut:


The timeout (in milliseconds) when reading from input stream when a connection is established to a resource.It is the timeout between two consecutive packets from the socket.

The property provided by sun for readTimeOut is

sun.net.client.defaultReadTimeout (default: -1)


Retry If Post Fails:


It determines if an unsuccessful HTTP POST request will be automatically resent to the server. Unsuccessful post means  in this case  the server did not send a valid HTTP response or an IOException occurred.And it defaults to true in system level.

The property provided by sun for retry post fails is  
sun.net.http.retryPost (default: true)
 
 
 We can use it in system level to configure a global connection time out or  read time out setting.We can give the time out in the client , which is used to make the http call.For example apache http client.But it is important to note  that , these are sun implementation specific properties and these properties may not be supported in future releases.

We can set the property like

-Dsun.net.client.defaultReadTimeout =timeinmiliseconds
-Dsun.net.client.defaultReadTimeout =timeinmiliseconds
-Dsun.net.http.retryPost =false

For more details please follow the oracle doc.

Saturday, June 4, 2016

NIO.2 Asynchronous file I/O with Future and CompletionHandler

Recently I had a requirement to work with lot of I/O type of work and at the same time a lot of computation.So what Immediately a solution comes to mind that we will start a configurable number of threads.And the job of each thread will do the I/O independently and then after start the computation.But here one thing to observe that my computation has a very little to do with  the I/O.But in this design  my thread is not doing any  useful when it is doing the I/O and after the completion of the I/O the thread is going for computation.But it would be great if my thread can be free once it starts the I/O and without waiting to complete the I/O  jumps to the computation part.And some one  informs my thread once the I/O  completes.Till that my thread is busy with doing some useful calculation.

So here we get the two benefits.My thread is not waiting for I/O to complete and at the same time , it is doing some useful calculation.Here note that the job of my thread is both I/O bound and CPU bound.

Asynchronous  I/O :


NIO.2 provides support for  asynchronous  I/O(connecting, reading, and writing). In a synchronous  I/O, the thread that requests the I/O operation waits until the I/O operation  completes.In an asynchronous  I/O, the  application requests the system for an I/O operation and the operation is performed by the system asynchronously. When the system is performing the  I/O operation, the application continues doing some other useful computation  work. When the system finishes the  I/O, it notifies the application about the completion of I/O operation.


Four asynchronous channels are added in NIO.2 (java 7) to the java.nio.channels package:

  •     AsynchronousSocketChannel
  •     AsynchronousServerSocketChannel
  •     AsynchronousFileChannel
  •     AsynchronousDatagramChannel
       
Here  we take AsynchronousFileChannel  as our example and try to understand the asynchronous I/O.

The AsynchronousFileChannel provides us two different ways for monitoring and controlling the initiated asynchronous operations.

 The first one is by returning a java.util.concurrent.Future object, which poses a Future object and can be used to enquire its state and obtain the result.It follows a poll type approach.

The second is by passing to the  I/O operation an object of a new class, java.nio.channels.CompletionHandler, which defines handler methods that are executed after the operation is completed.It follows a push type approach.

Each method of the AsynchronousFileChannel class that supports asynchronous file I/O operation has two versions.One for Future object and another for CompletionHandler object.

Example of poll approach using Future object:



package com.brainatjava.test;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Future;

public class AshyncronousIOWithFuture {
static String str="write some meaning full text to file,which is desired for your applications.";
        public static void main(String[] args) {
        long startPosition=0;
        Path path = Paths.get("/home/brainatjava/mytest");
        try (AsynchronousFileChannel asyncFileChannel =
         AsynchronousFileChannel.open(path, WRITE, CREATE)) {
        ByteBuffer dataBuffer = ByteBuffer.wrap(str.getBytes());
        Future result = asyncFileChannel.write(dataBuffer, startPosition);
        while (!result.isDone()) {
        try {
        //remember in real life scenario the initiating thread will not sleep but it will  do some useful work.
        System.out.println("Sleeping for one seconds before the next pooling.We will continue to keep pooling in each one second.");
        Thread.sleep(1000);
        }
        catch (InterruptedException e) {
        e.printStackTrace();
        }
        }
       
        System.out.println("Now I/O operation is complete and we are going to get the result.");
        try {
        int resultbytewritten = result.get();
        System.out.format("%s bytes written to %s%n",
        resultbytewritten, path.toAbsolutePath());
        }
        catch (Exception e) {
        e.printStackTrace();
        }
        }
        catch (IOException e) {
        e.printStackTrace();
        }
        }
        }

In the example above first we create an AsynchronousFileChannel for writting. Then we use the write method to write some data,which return a Future object. Once we get a Future object, we  use a polling method method to handle the result of the asynchronous file I/O, where it keeps calling the isDone() method of the Future object to check if the I/O operation is finished or not.And rest of the code is self explanatory.But note that while checking the result of future object we are taking a 1 second sleep,    but in real life we  we will do some useful calculation there.

Example of push approach using CompletionHandler object:


 This version of the write method of the AsynchronousFileChannel class  allows us pass a CompletionHandler object whose methods are called when the requested asynchronous I/O operation completes or fails.

CompletionHandler interface is defined in the java.nio.channels package.

The type parameters:

    V – The result type of the I/O operation
    A – The type of the object attached to the I/O operation

The CompletionHandler interface has two methods: completed() and failed(). The completed() method is called when the requested I/O operation completes successfully. the failed() method is called ,when the requested I/O operation fails. The API allows  us to  pass an object of any type to the completed() and failed() methods. Such an object is called an attachment.We may want to pass an attachment such as the ByteBuffer or the reference to the channel or an reference to the I/O source etc. to these methods such that we can perform additional actions  inside these methods.For example we want to close the AsynchronousFileChannel once the async I/O operation completes successfully or fails due to any reason.We can also pass  null as an attachment , if we don't want to do anything usefull.
Lets create an Attachment object first

public class Attachment {

private Path filesource;
private AsynchronousFileChannel asyncChannel;


//getters and setters goes here.

}

Now let's define the CompletionHandler

private static class MyWriteCompletionHandler
implements CompletionHandler {
@Override
public void completed(Integer result, Attachment attachment) {
System.out.format("%s bytes written to %s%n",
result, attachment.path.toAbsolutePath());
try {
attachment.asyncChannel.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable e, Attachment attachment) {
System.out.format("I/O operation on %s file failed." +
"with  error is: %s", attachment.path, e.getMessage());
try {
attachment.asyncChannel.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}


public class ASyncIOWithCompletionHandler{

 public static void main(String[] args) {
static String str="write some meaning full text to file,which is desired for your applications.";
 Path path = Paths.get("/home/brainatjava/mytest");
 try {
AsynchronousFileChannel asyncfileChannel =
AsynchronousFileChannel.open(path, WRITE,CREATE);
MyWriteCompletionHandler handler = new MyWriteCompletionHandler();
ByteBuffer dataBuffer = ByteBuffer.wrap(str.getBytes());
Attachment attachment = new Attachment();
attachment.setAsyncChannel(asyncfileChannel);
attachment.setPath(path);
asyncfileChannel.write(dataBuffer, 0, attachment, handler);

try {
System.out.println("Sleeping for 10 seconds...");
Thread.sleep(10000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Completed");
}
catch (IOException e) {
e.printStackTrace();
}
 }
}

Here the main thread is  sleeping for 10 seconds ,but in real life scenario , the main thread will do some useful calculation rather than sleeping.

Sunday, May 8, 2016

Remote debugging Tomcat with Eclipse

Sometimes it is required to debug a remote  application that is deployed in tomcat in the local network.We can configure eclipse to  debug the remote application locally  for a running tomcat instance that is configured with JPDA support.JPDA is a multi-tiered debugging architecture.Please visit the oracle docs for more about JPDA.

First let's set up tomcat for remote debugging using JPDA

Setting Up Tomcat For Remote Debugging

 Tomcat can be configured to allow a program such as eclipse to connect remotely using JPDA and see debugging information.We can do the configuration change in catalina.sh.Now open the catalina.sh or catalina.bat and find the line JPDA_TRANSPORT.Chnage the value of the parameter as  

JPDA_TRANSPORT=dt_socket
JPDA_ADDRESS="ipwhereyourapplicationisdeployed:5001" (port 5001 is not mandatory, you can give any unused port)

Here also we can write  JPDA_ADDRESS="*:5001" ,but it has some security issue,so it is good practice to specify the ip.

Then we start tomcat with the command ./catalina.sh jpda run.And now we are ready to go.

Also without changing anything in catalina.sh or catalina.bat , we can write the same parameter in startup.sh or startup.bat  

In Unix
export JPDA_ADDRESS=ip:5001
export JPDA_TRANSPORT=dt_socket
bin/catalina.sh jpda run
In Windows
set JPDA_ADDRESS=ip:5001
set JPDA_TRANSPORT=dt_socket
bin/catalina.bat jpda start
 Once we  have tomcat configured , now we start tomcat manually from command line.


Now we configure our eclipse to listen the tomcat running remotely.

Setting Up Eclipse:

1.Set break point in eclipse.
2.Then Debug As Debug Configurations...
3.Then double click on the heading Remote Java Application.A window like this will appear

4.In the host write the ip address you mentioned in the JPDA_ADRESS and in port write the port you mentioned in JPDA_ADDRESS.Here in our case it is 5001.
5.Now click apply and debug.

Now the  eclipse is ready for debugging.

The above scenario is tested in  Linux Mint 17.1 Rebecca ,STS 3.7.2 and apache-tomcat-8.0.24.

Saturday, April 23, 2016

Redis Pub Sub with Jedis

Within these days we were working on a project which heavily relies on Redis for its data sync process.To give  more clarity here we are briefing  the scenario.

There are two parts on the system.One is a producer which is making some cache in Redis and another is a consumer which is subscribed to the same Redis.The subscription is through a channel.The consumer is subscribed to the channel.When there is some change in the channel ,it is published to the consumer and the consumer  updates itself accordingly.Here we used Jedis as Redis  client.



In Redis, we can subscribe to multiple channels and when someone publishes messages on those channels, Redis notifies us  with published messages. Jedis provides this functionality with JedisPubSub abstract class. To handle pub / sub events, we need to extend JedisPubSub class and implement the abstract methods.



package com.brainatjava.test;
public class xyzListener extends JedisPubSub {   @Override
    public void onMessage(String channel, String message) {
    System.out.println(message);
}

Now we wrote the code for registering listener in a different class.

public class TestProgram {
private void registerListeners() {
        if(!xyzListener.isSubscribed()){
                Runnable task=()->{       
                try{
                    Jedis jdeisConnection=    ((Jedis) redisTemplate.getConnectionFactory().getConnection().getNativeConnection());
                    jedisConnectionExceptionFlag=false;
                    jdeisConnection.subscribe(lineItemDeliveryListener, "channelName");
                      
                }
                catch(JedisConnectionException jce){
                    logger.error("got jedis connection excpetion "+jce.getMessage(),jce);
                    jedisConnectionExceptionFlag=true;
                }
                catch(RedisConnectionFailureException rce){
                    logger.error("got jedis RedisConnectionFailureException excpetion "+rce.getMessage(),rce);
                    jedisConnectionExceptionFlag=true;
                }
                catch(Exception e){
                logger.error("error in registerListeners "+xyzListener.isSubscribed(),e);
            }};
           
            Thread xyzUpdater = new Thread(task);
            xyzUpdater.setName("xyzUpdater");
            xyzUpdater.start();
        }
    }

}
Here if we notice the above code ,we found that  first we are checking is xyzListener is subscribed to the required channel ,if not we are doing it.But Observe that we are doing it in a hacky way.That is we are getting the native connection first and then we are subscribing to the channel.And the subscribe is a blocking call.It act in wait and watch mode.

So when there is a change in the channel the listener listens it and update its cache accordingly.But There is always should have a fail safe mechanism in place.We have also done that.If somehow Jedis pubsub is not working,then we have a mechanisim in place to do it manually.

The mechanism is like we have a cron scheduler running in every 15 minutes and    checking the cache timestamp and if the cache timestamp of the latest cache and the timestamp of the consumer varies, then we assume there is issue with pubsub and we will update the consumer cache manually.

With this design everything was fine and  the 15 minutes cron was their without any use.After the smooth working of some days we got an alert that the 15 minute cron is running and manually updating the cache.So it has no impact on our service as the cache is getting updated manually with the help of cron scheduler.

But why this happened?After investigetting sometimes we found before some  days the redis was restarted.And this created the whole issue.It is behaving like it is subscribed.Now you know the solution.

Friday, March 11, 2016

The try-with-resources Statement

It is always required to close the resources like database connections, file handles like BufferedReader,BufferedWriter etc after it's use.Otherwise we will face resource leak issue.And sometimes we forget to close the resources after the use.But in Java 7 a functional interface namely AutoCloseable is introduced.And resoureces like Connection ,BufferedReader and BufferedWriter etc extends AutoCloseable.
The try-with-resources statement is a try statement that declares one or more resources. The try-with-resources statement ensures that each resource is closed at the end of the try statement. Any object that implements java.lang.AutoCloseable,  can be used as a resource inside the try-with-resources statement.
The following example writes a line in a file. It uses an instance of BufferedWriter to write data in the file. BufferedWriter is a resource that must be closed after the program is finished with it:
static String writeALineToFile(String path) throws IOException {
    try (BufferedWriter bw =
                   new BufferedWriter(new FileWriter(new File("path")))) {
        return bw.write();
    }
}
In this example, the resource declared in the try-with-resources statement is a BufferedWriter. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedWriter, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedWriter instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedWriter.write throwing an IOException).

Let's make it clear that here try-with-resource statement and try block are two different things.

Prior to Java SE 7, we can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String writeALineToFileWithFinally(String path)
                                                     throws IOException {
 try {
       BufferedWriter bw =
                   new BufferedWriter(new FileWriter(new File("path")))) ;
         bw.write();
    }
}
    } finally {
        if (bw != null) bw.close();
    }
}
However, in this example, if the methods write and close both throw exceptions, then the method  
writeALineToFileWithFinally   throws the exception thrown from the finally block; the exception thrown from the try block is suppressed.

But In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed.

We  can retrieve the suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.


Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Thursday, November 19, 2015

Make a BoundedCollection by Using a Synchronizer

Sometimes it is required to create bounded collection.The main aim of the question is to create a collection so that it can contain only a fixed number of elements at a particular instant of time.There are many approaches to do it.There are some third party apis like apache.commons,Guava  which provides such functionalities.

But our aim here is to not to use any third party apis, rather we can implement it using some provided tools in Java.We are going to implement it by using an existing synchronizers ie. semaphore.We will take a semaphore with fixed number of permit.Before adding something in our collection we will acquire a permit and and if in case of any exception of adding will release the permit.And also when removing something from the collection we will release a permit.To read more about semaphore please visit the series semaphore and mutex


Implementation details:


In our below implementation we will take a hashSet  and make it bounded.Similarly we can make any collection  a bounded collection.

package com.brainatjava.test;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

public class BoundedCollection {
    private final Set hashSet;
    private final Semaphore semaphore;

    public BoundedCollection(int nosOfPermit) {
        this.hashSet = Collections.synchronizedSet(new HashSet());
        semaphore = new Semaphore(nosOfPermit);
    }

    public boolean add(T o) throws InterruptedException {
        semaphore.acquire();
        boolean isSomethingAdded = false;
        try {
            isSomethingAdded = hashSet.add(o);
            return isSomethingAdded;
        } finally {
            if (!isSomethingAdded)
                semaphore.release();
        }
    }

    public boolean remove(Object o) {
        boolean isSomethingRemoved = hashSet.remove(o);
        if (isSomethingRemoved)
            semaphore.release();
        return isSomethingRemoved;
    }
}

Friday, November 13, 2015

notify() and notifyAll():Which one to use

Sometimes we face dilemma to choose one out of notify() and notifyAll().This post aims to explain  the use of notify() and notifyAll() with the help of an example.Although there are many more apis in java.util.concurrent package to use for more serious multi threaded programming.But still it is required to understand the basics.Although this post is for the beginners to learn about the use of wait(), notify() and notifyAll(),but still the senior developers can clear their doubts and refresh their memory about it.

 Let's assume that we have a room and inside it there are three equipment.One is motor which is filling water in a tank.Other one is an  oven which is baking a cake.And the third one is an ice maker which converts water into ice.But all these are associated with a bell which rings after the completion of the specific task.And initially the room is locked and the key is available next to it.But the condition is at any instant of time only one person can take the lock and enter inside the room to use one of the equipment.After initiating his work
he can come out of the room by releasing the lock giving a chance to any other person to use any other equipment.And he waits outside of the room till the completion of his task and can collect his product from the equipment by entering the room again by reacquiring the lock.

And let's  have three threads named thread1 , thread2 and thread3.Let's assume thread1 came and take the lock of the room and go inside and switch on the motor to fill the tank and came out of the room by releasing the lock and wait outside to listen the ringing of the bell.This is exactly what wait method does.

Now thread2 came and took the the lock , went inside the room and put a cake in the oven.Then release the lock and went out of the room and wait outside to listen the ringing of the bell.

Similarly the thread3 came , took the lock and went inside the room and keep some water in the ice maker.Then release the lock and  went out of the room and wait outside to listen the ringing of the bell.

Here all threads are waiting  to listen the bell ringing sound.And bell ring means one of the task is finished.

Assume here that we have used notify() method of the object to notify a thread that it's waiting is over and the condition on which it was waiting is already changed,now it can woke up check for the condition again and if the condition is really changed then the thread can proceed whatever it wants to do.

But the issue here is that suppose a notification is issued for thread3 that water is already converted to ice.But since we use notify here.And we have three threads in waiting state , now the JVM will decide to wake up any one thread by using it's own algorithm.Suppose unfortunately JVM decided to wake up thread1.So now thread1 woke up and got the lock as it has no contestant checks the condition again (that is whether the tank is filled).
As tank is not filled yet again go to the waiting state by releasing the lock.But here the thread3 which actually is the deserving candidate missed the notification and still waiting to get it's turn.

Now in this case if we have used notifyall, then all the threads will  wake up and contest for lock and get the lock one by one.And the thread for which notification was meant for will  definitely  get the lock sooner or later and will not miss the signal at all.

So if this the case then we should use notifyall instead of notify.
But assume if we have only one equipment associated with the bell which is ringing upon completion of the task.Then we can use notify.
So if we model our real life scenario with the above example.We can decide whether it is best to use notify or notifyAll.

But we might tempted to think if there is so much confusion to use notify over notifyall,why not always use  notifyall.Yes we can do that,but we have to pay the price for it. Using notifyAll when only one thread can make progress is horribly inefficient. If more than one  threads are waiting on same  lock, calling notifyAll causes all of them to wake up and contest for the lock; then most or all of them will not get the lock and  will go to sleep again. This means a lot of context switches and a lot of contested lock acquisitions, which is not desirable.

Important Points to remember:

  • The thread whicch has called wait() method releases the lock as it waits.
  • The thread which has called wait method blocks until it is notified. 
  • Once it is notified ,it needs to reacquire the lock to  continue.
  • The thread must hold the lock released by the waiting thread to  call notify() or notifyall().
  • Suppose there are more than one thread  waiting on the same lock , calling notify causes the JVM to select one thread waiting on that lock  to wake up.
  • Calling notifyAll wakes up all the threads waiting on that lock.
  • Since the thread must hold the lock to call notify() or notifyall() method and waiting threads cannot return from wait without reacquiring the lock, the notifying thread should release the lock quickly to ensure that the waiting threads are unblocked as soon as possible.
  • If there is confusion which method to call notify() or notifyAll(),it is always safe to call notifyAll().
  • But calling notifyAll() has some overhead.
calling notifyAll() causes all the threads to wake up and contest for the lock; then most or all of them will go back to sleep, as any one thread will get the lock.Which causes a lot of context switch which is very much undesirable.  

 Consider the following code sample.Here we have examined the famous Consumer Producer  problem.
We have a sharedBuffer having a fixed size.And there are three threads.And all the three threads are using the same lock  i.e  sharedBuffer as the lock.


producerThread:It checks the sharedBuffer,if  the sharedBuffer is full , the thread calls wait() method.After getting notification from some another thread, it wakes up and an element in sharedBuffer.And then it calls notify().This notify call is meant for the consumerThread.That is it is an indication to the consumer thread that ,now the consumer thread can wake up and start consuming the element from the sharedBuffer.

consumerThread:It checks the sharedBuffer.If the sharedBuffer is empty,then the thread calls wait.Release the lock  and blocks till the notification received which is issued  by the producer after putting an element in the sharedBuffer.After consuming an element the consumerThread calls notify().And this notification is meant for the producerThread.That is it is an indication to the producerthread that ,now the producerthread can wake up and start producing an element in the sharedBuffer.

sizeCheckerThread:It checks the size of the sharedBuffer.If it is greater than 0,then it calls the wait method by releasing the lock.This thread is an extra thread to demonstrate the fact that it is receiving the notification which is not meant for it.

Notice that in produce method , consume method   and  doSizeChecking method we are checking the condition by using a while loop  but not using  if.The main reason for this is if the waiting  thread  wake up by spurious wake up(which is generated by OS) but the condition on which it is waiting is still not satisfied , then the thread will have an opportunity to wait again.

Analogy between the Example and Sample Code:

Now let's compare the analogy between the example and the sample code.notify() method is analogous to the bell which rings.But the bell rings in three different conditions i.e when tank is filled,cake is baked and ice is made.Here also notify is called in three different conditions.When consumer consumes an element,producer produce an element and size of the sharedBuffer is not greater than zero.In the example the shared lock is the room lock and here in the sample code the shared lock is sharedBuffer.

Missed Signal Issue:

Assume that if the notification is raised by  consumerThread that it has consumed an element and the sharedBuffer is not full and the producer can put new element in it.Actually this notification is meant for the producer, but there is no guarantee that the producer thread will receive the notification.By the choice of the JVM  the sizeCheckerThread may receive the notification instead of  producerThread.The case may be so unfortunate that, the producerThread may never receive the notification signal issued for him and it is always hijacked by the  sizeCheckerThread.Which we can say as a missed signal issue.So in this case we should  use notifyAll instead of notify, to avoid such missed signal issue.So that all the threads will get equal chance to wake up and contest for lock and will get the lock sooner or later.

When to use notify():

  1.  Only one condition is associated with the lock.
  2.  Each thread executes the same logic by returning from wait() method call.
  3. A notification  enables at most one thread to proceed.
In our below example code if we remove the sizeCheckerThread,then it follows the 3rd rule of the above three rules, that is a notification  will allow only one thread to proceed  ie. either consumerThread or producerThread.But it does not follow the 1st rule.It has two conditions associated   with the same lock ie. if sharedBuffer is full  for producerThread and sharedBuffer is empty for consumerThread.Also it does not follow the 2nd rule ie. each thread executes the different logic after returning from wait() method call.

Usually we rarely get such ideal scenarios to implement  in our multithreaded environment , so in almost all cases it is required to use notifyAll().


package com.brainatjava.test; import java.util.ArrayList; public class ProducerConsumerProblem { public static void main(String args[]) { ArrayList sharedBuffer = new ArrayList(); int size = 4; Thread producerThread = new Thread(new Producer(sharedBuffer, size), "Producer"); Thread consumerThread = new Thread(new Consumer(sharedBuffer), "Consumer"); Thread sizeCheckerThread = new Thread(new SizeChecker(sharedBuffer), "sizeChecker"); producerThread.start(); consumerThread.start(); sizeCheckerThread.start(); } } class Producer implements Runnable { private final ArrayList sharedBuffer; private final int SIZE; public Producer(ArrayList sharedBuffer , int size) { this.sharedBuffer = sharedBuffer ; this.SIZE = size; } @Override public void run() { int i=0; while (true) { System.out.println("Producer Produced: " + i); try { produce(i); i++; } catch (InterruptedException ex) { ex.printStackTrace(); } } } private void produce(int i) throws InterruptedException { synchronized (sharedBuffer) { while (sharedBuffer.size() == SIZE) { System.out.println("Queue is full " + Thread.currentThread().getName() + " is waiting , size: " + sharedBuffer.size()); sharedBuffer.wait(); } sharedBuffer.add(i); sharedBuffer.notify(); } } }


class Consumer implements Runnable {

    private final ArrayList sharedBuffer;

    public Consumer(ArrayList sharedBuffer ) {
        this.sharedBuffer = sharedBuffer ;
    }

    @Override
    public void run() {
        while (true) {
            try {
                consume();
                Thread.sleep(50);
            } catch (InterruptedException ex) {
               ex.printStackTrace();
            }

        }
    }

    private void consume() throws InterruptedException {
         synchronized (sharedBuffer) {
        while (sharedBuffer.isEmpty()) {
                System.out.println("Queue is empty " + Thread.currentThread().getName()
                                    + " is waiting , size: " + sharedBuffer.size());
                sharedBuffer.wait();
            }
            int value=(Integer)sharedBuffer.remove(0);
            System.out.println("Consumer consumed "+value);
            sharedBuffer.notify();
        }
    }
}


class SizeChecker implements Runnable {
      private final ArrayList sharedBuffer;

        public SizeChecker(ArrayList sharedQueue) {
            this.sharedBuffer = sharedQueue;
        }
        @Override
        public void run() {
            while (true) {
                try {
                    doSizeChecking();
                    Thread.sleep(50);
                } catch (InterruptedException ex) {
                   ex.printStackTrace();
                }

            }
        }
        private void doSizeChecking() throws InterruptedException {
             synchronized (sharedBuffer) {
            while (sharedBuffer.size()>0) {
                    System.out.println("Going to wait as size>=0 " + Thread.currentThread().getName()
                                         +"  "+ sharedBuffer.size());
                    sharedBuffer.wait();
                    System.out.println("wake up from wait by notification form a thread");
                }
               
                System.out.println("Quesize is 0 "+sharedBuffer.size());
               
            }
        }
}
Please feel free to comment for anything wrong is observed.Comments will be used to improve or correct the post if required.

Saturday, October 10, 2015

Volatile keyword in Java

Usually we discuss a lot about how volatile works in java,but still it is not clear about the scope of volatile keyword.Recently one of my colleague asked me about the scope of volatile and its usefulness.I would like to use this space to  make it clear as possible.Although I described about the volatile keyword  in one of my post compiler reordering.But still it has some more directions to discuss.

Some points to know about JMM(JAVA Memory Model )
  1. Each thread has separate memory space.
  2. We need some special trick to enforce the communication between different threads.
  3. Some times memory writes can leak so that other threads may read the updated value.But this is not guaranteed means of communication between two threads.

Role Of Volatile in Thread communications :

  • Volatile modifier is a mechanism by which communication between different threads are guaranteed.
  • When second thread see the value written in volatile variable by the first thread.,then it is the guarantee that second thread will see all the contents of the (first threads memory space ) memory space written by first thread just before writing into the volatile variable.
  • We call this principle as  happens before principle in JMM.
 Let's try to understand it with the help of an example.

Consider we have an scenario  like this.We have an int variable named result which is not volatile and an Boolean variable named flag which is volatile.And we have two threads Thread1 and Thread2.Suppose Thread1 started and make the value of result as 30 and the value of flag as true.

Thread1                                                                             
______

 result=30;
  flag= true;


   Thread2
________

if(flag)
System.out.println(result); 


Then Thread2 comes and reads from flag and sees the value written to it by Thread1 .Because this communication happens, all of the memory space seen by Thread 1, just before it wrote to flag , must be visible to Thread2, after it reads the value true for flag.

So here Thread2 will print the value of result as 30.This is guaranteed due to the volatile modifier of flag.

Here if  you follow one of my  blog on double check for null instance , we have used the volatile modifier in line 2.
Just for convinece i am writing the snippet here

 public class SigletonTest {
 private static volatile SigletonTest instance = null;
          // private constructor
        private SigletonTest() {
        }
         public static SigletonTest getInstance() {
            if (instance == null) {
                synchronized (SigletonTest.class) {
                    // Double check
                    if (instance == null) {
                        instance = new SigletonTest();
                    }
                }
            }
            return instance;
        }
  }
Because If one thread creates an object, it has to convey or communicate the contents of its memory to another thread.Otherwise the newly created object will just remain in it's own memory space.But we need to communicate this message to other threads also, so that our purpose of single object creation can be achieved.That's why we used volatile modifier in line 2.

Some people argue that  , since the lock in form of synchronized block  also follows this happens before relationship , is the volatile modifier is necessary in line no 2?

The answer is yes,because here only the writting thread is performing the locking mechanism.But not the reader thread.If you see in line 7 null check of the instance is performed outside the synchronized block which is done by the reader thread.

Synchronization by itself would be enough in this case if the first check was within synchronized block.But we have kept it outside the synchronized block to save the synchronization cost, when the object is already created as discussed in my previous blog double check null instance.

Without explicit communication  with the help of volatile variable , the reader thread will not be able to see the fully constructed object created by the writer thread.

Immutability in Java

Generally we are asked questions about immutable in java.When a class is said to be immutable?Can you say whether the given class  is immutable?Lots of discussion.Here I want to summarize my knowledge about Immutable with the help of  some examples.

Immutable:

Definition: Informally we say an object is immutable if the state can not be modified after construction.That is the invariants defined by the constructor always hold even after any  steps of  the constructor creation.

Now let's see some example of immutable classes.

1. String:

As we all know that string class is immutable,let's start with String class. we see string class is final and it has  4 instance variables which form the object state.They are char array,offset,count and hash.Out of them 3 is final and hash is not final.Now let's check the invariants  here.The invariant is that at any time after the string construction the value of the charcter array will remain the same. 
This invariant will hold for the String as the character array is final.So once we assign some value to it in constructor , we can't assign any value afterwards.

why hash is not final:

Let's see the hashcode method defined in String below

public final class String {
 private final char value[];
private final int offset;>
private final int count;
private int hash;

public int hashCode() {
         int h = hash;
         if (h == 0) {
             int off = offset;
             char val[] = value;
             int len = count;

             for (int i = 0; i < len; i++) {
                 h = 31*h + val[off++];
             }
             hash = h;
         }
         return h;
     }
}
Now let's think about hash.Assume It as  a cache to store the value of the hashcode. If  we don't call hashcode method , the value for it will not be set. It could have been set during the creation of the string, but that will lead to longer creation time, for a feature we might not need at all.On the other hand, it would be unnecessary to calculate the hash each time its  required.So it is stored in a non final field.Just see inside the hashcode method if  hash  is assigned to  h.If h is not  0 , then same value is returned  immediately.So no need to recalculate  hash again and again.

The fact that there's a non-final field which  gives us the perception that the invariants may not hold. It's an internal implementation detail, which has no effect on the invriants we defined above.

 As hash is non final,so it might lead us to the doubt that ,it may change in future in some cases.
 Let's be specific about it.Here hash is used to contain the hashcode of the string.But in most of
 the cases it is never required to compute the hashcode till the lifespan of the String.But it is needed   sometimes to compare two strings to check the content equality.In that case hashcode is required.So string computes hashcode lazily but not in the constructor, as it is not immediately required.Also if we look at the hashcode method , we see that it is dependent on three parameters that is offset,count and value which themselves are final and can't change.so  every calculation of the hash give us the same result.As the method hascode is not synchronized , so it is possible that two threads are accessing the the method simultaneously and setting value in hashcode.So hash should be non final.

Why string class is final: 

 Let's assume String class is not final and see what misshapening can occur.
           
   Let's create a class MutableString which extends String.
           
     public class MutableString extends String {
     private String text;

     public MutableString(String value) {
         super(value);
         text = value;
     }

     public int getText() {
         return text;
     }
     public void setText(String newValue) {
         text = newValue;
     }
}

Now  the class MutableString  can be passed everywhere  where String is needed ,because it is of type String.consider the below case.Here we have a method ,that is verifies the password.If it does not pass certain criteria  it  discards the password, otherwise  forward  it for  the next step.

public String verifyPassword(String password) {
     if (!password.contains("some charcter"))
         throw SecurityException("The password is not a valid one");
     //Here in betwwen a thread come along and change the password value ,But now this password just      //changed to some new one is not verified and may contains invalid characters but still return by the method.
     return password;
 }
 Thread1
_______
 MutableString password="secret"
 verifyPassword(password)
 password.setText("secret1")

Here in between the verification process complete and before returning the password  a thread came along and changed the password, as described in the above code snippet.
But if String class was final,such type of scenario wouldn't have happened because MutableString class could not have extended the String class.

 So from these discussion,we reached in the conclusion that String class should be final and hash variable being not final has no impact in the invariant of the String class.

2.ThreeStoges:

 In the famous example of ThreeStoges.java from Brian Goetz page no 32.

 public final class ThreeStooges {
    private final Set stooges = new HashSet();
    public ThreeStooges() {
        stooges.add("Moe");
        stooges.add("Larry");
        stooges.add("Curly");
    }
    public boolean isStooge(String name) {
        return stooges.contains(name);
    }
}

Notice here that Set that stores the names is mutable and it is final.But just follow the argument here that the ThreeStooges class is immutable.

Let's consider the invariant for this class.
The invariant is the instance variable set should not be changed after the construction of the object finished.

Now  let's argu that we can change it after construction.
But here the stooges reference is final.So once it is assigned and initialized in the constructor it can not be changed.If there was a method to modify the set stooges  after construction or if a reference of this class was  escaped outside to some other thread before the construction is complete,then there would have been a chance that our invariant would not hold even after object construction.

So from this we reached in the conclusion that our assumption that we can change it after object construction is wrong.

But if we argue that if the line
 ThreeStooges ts = new ThreeStooges()
 is thread safe.Is it possible that one thread can can see the uninitialized object of the ThreeStooges where the intialization process already is in progress by another thread.
 Yes it is thread safe and no such thing will happen as it is guaranteed by the final keyword by JMM.See my   blog on compiler reordering : final and volatile

 Hence ThreeStoges class is immutable.

For more details please refer  Brian Goetz java concurrency in practice page 31.

3.Unmodifiable HashMap:



public class unmodifiableHashMap implements Map {
private final Map map;
public unmodifiableHashMap(Map map) {
this.map = new HashMap(map);
 }

  @Override
public V get(Object key) {
return map.get(key);
 }

  @Override
public V put(K key, V value) {
throw new UnsupportedOperationException();

similarly we can override all other getter and mutator(modifier/changer) methods.In this way we can  change a hashmap to an immutable hashmap.Here this immutable hashmap can be shared with multiple threads  safely.This guarantee is given by the final keyword used  in line no 2 of the above code snippet.

Conclusion:

 From the above three examples and discussions we conclude that
  •  An object is immutable if , It's state can't be modified after construction.
  •  An immutable object is thread safe.

 Ways to achieve it:

 1.All fields should final.
 2.the this reference should not escape during construction to any outside thread or client.
 3.There should not be any mutator method that can change the value of the instance variable after object construction.

Thursday, October 1, 2015

Compiler Reordering: final and volatile

Usually when we write a statement like Object o=new Object(); it is a three step process of CPU instruction
  1. Allocate space for new object
  2. Store the unconstructed object in variable
  3. Initialise object
Although the above steps are not exact,some similar steps happen  at the time of creating an object.
Let's see an example

class MyClass {
  int i;
  MyClass () {
    i = 1;
  }
}

When we write something like MyClass clazz=new MyClass();

The following steps should ideally  happen as per our assumption

  1. var= Allocate space for MyClass
  2. var.i = 1;
  3. clazz= var;
 But the compiler might do it in a different ordering.For optimization purpose  the above line of code can be written by compiler in a different manner like below snippet.

  1. clazz= Allocate space for MyClass 
  2. clazz.i = 1;
 But something different ordering happened in contrary to our assumption,We can call this as compiler reordering of the statements.

But the reordering of statements by compiler affects the thread safety.Assume that one thread is in the process of creating the MyClass object and it just completed the step 1.Now another thread came and saw the object is not null because of thread 1 completed step 1.And tried to clazz.i  and will get the wrong value,since thread1 has not completed step 2 yet.

Thread 1:
MyClass clazz = new MyClass ();

Thread 2:
if (clazz != null) {
  System.out.println(clazz .i);
}

So there is no guarantee that thread 2 will print 1.

Here this is a concern of thready safety.

Prevent Compiler Reordering:

1.final
 If  we redesign our class like 

class MyClass {
final  int i;
  MyClass () {
    i = 1;
  }
}

Here note that we changed the modifier of  the variable i as final.Now we can say this class is thread safe.
Without the final modifier, the compiler and JVM are allowed to move the write to i so that it occurs after the reference to the new object is written to clazz.But the final modifier will  restrict the compiler to do such type of reordering.

 2.volatile 
If you refer one of my series double check locking for singleton you will see in line number 2 we have used the keyword volatile for our singletonTest  instance.Without the volatile keyword this code will not work in java.The basic rule is that compiler reordering can change the code  so that the code in the SingletonTest constructor  occur after the write to the  instance variable in line number 11.If this will happen then there will be thread safety issue.

Just assume we have two threads Thread1 and Thread2.Now Thread1  will come and see  instance is null in getInstance method and  proceed to execute line 11 , but as we know line 11 is not an atomic operation , so just after  assigning to instance variable and  before constructing the SingletonTest object completely   , Thread2 can come along and read the instance before Thread1 finished the construction in line number 7 of getInstance method..

If we make the instance field volatile in line no 2 , the actions that should  happen before the write to instance  in the code must actually happen before the write to instance .No compiler  reordering is allowed. 

Saturday, August 29, 2015

CyclicBarrier Continued

In our previous series of CyclicBarrier we learned that CyclicBarrier can be constructed in two ways.
Like 
  1. CyclicBarrier cb=new  CyclicBarrier (int nosOfPArallelThread,Runnable BarrierAction);
  2.  CyclicBarrier cb=new  CyclicBarrier (int nosOfParallelThread);  
In our previous series we saw an example of first constructor, which takes two parameters numberofParallelThreads and a Runnable as argument.
In this series we look for the use of the second constructor ,  which takes only one integer argument,the number of parallel threads.

package com.brainatjava.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierConstructorWithOneArgument {

    private static int matrix[][] =
    {
        { 1 ,1,1,1},
        { 2, 2 ,2,2},
        { 3, 3, 3 ,3},
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5 } };

    private static int results[];

    private static class Adder extends Thread
    {
        int row;

        CyclicBarrier barrierWhereAllThreadsWillWait;

        Adder(CyclicBarrier cb, int row)
        {
            this.barrierWhereAllThreadsWillWait = cb;
            this.row = row;
        }

        public void run()
        {
            int columns = matrix[row].length;
            int sum = 0;
            for (int i = 0; i < columns; i++)
            {
                sum += matrix[row][i];
            }
            results[row] = sum;
            System.out.println("Results for row " + row + " are : " + sum);
           int arrivalIndex=0;
            try
            {
                arrivalIndex= barrierWhereAllThreadsWillWait.await();
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            } catch (BrokenBarrierException ex)
            {
                ex.printStackTrace();
            }
            if(arrivalIndex==0){
                System.out.println(Thread.currentThread().getName()+" is executing the combined result.");
                 int total = 0;
                 for (int i = 0; i < results.length; i++)
                 {
                     total += results[i];
                 }
                 System.out.println("Results are: " + total);
            }
        }
    }

    public static void main(String args[])
    {
        final int rows = matrix.length;
        results = new int[rows];
        CyclicBarrier barrier = new CyclicBarrier(rows);
        for (int i = 0; i < rows; i++)
        {
            new Adder(barrier, i).start();
        }
       
    }
}

In the above code snippet ,Please note the line highlighted with red color.Here the await() method of cyclicbarrier class is returning an int value.That signifies the arrival index of the thread at the barrier.
If the arrival index is zero ,it means that thread is the last thread to arrive at the barrier.

Here we choose the last thread that reaches at the barrier to execute the final action that is to calculate the total sum.Since we have taken the arrival index of the thread as zero.

Reset Method of CyclicBarrier(): 

If reset() method is called by any thread, then all the other threads waiting at the barrier will awake by throwing a BrokenBarrierException.So we can say that the reset() method is used when we want to break the barrier forcibly.Remember that if one thread will call reset method when no other threads are waiting on barrier,then reset method has no  effect.

Let's see the reset method in action with the help of an example.

package com.brainatjava.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

    class CyclicBarrierResetExample
    {
        public static void main(String args[])
        {
            CyclicBarrier cb=new CyclicBarrier(2,new Master());
            Thread slave1=new Thread(new Slave1(cb));
            slave1.start();
            Thread slave2=new Thread( new Slave2(cb));
            slave2.start();
        }
    }
    class Slave1 implements Runnable
    {
    CyclicBarrier cb;
        public Slave1(CyclicBarrier cb)
        {
            this.cb=cb;
        }
        public void run()
        {
            System.out.println("Slave1 has performed some work.");
            System.out.println("Slave1 is going to wait.");
            try
            {
                cb.await();
            }catch(BrokenBarrierException e){
                System.out.println("Slave1 can't wait as it is getting BrokenBArrier exception "+e.getMessage());
                e.printStackTrace();
            } catch (InterruptedException e) {
                 System.out.println("Slave1 can't wait as it is getting interupted exception  "+e.getMessage());
                e.printStackTrace();
            }
            System.out.println("Anyway !!!! Woo Slave1's waiting is finsihed.Slave1 is going home now.");
        }
    }
    class Slave2 implements Runnable
    {
    CyclicBarrier cb;
        public Slave2(CyclicBarrier cb)
        {
            this.cb=cb;
        }
        public void run()
        {
            System.out.println("Slave2 has performed some work.");
            System.out.println("Slave2 is going to wait.");
            try
            { Thread.sleep(1000);
                cb.reset();
                cb.await();
            }catch(BrokenBarrierException e){
                System.out.println("Slave2 can't wait as it is getting brokenbarrier exception "+e.getMessage());
            } catch (InterruptedException e) {
                 System.out.println("Slave2 can't wait as it is getting nullpointer exception "+e.getMessage());
                e.printStackTrace();
            }
           
            System.out.println("Anyway !!!! Woo Slave2's waiting is finsihed.Slave2 is going home now.");
        }
       
    }
    class Master implements Runnable
    {
        public void run()
        {
            System.out.println("Master is going to complete all his work as two slaves have already reached at the barrier.");
            System.out.println("Thank you slaves you completed all your work on time.");
        }
       
    }


Output Of the Above Programme

Slave1 has performed some work.
Slave1 is going to wait.
Slave2 has performed some work.
Slave2 is going to wait.
Master is going to complete all his work as two slaves have already reached at the barrier.
Thank you slaves you completed all your work on time.
Anyway !!!! Woo Slave2's waiting is finsihed.Slave2 is going home now.
Slave1 can't wait as it is getting BrokenBArrier exception null
java.util.concurrent.BrokenBarrierException
    at java.util.concurrent.CyclicBarrier.dowait(Unknown Source)
    at java.util.concurrent.CyclicBarrier.await(Unknown Source)
    at com.brainatjava.test.Slave1.run(CyclicBarrierResetExample.java:30)
    at java.lang.Thread.run(Unknown Source)
Anyway !!!! Woo Slave1's waiting is finsihed.Slave1 is going home now.