Search This Blog

Sunday 13 April 2014

What is difference between TRUNCATE and DELETE?

What is difference between TRUNCATE and DELETE?

TRUNCATE
1. Truncate is a DDL command
2. We can remove bulk amount of records at a time
3. We can't rollback the records
4. Release the space in database
5. Truncate reset the high water mark
6. Truncate explicitly commit
                                                 DELETE
                                                 1. Delete is a DML command
                                                 2. We can delete record by record
                                                 3. We can rollback the records
                                                 4. Can’t release the memory in database
                                                 5. Delete can’t reset the water mark
                                                 6. Delete implicitly commit

Saturday 12 April 2014

How Volatile in Java works ? Example of volatile keyword in Java



Any way  Volatile keyword in Java is used as an indicator to Java compiler and  Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like AutoboxingEnumGenericsand Variable arguments ,  Java introduces some change in Java Memory Model (JMM),  Which  guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatilekeyword also  guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.



Example of volatile keyword in Java:

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.

/**
 * Java program to demonstrate where to use Volatile keyword in Java.
 * In this example Singleton Instance is declared as volatile variable to ensure
 * every thread see updated value for _instance.
 *
 * @author Javin Paul
 */

public class Singleton{
private static volatile Singleton _instance; //volatile variable 

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creatininstance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.


Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.



Let’s see another example of volatile keyword in Java:
Volatile variable example in Javamost of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't  use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory  and  "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.

 private boolean bExit;

 while(!bExit) {
    checkUserPosition();
    updateUserPosition();
 }

In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.


When to use Volatile variable in Java



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

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

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

private boolean isActive = thread;
public void printMessage(){
  while(isActive){
     System.out.println("Thread is Active");
  }
} 

without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.

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

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

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

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

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

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

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

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

8. Java volatile variable that is an object reference may be null.

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

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


Friday 11 April 2014

How to convert String to Date in Java

How to convert String to Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String which follows that pattern into Date in Java. e.g. ddMMyy or dd-MM-yyyy. Though converting String to Date is quite easy using SimpleDateFormat, but you need to remember that SimpleDateFormat is not thread-safe, which means you can not share same instance of SimpleDateFormat between multiple threads. Avoid storing SimpleDateFormat in static variable and if you want to safely share or reuse SimpleDateFormat.



Steps to Convert String into Date

How to convert String to Date in Java program with SimpleDateFormat exampleConverting String to date is rather common scenario because you may get date in a String format from any file or xml document. SimpleDateFormat in Java also support time information e.g. HH for hour , mm for minutes and SS for seconds.

Here are steps we need to use for conversion in Java:

1) Create a SimpleDateFormat object with a date pattern e.g. dd-MM-yyyy. here d denotes day of month, M is for month of year and yyyy is year in four digit e.g. 2012. Java documentation of SimpleDateFormat has complete list of date and time pattern specified.

2) Call parse() method of SimpleDateFormat and cast the result into Date object and you are done. parse() method of SimpleDateFormat throws ParseException so you need to either throw it or you can provide handling of this exception. Let’s see some SimpleDateFormat Example of converting string to date in Java to get hold of concept.       

SimpleDateFormat Example in Java


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Java program to convert String to Date in Java. This example
 * use SimpleDateFormat for String to Date conversion, you can also
 * use JODA date and time API for that.
 *
 * @author Javin
 */

