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

Saturday, 21 March 2015

Volatile Keyword


In this post I am going to describe why we use volatile keyword.

I am assuming you have a basic knowledge of compiler. Whenever we write a code and compile it. Compiler optimizes our code according to some basic fundamentals.

Like for eg. If in our code we have a constant variable whose value cannot be modified and we have a loop checking this constant variable with another constant. Means if compiler thinks that none part of our code is changing the value of the variable than it can optimize the comparisons.

Ex:
I am not writing the complete code. I am writing only the part which considers the above fact.

const int a=10;

while(a<20){    /// focus on this line
      some task;
}
Now At compile time compiler will check that variable a is constant and its value cannot be changed. And in the while loop it determines that 20 is also constant so it is also not changed. So it evalutes the result of a<20 and put it in the while condition.

Then compiler will put either true or false there to optimize. So that at each time it iterate through the loop it does not have to compare the variable.

For ex: After optimization code looks like this.

const int a=10;

while(true){   /// focus on this line
      some task;
}

But sometime this optimization affect the code in the wrong way.
Like : If we have a share variable between two files or two program then we don't want compiler to do any optimization with those variables. 

In this case we can define those variables to volatile. So compiler will not apply any kind of optimization on these variables.

Scenario 1: Variable with Volatile Keyword :

Ex:  we have a variable called a which is shared in two threads thread1 and thread2.

Volatile Keyword


Explanation: We have a volatile variable a=1 in thread 1 and it is shared. When thread 1 runs it goes in to while loop and check for a and goes in to the loop and do the task and switch to thread 2. Now thread 2 also checks a=1 goes in to loop and make a=0 and then again switch to thread 1 at line 8.

Now it checks the value of a which is equal to 0 and come out of the loop.


Scenario 2: Variable without Volatile Keyword.

Now consider the scenario where value of a is optimized. Means without volatile.

In thread 1;
int a=1;

some task;
while(a){  /// this is replaced by while(1)   /// optimized by compiler    ///// line 1
    do some task;  
   switch to thread2;
   //// line8
}


In thread 2:

while(a){
   do some task;
    a=0;
   switch to thread 1;
}


Explanation: We have a variable a=1 in thread 1 and it is shared. When thread 1 runs it check for a and goes in to the loop and do the task and switch to thread 2. Now thread 2 also checks if a!=0 and goes in to loop and make a=0 and then again switch to thread 1 at line 5.

Due to while(1).
Now because of optimization thread 1 now do not check the value of a at line 1.

And goes into infinite loop. A serious problem caused due to optimization. 

So for avoiding this problem use volatile keyword to the variables which we do not want compiler to optimize in any case.



I hope it helps. If you find this useful share it. If you have any problem feel free to comment. How do you rate this post either interesting or cool or funny. See below. Thanks for visiting.


Interrupted Exception (Thread.sleep() )

In this post I am going to describe what is an Interrupted Exception is and another thing is why always we write thread.sleep function in try catch block.

A thread or java execution throws an interrupted exception whenever a thread is interrupted by another thread. There might be some other reason also but this is the most frequent reason for the InterruptedException.

Whenever we use Thread.sleep() function, we have to use it in try catch block because this function can throw an interrupted exception. If we will not provide a catch block for handling that exception it might give an error at running time. Because the sleeping thread might be interrupted by some other running thread.

So the code for using thread.sleep will be.

I am writing only main function.
Note: Do not forget to use throws InterruptedException in whichever function you are using Thread.sleep.

public static void main(String [] args) throws InterruptedException{
     try {

           Thread.sleep(1000);  // sleeping the thread for 1000 ms
     } catch( InterruptedException e){

            System.out.println("our thread is interrupted");
        }
  }



Thursday, 19 March 2015

How to write data to an excel file in java (Eclipse)

In this post I am going to describe how to write data in to an excel file in java.

There are number of ways. One of them is by using Apache POI.

Apache POI is a project under the guidance of Apache Software Foundation. This POI libraries are used to write data to Microsoft office formats like excel, word etc.

I am assuming you are using Eclipse IDE for developing Java project.

1. First thing you have to download the apache POI from the following link according to your computers environment.(Operating System, 32/64 bit version)


I prefer to download the stable version.

2. After Downloading unzip the folder. You will see some jar files. There will be a jar file with named like poi-3.11-20141221.jar . Digits may vary in the files name according to their version and their release date.

