Saturday, 15 November 2014

How to make Spring beans thread-safe ?

Spring beans are singleton by default.
Singleton means bean identified by a particular bean id will have only one instance.

Consider the following code:
@Controller
public class MyServlet {

    @Autowired
    private HelloService service;

    @RequestMapping(value="/hello", method = RequestMethod.GET)
    public void sayHello(HttpServletRequest req, HttpServletResponse res) throws IOException {
        service.doStuff();
    }

}


public class HelloService {

    private int i = 1;

    public void doStuff() {
        System.out.println("Started " + i);
        i++;
        System.out.println(Thread.currentThread().getName() + " Done " + i);
    }
}
The output will be something like this:
32911580@qtp-28064776-0 - Started 1
7802158@qtp-28064776-2 - Started 2
32911580@qtp-28064776-0 - Done 3
7802158@qtp-28064776-2 - Done 3
This prove the "i" var is shared between multiple threads.
Now lets try to define the HelloService bean as prototype, like this
<bean id="helloService" class="my.package.HelloService" scope="prototype" />
In this case as well, the result is the same.
The only ways this can be solved is : move the declaration into doStuff() method, but it's not what we want - make the doStuff() method, but this means have locks
What I would like is have a new instance of HelloService on every call.
Since you have only one instance of MyServlet you will also have only one instance of HelloService.
One of the following spring scopes help: request A new instance for each HTTP request. session A new instance of the class for each new HttpSession created in a servlet container.
This will change the semantics of your code. If you declare the bean in the scope request your counter will always be 1.
So, to make bean thread-safe, make the bean definition scope as "request" or "session".

Wednesday, 12 November 2014

How to create a Bootable Windows 7 USB Flash Drive

Instructions to create a Bootable Windows 7 USB Flash Drive 

rufus How to Create a Bootable Windows 7 USB Flash Drive
  • Step 1: Download rufus on your computerand run it .
  • Step 2: Plug in your USB flash drive into your computer .
  • Step 3: From Rufu’s settings, Choose NTFS as the file system.
  • Step 4: Check ” Quick format ” and ”Create extended label and icon files “
  • Step 5: Check ” Create a bootable disk using ” and click the drive icon beside it to select the windows 7 ISO file .
  • Step 6: Now click on start to create a bootable window 7 USB flash drive .
After a few minutes your Windows 7 bootable  USB flash drive will be  ready for installation. Reboot your PC and set the bootable flash drive as a first boot priority in the bios settings. Save the bios settings and reboot once again to continue with the windows 7 installation process .
 Note: You have to allow booting from USB devices in your BIOS settings in order to proceed further with the windows 7 installation .

For those who install using the bootable USB Flash Drive

For newer desktop computer or laptop with USB 3.0 Ports, be sure to plug it in USB 2.0 ports to avoid the error. 

The rest proceed to the next step

To fix the problem:


  • Browse the file f6flpy-x86 or f6flpy-x64 file included in DVD drivers

  • If the file is not in the DVD, download the file in Microsoft Website

  • extract the file, put it in usb and browse the file.

Additional Resources

  • f6flpy-x64  f6flpy-x86  Windows 7 download f6flpy-x86 sata drivers

Sunday, 2 November 2014

Why should immutable class be declared as final?

We have read that to make a class immutable in Java, we should do the following,
  1. Do not provide any setters
  2. Mark all fields as private
  3. Make the class final
Now have you ever thought why is step 3 required? Why should I mark the class final?
Lets see with the help of example.
If you don't mark the class final, it might be possible for me to suddenly make your seemingly immutable class actually mutable. For example, consider this code:
public class Immutable {
     private final int value;

     public Immutable(int value) {
         this.value = value;
     }

     public int getValue() {
         return value;
     }
}
Now, suppose I do the following:
public class Mutable extends Immutable {
     private int realValue;

     public Mutable(int value) {
         super(value);

         realValue = value;
     }

     public int getValue() {
         return realValue;
     }
     public void setValue(int newValue) {
         realValue = newValue;
     }
}
Notice that in my Mutable subclass, I've overridden the behavior of getValue to read a new, mutable field declared in my subclass. As a result, your class, which initially looks immutable, really isn't immutable. I can pass this Mutable object wherever an Immutable object is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base class finalprevents this from happening.

Sunday, 5 October 2014

How to show Alert Dialog in Android applications?


How to Show Alert Dialog in Android


1
Import the AlertDialog class to your Android application.

import android.app.AlertDialog;


2
Set up the AlertDialog class to the body of your application like this. Set some properties for the AlertDialog object.

AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Reset...");
alertDialog.setMessage("Are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.setIcon(R.drawable.icon);
alertDialog.show();


3
Save your application and run. You will get the image as below.


Tuesday, 9 September 2014

What is difference between Program Files and Program Files(x86) folders in Windows 7 ?

The difference between the two is that "Program Files" is used to install softwares which are 64-bit softwares and "Program Files (x86)" is used to install softwares which are 32-bit softwares.

This is the default behavior. So if u find any softwares under "Program Files", remember they are 64-bit softwares and vice-versa.

Wednesday, 20 August 2014

Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java ?

Most of Java developer knows that wait() ,notify() and notifyAll() method of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why ?

We use wait () and notify () or notifyAll () method mostly for inter-thread communication. One thread is waiting after checking a condition e.g. In Producer Consumer example Producer Thread is waiting if buffer is full and Consumer thread notify Producer thread after he creates a space in buffer by consuming an element. calling notify() or notifyAll() issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block , all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Let’s divide this whole operation in steps to see a possibility of race condition between wait () and notify () method in Java, we will useProduce Consumer thread example to understand the scenario better:

   1. The Producer thread tests the condition (buffer is full or not) and confirms that it must wait (after finding buffer is full).
   2. The Consumer thread sets the condition after consuming an element from buffer.
   3. The Consumer thread calls the notify () method; this goes unheard since the Producer thread is not yet waiting.
   4. The Producer thread calls the wait () method and goes into waiting state.

So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang.

Now let's think how does this potential race condition get resolved? This race condition is resolved by using synchronized keyword and locking provided by java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method. Since the wait () method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait () method, we must use this lock to ensure that checking the condition (buffer is full or not) and setting the condition (taking element from buffer) is atomic which can be achieved by using synchronized method or block in Java.

Just to summarize we call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:
1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.
2) Any potential race condition between wait and notify method in Java.

You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?

This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.

main(){

t1.start();
t1.join();
t2.start();
t2.join();
t3.start();

}

What is difference between Executor.submit() and Executer.execute() method ?

The answer is that former returns an object of Future which can be used to find result from worker thread)

There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

How to create immutable class in Java and what are its pros and cons?


public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}

This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes like java.util.Date, despite storing Date into final field it can be modifiedinternally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

public final class ImmutableReminder{
    private final Date remindingDate;
  
    public ImmutableReminder (Date remindingDate) {
        if(remindingDate.getTime() < System.currentTimeMillis()){
            throw new IllegalArgumentException("Can not set reminder” +
                        “ for past time: " + remindingDate);
        }
        this.remindingDate = new Date(remindingDate.getTime());
    }
  
    public Date getRemindingDate() {
        return (Date) remindingDate.clone();
    }
}

In above example of creating immutable class, Date is a mutable object. If getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.

Pros of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:


1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.


3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers. You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.

Cons of Immutable Classes in Java

Immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.