public class StringToDateExample{
   
    
public static void main(String args[]) throws ParseException{
       
        DateFormat formatter = 
null;
        Date convertedDate = 
null;
       
        
// Creating SimpleDateFormat with yyyyMMdd format e.g."20110914"
        String yyyyMMdd = 
"20110914";
        formatter = 
new SimpleDateFormat("yyyyMMdd");
        convertedDate = 
(Date) formatter.parse(yyyyMMdd);
        System.
out.println("Date from yyyyMMdd String in Java : " + convertedDate);

        
//convert string to date with ddMMyyyy format example "14092011"
        String ddMMyyyy = 
"14092011";
        formatter = 
new SimpleDateFormat("ddMMyyyy");
        convertedDate = 
(Date) formatter.parse(ddMMyyyy);
        System.
out.println("Date from ddMMyyyy String in Java : " + convertedDate);

        
//String to Date conversion in Java with dd-MM-yyyy format e.g. "14-09-2011"
        String dd_MM_YY = 
"14-09-2011";
        formatter = 
new SimpleDateFormat("dd-MM-yyyy");
        convertedDate = 
(Date) formatter.parse(dd_MM_YY);
        System.
out.println("Date from dd-MM-yyyy String in Java : " + convertedDate);

        
// dd/MM/yyyy date format for example "14/09/2011"
        String stringDateFormat = 
"14/09/2011";
        formatter = 
new SimpleDateFormat("dd/MM/yyyy");
        convertedDate = 
(Date) formatter.parse(stringDateFormat);
        System.
out.println("Date from dd/MM/yyyy String in Java : " + convertedDate);

        
//parsing string into date with dd-MMM-yy format e.g. "14-Sep-11"
        
//MMMM denotes three letter month String e.g. Sep
        String ddMMMyy = 
"14-Sep-11";
        formatter = 
new SimpleDateFormat("dd-MMM-yy");
        convertedDate = 
(Date) formatter.parse(ddMMMyy);
        System.
out.println("Date from dd-MMM-yy String in Java : " + convertedDate);

        
//convert string to Date of dd-MMMM-yy format e.g. "14-September-11"
        
//MMMM denotes full month String e.g. September
        String dMMMMyy = 
"14-September-11";
        formatter = 
new SimpleDateFormat("dd-MMMM-yy");
        convertedDate = 
(Date) formatter.parse(dMMMMyy);
        System.
out.println("Date from dd-MMMM-yy String in Java : " + convertedDate);
       
        
//SimpleDateFormat also allows to include time information e.g. dd-MM-yyyy:HH:mm:SS
        String date = 
"15-09-2011:23:30:45";
        formatter = 
new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS");
        convertedDate = 
(Date) formatter.parse(date);
        System.
out.println("Date from dd-MM-yyyy:HH:mm:SS String in Java : " 
                            + convertedDate);
    
}
}

Output:
Date from yyyyMMdd String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from ddMMyyyy String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from dd-MM-yyyy String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from dd/MM/yyyy String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from dd-MMM-yy String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from dd-MMMM-yy String in Java : Wed Sep 
14 00:00:00 PST 2011
Date from dd-MM-yyyy:HH:mm:SS String in Java : Thu Sep 
15 23:30:00 PST 2011


Difference between InvokeLater and InvokeAndWait in Java Swing

Why do we need InvokeLater method in Swing?


invokeAndWait invokeLater and SwingUtilities in java As we all know java swing is not threadsafe , you can not update swing component like JButton, JLable , JTable or JTree from any thread , they all needs to be updated from just one thread and we call it Event Dispatcher thread or EDT in short. Event Dispatcher thread is used to render graphics for java swing component and also process all events corresponding to key press, mouse click or any action. So if you want to update a particular swing component suppose label of a JButton from Yes to No you need to do this in Event Dispatcher thread and for doing this you need InvokeLater. invokeLater is used to perform any task asynchronously on AWT Event Dispatcher thread.

What is invokeLater in Java Swing


Invokelater is a method in java on swing package and belongs to swingutilities class. Invokelater is used by java swing developer to update or perform any task on Event dispatcher thread asynchronously.invokeLater has been added into Java API from swing extension and it’s belong to SwingUtilities class.


How does invokeLater works in Java Swing


If you see the signature of invokeLater method you will find that invokeLater takes a Runnable object and queues it to be processed by EventDispatcher thread. EDT thread will process this request only after sorting out all AWT pending events or requests. Even if invokeLater is called directly form Event dispatches thread processing of Runnable task still be done only after processing all pending AWT Events. An important point to note is that in case if run method of Runnable task throw any exception then AWT Event dispatcher thread will unwind and not the current thread.