3. Include this file into your projects external jar files. For doing the same you can visit my previous post.


Now we are done with preprocessing. We have to write code for writing data in an excel file.

4. Import these classes to your code.

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class writeToExcel{


       public static void main(Strings [] args) throws InterruptedException{

                  try{

                               FileOutputStream fileOut = new FileOutputStream("test2.xls");
                               HSSFWorkbook workbook = new HSSFWorkbook();
                               HSSFSheet worksheet = workbook.createSheet("test2 Worksheet");

                                // It means we create an output file with name test2.xls and open an workbook 
                                // for working and worksheet for creating data and then we will write to our file

                             HSSFRow row1 = worksheet.createRow(0);
                             HSSFCell column1= row1.createCell(0);
                             column1.setCellValue("hello");
                             HSSFCell column2= row1.createCell(1);
                             column2.setCellValue("Thanks for visiting ");
          
                             // you can iterate through for creating more rows. make sure that it is indexed 
                            // from 0 as array in C 
                            // First create row and then column and set their values.
                               
                                workbook.write(fileOut);
                                  fileOut.flush();
                                fileOut.close();
                                workbook.close();
                   }

                    catch (FileNotFoundException exc) {
                                                 exc.printStackTrace();
                   } catch (IOException exc) {
                                                 exc.printStackTrace();
                   }
      }

}

This code is running. If you get any error comment. I will try to help. If you find the post useful Share it.

How to add external jar files in Eclipse

In this project I am going to describe how to add jar files in eclipse.

1. First of all locate the folder where your jar file is.

2. Then open Eclipse and go to Project Option  in the menu bar

Project -> Properties -> Java Build Path -> Libraries -> Add External Jars

Adding External Jar file in Eclipse


3. Browse to the location where your jar file is located.

Click on the open and then Ok.

You are done. Feel free to comment. If you have another problem comment. If you like this post share it and visit other posts also. Thanks for visiting.

Monday, 16 March 2015

How to generate automatically set and get function for elements in eclipse

In this post I am going to describe you how to generate setter and getter function automatically for elements of the class.

First of all go to any of the elements of the class, right click on it and go to sources and there you will find the option of many types like this image.

Generate Getters and Setters


Click on the Generate Getters and Setters.

Now It will ask for which elements you want to create those function. Select those elements by cheking those check boxes and click on finish.

I hope it helps. If you find any problem related this describe it in comment. May be I can help you.
Thanks for visiting my blog. Share it , like it or comment it If you like my post. Check again for new posts.

Wednesday, 8 October 2014

Explain public static void main(string [] args)

Q. The question comes here is why java's main function has all the keyword like public, static  and void?

Ans. First start with public is because of scope of the main function so that it can be called out of the class . If it would be private or something else compiler can not invoke the main function out of the class.

Second static is because when main function is called there will be no object of the class so if we want to call a method of a class without initializing the object of that class then we have to make that method static. Static function can be called without initializing the object of that class.

Void is the return type of main function we can not change it because main function will not return anything in java. If it would then to whom it will return something?? Think about it......

And the argument is the array of string objects which it expects.

Two main function in java

Q. The question is that can we have two main functions in java?

Ans. Yes, We can have two main function in java but the function's prototype should be different.

 For example we can have two functions like-
public static void main(string[] args);

and second one may be

public static void main(int a);


The reason for this is that when compiler/interpreter starts executing it starts with finding a function whose prototype is similar to the first one i have written have which takes argument as a array of string objects. It does not consider the second main function because it has different argument then the one which is needed. So we can have two main functions with two different arguments and one of them should be similar to the first one.

Header files

The question always comes to our mind is why we include header files?

Ans:  The answer is simple The function which we use can be define separately in .h files. .h is the extension of header files which contains the prototype of the function and also may contain the definition but for reason of abstraction we prefer to write prototype and definition in different file prototype in .h but not necessary can be written with some other extension also.

Then we write the definition to .c file compile those files make their object files and include header file to our main file and put both .h and .c file to the same folder then use the functions written in that header file. Some header files are already in-built which we can directly use like #include<stdio.h> it is a standard input output file which we can use for printf and scanf functions etc.

The advantage is our source code file's size is less. And if we want to give someone which functions are available we can give the header .h file only. No need to give .c file we can give object file so he/she will not need to understand how the implementation is happening.

Related Posts

Related Posts Plugin for WordPress, Blogger...