Why do we need InvokeAndWait method in Swing


As we know that Swing is not thread-safe and we can not update the Swing component or GUI from any thread. If you try to update GUI form any thread you will get unexpected result or exception, it could be your GUI might not be visible or simply disappered. Only method which is thread-safe in swing is repaint() and revalidate(). On the other hand InvokeAndWait allows us to update the GUI from EDT thread synchronously. InvokeAndWait method also belongs to swingUtility class like invokeLater.


How does InvokeAndWait works in Java Swing


If you look at the signature of invokeAndWait method you will see that it takes a Runnable object and run method of that Runnable is executed synchronously on EDTThis is a blocking call and wait until all pending AWT events gets processed and run() method completes. Its a preferred way of updating GUI form application thread.

Important point to note is that it should not be called from EventDispatcher thread unlike invokeLater; it’s an error because it will result in guaranteed deadlock. because if you cal invokeAndWait from EDT thread it will be an AWT event and caller of invokeAndWait will wait for EDT thread to complete and EDT will wait caller thread to be completed so they will be locked in deadlock. Its also important to remember that if run() mehtod of Runnable object throw exception then its caught in AWT EDT thread and rethrown as InvocationTargetException on caller thread.

Example of InvokeLater in Java Swing


Here is an example of invokeLater() in Swing which will demonstrate that in case of invokeLater application thread doesn’t block.

Runnable pickHighBetaStock = new Runnable() {
public void run() {
System.out.println("High beta Stock picked by  " + Thread.currentThread());
}
};

SwingUtilities.invokeLater(pickHighBetaStock);
System.out.println("This might well be displayed before the other message. if Event-dispatcher thread is busy");


Example of using InvokeAndWait in Java Swing


In this example of InvokeAndWait we will see that Application thread will block until Runnable object passed to EDT has been executed.

final Runnable pennyStockPicker = new Runnable() {
public void run() {
System.out.println("pick penny Stock on " + Thread.currentThread());
}
};

Thread stockPicker = new Thread() {
public void run() {
try {
SwingUtilities.invokeAndWait(pennyStockPicker);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("This will finish after pennyStockPicker thread because InvokeAndWait is block call" + Thread.currentThread());
}
};
stockPicker.start();

Difference on InvokeLater vs InvokeAndWait in Swing

Swingutilies provides us two methods for performing any task in Event dispatcher thread. Now let's see what the difference between invokeLater and InvokeAndWait is and when to use invokeLater.

1) InvokeLater is used to perform task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously.

2) InvokeLater is non blocking call while InvokeAndWait will block until task is completed.

3) If run method of Runnable traget throws an Exception then in case of invokeLater EDT threads unwinds while in case of invokeAndWait exception is caught and rethrown as InvocationTargetException.

4) InvokeLater can be safely called from Event Dispatcher thread while if you call invokeAndWait from EDT thread you will get an error because as per java documentation of invokeAndWait it clearly says that "this request will be processed only after all pending events" and if you call this from EDT this will become one of pending event so its a deadlock because caller of InvokeAndWait is waing for completion of invokeAndWait while EDT is waiting for caller of InvokeAndWait.

5) InvokeLater is more flexible in terms of user interaction because it just adds the task in queue and allow user to interact with system while invokeAndWait is preffered way to update the GUI from application thread.


In Summary we can just say that since Swing is not thread-safe and we  cannot update different Swing GUI components on any thread other-than Event dispatcher Thread we need to use InvokeAndWait or InvokeLater to schedule any Runnable task for AWT Event dispatcher Thread. InvokeAndWait is synchronous and blocking call and wait until submitted Runnable completes while InvokeLater is asynchronous and non-blocking it will just submit task and exit."

That’s all on InvokeAndWait() and InvokeLater() method of SwingUtilities class. They are very important while doing GUI programming on Swing as well as this is very popular interview questions which I have discussed on my latest post on swing interview questions asked in Investment bank