Monday, May 2, 2016

Take thread dumps from a JVM on UNIX or Windows?

How can I take thread dumps from a JVM on UNIX or Windows?

A thread dump is a list of all the Java threads that are currently active in a Java Virtual Machine (JVM).
There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump. A good practice is to take 10 thread dumps at a regular interval (for example, one thread dump every ten seconds).

Step 1: Get the PID of your Java process


The first piece of information you will need to be able to obtain a thread dump is your Java process's PID.
The Java JDK ships with the jps command which lists all Java process ids. You can run this command like this:
jps -l 70660 sun.tools.jps.Jps 70305


Note: In Linux and UNIX, you may have to run this command as sudo -u user jps -l, where "user" is the username of the user that the Java process is running as.
If this doesn't work or you still cannot find your Java process, (path not set, JDK not installed, or older Java version), use
  • UNIX, Linux, and Mac OS X: ps -el | grep java
  • Windows: Press Ctrl+Shift+Esc to open the task manager and find the PID of the Java process

Step 2: Request a thread dump from the JVM  

jstack
If installed/available, we recommend using the jstack tool. It prints thread dumps to the command line console.
To obtain a thread dump using jstack, run the following command:
jstack <pid>
You can output consecutive thread dumps to a file by using the console output redirect/append directive:
jstack <pid> >> threaddumps.log
Notes:
  • The jstack tool is available since JDK 1.5 (for JVM on Windows it's available in some versions of JDK 1.5 and JDK 1.6 only).
  • jstack works even if the -Xrs jvm parameter is enabled
  • It's not possible to use the jstack tool from JDK 1.6 to take threaddumps from a process running on JDK 1.5.
  • In Linux and UNIX, you may need to run this command as sudo -u user jstack <pid> >> threaddumps.log, where "user" is the user that the Java process is running as.
  • In Windows, if you run jstack and get the error "Not enough storage is available to process this command" then you must run jstack as the windows SYSTEM user.  You can do this by using psexec which you can download here. Then you can run jstack like this: psexec -s jstack <pid> >> threaddumps.log

jstack script

Here's a script, taken from eclipse.org that will take a series of thread dumps using jstack.  It also takes the thread level cpu usage using top command as well.
#!/bin/bash
if [ $# -eq 0 ]; then
    echo >&2 "Usage: jstackSeries <pid> <run_user> [ <count> [ <delay> ] ]"
    echo >&2 "    Defaults: count = 10, delay = 0.5 (seconds)"
    exit 1
fi
pid=$1          # required
user=$2         # required
count=${3:-10}  # defaults to 10 times
delay=${4:-0.5} # defaults to 0.5 seconds
while [ $count -gt 0 ]
do
    sudo -u $user top -H -b -n1 -p $pid >top.$pid.$(date +%H%M%S.%N) &
    sudo -u $user jstack -l $pid >jstack.$pid.$(date +%H%M%S.%N)
    sleep $delay
    let count--
    echo -n "."
done

Just run it like this:
sh jstackSeries.sh [pid] [cq5serveruser] [count] [delay]
For example:
sh jstackSeries.sh 1234 cq5serveruser 10 3
  • 1234 is the pid of the Java process
  • cq5serveruser is the Linux or UNIX user that the Java process runs as
  • 10 is how many thread dumps to take
  • 3 is the delay between each dump
Note: The top output has the native thread id in decimal format while the jstack output has the nid in hexadecimal.  You can match the high cpu thread from the top output to the jstack output by converting the thread id to hexadecimal.
Thread Dump Tool for Adobe Experience Manager
If you are using Adobe Experience Manager product then you can install this tool to have a simple UI for generating thread dumps.

Alternative ways to obtain a thread dump

If the jstack tool is not available to you then you can take thread dumps as follows:

Note: Some tools cannot take thread dumps from the JVM if the commandline parameter -Xrs is enabled. If you are having trouble taking thread dumps then please see if this option is enabled.
UNIX, Mac OS X, and Linux (JDK 1.4 or lesser version)
On UNIX, Mac OS X, and Linux, you can send a QUIT signal to the Java process to tell it to output a thread dump to standard output.
  1. Run this command to do this:
    kill -QUIT <pid>
    You may need to run this command as sudo -u user kill -QUIT <pid> where "user" is the user that the Java process is running as.
  2. If you are starting CQSE using the crx-quickstart/server/start script then your thread dumps will be output to crx-quickstart/server/logs/startup.log. If you are using a third-party application server such as JBoss, WebSphere, Tomcat, or other, see the server's documentation to find out which file the standard output is directed to.
Windows:
JDK 1.X
  1. Download javadump.exe (attached below).
  2. Start the JVM with these three arguments (they must be in the right order):
    -XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput -XX:LogFile=C: mpjvmoutput.log
  3. Press Ctrl+Shift+Esc to open the Task Manager.
  4. Find the PID of the Java process.
  5. From the command line, run
    javadump.exe [pid]
  6. The thread dump will appear in the jvmoutput.log file mentioned in step 2.
JDK 1.6
Get a thread dump from jconsole tool, by using a plugin: [0]
Here's how you can request a thread dump:
  1. Add the following parameter to the jvm running Communique : -Dcom.sun.management.jmxremote
  2. Download and install JDK 1.6 (if not done yet).
  3. Download and extract the Thread Dump Analyzer utility. [1]
  4. Run jconsole.exe of JDK 1.6:
                                jconsole.exe -pluginpath /path/to/file/tda.jar
  5. Click the Thread dumps tab.
  6. Click the Request Thread Dump link.

Thursday, March 17, 2016

Virtusa interview questioniors for senior developers

1. What is the difference between shallow copy and deep copy?
2. what is the use of generated in hibernate and what exactly the native is?
3. What are all the collections mapping and association mappings in hibernate?
4. What is the use of hibernate.cfg.xml?
5. In parent child relationship, which annotation is used to affect the changes from parent to child.
6. What is the syntax of cascade annotation?
7. How do you handle sessionfactory in hibernate?
8. What are all the relationships are exists in hibernate?
9. What are all the scopes availabe in spring?
10. What is prototype Scope?
11. How do you handle prorotype scope in singleton bean?
12. What is lamda expressions?
13. What is the difference between jdk 6 and jdk 7?
14. What is spring boot and groovy, gradle in spring?
15. Difference between servlet and jsp?
16. What are all the design patterns you have used in your project?
17. What is singleton design pattern and write the code for that pattern
18. What is ConcurrentModificationException?
19. What is the difference between Enumeration and  Iterator?
20. What is fail-fast and fail-safe iterator?

Sunday, March 13, 2016

Syntel Interview questions for senior developers

1. How do you handle session timeout by core java?
2. If there are 4 requests sending from the single servlet, what database will do?
3. There is sciplet tag and declaration tag nad both are having the value int a = 4.
   Now you are printing the value using expression tag, the value will be printed out from which tag scriplet or declaration?
4. How do you handle different action in the controller using struts?
5. In struts which method is used to handle the requests?
6. How do you deploy a war file using ant in Linux?
7. what are the xml files are required to configure hibernate?
8. What is the use .hbm and .cfg.xml in hibernate?
9. Which tool have been used for appllication deployment?
10. How to get the checkbox values in servlet?

Friday, March 11, 2016

Excelacom Java interview questions for Senior Lead Developer

1. What is multi action controller in spring?
2. How do you connect your controller with jsp in spring mvc?
3. What is auto-wiring?
4. What design patterns you worked in and tell some explanation among one of them.
5. What part you have worked in jquery?
6. How do you use ajax in jquery?
7. In which situation you will use abstract class and tell me the example
8. What are all the ways you will resolve performance issues in your application?
9. How do you handle memory leaks
10. What is the difference between xml and json
11. Difference between and and maven
12. String and StringBuffer. Performance wise which one you will choose?
13. Why string is immutable?
14. String a = "abc", String b = "abc", what will happen if a pointing to the reference b?
15. How many members you have managed in your team?

Tuesday, March 8, 2016

How inheritence achieved in spring?

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. Using parent and child bean definitions can save a lot of typing. Effectively, this is a form of templating.

If you work with an ApplicationContext interface programmatically, child bean definitions are represented by the ChildBeanDefinition class. Most users do not work with them on this level, instead configuring bean definitions declaratively in something like the ClassPathXmlApplicationContext. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.
 
<bean id="inheritedTestBean" abstract="true"
    class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass"
      class="org.springframework.beans.DerivedTestBean"
      parent="inheritedTestBean" init-method="initialize">

  <property name="name" value="override"/>
  <!-- the age property value of 1 will be inherited from  parent -->

</bean>

A child bean definition uses the bean class from the parent definition if none is specified, but can also override it. In the latter case, the child bean class must be compatible with the parent, that is, it must accept the parent's property values.

 A child bean definition inherits scope, constructor argument values, property values, and method overrides from the parent, with the option to add new values. Any scope, initialization method, destroy method, and/or static factory method settings that you specify will override the corresponding parent settings.
The remaining settings are always taken from the child definition: depends on, autowire mode, dependency check, singleton, lazy init.

The preceding example explicitly marks the parent bean definition as abstract by using the abstract attribute. If the parent definition does not specify a class, explicitly marking the parent bean definition as abstract is required, as follows:
 
<bean id="inheritedTestBeanWithoutClass" abstract="true">
    <property name="name" value="parent"/>
    <property name="age" value="1"/>
</bean>

<bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean"
    parent="inheritedTestBeanWithoutClass" init-method="initialize">
  <property name="name" value="override"/>
  <!-- age will inherit the value of 1 from the parent bean definition-->
</bean>

The parent bean cannot be instantiated on its own because it is incomplete, and it is also explicitly marked as abstract. When a definition is abstract like this, it is usable only as a pure template bean definition that serves as a parent definition for child definitions. Trying to use such an abstract parent bean on its own, by referring to it as a ref property of another bean or doing an explicit getBean() call with the parent bean id, returns an error. Similarly, the container's internal preInstantiateSingletons() method ignores bean definitions that are defined as abstract.

Note
ApplicationContext pre-instantiates all singletons by default. Therefore, it is important (at least for singleton beans) that if you have a (parent) bean definition which you intend to use only as a template, and this definition specifies a class, you must make sure to set the abstract attribute to true, otherwise the application context will actually (attempt to) pre-instantiate the abstract bean.

Monday, March 7, 2016

Choose the right collection for your appication?


Choose the right Java Map interface

HashMap – use this implementation if the order of items while iterating is not important to you. HashMap has better performance compared to TreeMap and LinkedHashMap
TreeMap – is ordered and sorted but slower compared to HashMap. TreeMap has ascending order of keys, according to its Comparator
LinkedHashMap – it orders items by key during insertion

Choose the right Java List interface

ArrayList – items are ordered during insertion. Search operations on ArrayLists is faster compared to search operations on LinkedLists
LinkedList – has fast adding to the start of the list, and fast deletion from the interior via iteration

Choose the right Java Set interface

HashSet – use this implementation if the order of items while iterating is not important to you. HashSet has better performance compared to TreeSet and LinkedHashSet
LinkedHashSet – it orders items during insertion
TreeSet – has ascending order of keys, according to its Comparator

Sunday, March 6, 2016

Java interview questions for senior developers from TechMahindra

1. What is the need of using collections in java?
2. How to get unique id using collections?
3. Write the linked list algorithms
4. How do you write own class to order the hashmap elements by using arraylist but not using comparator interface?
5. Write a join query for employee(id,name) and employee address (id,addresd) table
 6. Why you choose spring framework instead of other frameworks
7. How do you achieve transactions in spring

Saturday, March 5, 2016

Java Study Notes 1

The constructors and initializers cannot be synchronized and a compiler error will occur if you put synchronized front of a constructor. But constructors and initializers of a class can contain synchronized blocks The interface's methods cannot be declared synchronized. The Synchronization is part of the implementation but not part of the interface.

Can float and double value represent decimal number exactly?

The int and long type do represent integral numbers exactly, but the value of float and double type do not represent decimal numbers exactly.
The float and double perform binary floating-point arithmetic. It only provide approximate of the results of arithmetic operations because they are binary and cannot exactly represent negative powers of then (i.e., 10 -1); If you want an exact representation you can use the java.math.BigDecimal class. For example,
import java.math.BigDecimal;

public class Change {

  public static void main(String args[]) {

    BigDecimal bigD1 = new BigDecimal("2.00");

    BigDecimal bigD2 = new BigDecimal("1.10"); 

    System.out.println(bigD1.subtract(bigD2));

  }

}

Are true, false, and null Java keywords?

The true, false, and null are not Java keywords, but they are reserved words. Remember that all keywords are reserved words, but not vice versa. Java keywords and reserved words can not be used as identifiers such as variable, class, or method names.
Java Language Specification has differentiated between the two to specify that reserved literals represents a value for a primitive,object or null type. On the other hand, you cannot assign keywords as values to primitives,objects or null type.

LinkedHashMap vs. HashMap?

  • A LinkedHashMap differs from HashMap in that the order of elements is maintained.
  • A HashMap has a better performance than a LinkedHashMap because a LinkedHashMap needs the expense of maintaining the linked list. The LinkedHashMap implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list.
  • Both of their methods are not synchronized.
Let's take a look their API documentations:
The HashMap is a hash table with buckets in each hash slot. Like in the API documentation:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
The LinkedHashMap is a linked list implementing the map interface. As said in the API documentation:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
Capacity of any collection class is the maximum number of elements collection can hold. size of collection must be less than or equal to its capacity. Though in reality, collection resize themselves even before it reaches its capacity, controlled by laod factor.

The initial capacity is nothing but the number of buckets when the hash table is created, capacity is automatically increased when hash table get full of element.
 Load factor is a measurement of how full hash table is allowed or number of elements in the hash table. When the hash table gets full of element its capacity automatically gets increased.

Difference between array and arraylist
1.       Array is static; its fixed size and cant change once created. ArrayList is dynamic; it can be resizable.
2.       ArrayList is a class from collections framework but array is native programming component
3.       Array can store primitives as well as objects and array list will store only the wrapper classes.
4.       Array is not generic but arraylist is
5.       We can remove element from arraylist but not from array.
6.       Array can be multidimensional and arraylist is one dimensional
7.       Array provide length attribute and arraylist provides size() method but both are different, length is capacity and size return number of elements.

Map is one of the most important interface in collection framework. It provide the hash table data structure functionality by using hashmap, linked hashmap, treemap, etc.,
If the map already contains a mapping for the key, the old value is replaced.

Hashmap is used to store the key and value pairs using hashing based datastructure. It doesn’t provide any ordering. It allows one null key and many null values.
Treemap based on NavigableMap implementation provides you sorting, on top of hashing. It doesn’t allow null keys.
LinkedHashmap maintaining mappings in order as they are inserted into Map. It also allows null keys and values.
EnumMap – storing mapping with enum constants as keys.
WeakHashMap – creating a garbage collector friendly cache, where values become eligible for garbage collection as soon as there is no other reference to them apart from keys in weakhashmap.
IdentityHashMap – used to creating a map which uses identity instead of equality for comparing keys since identity equality is rare, you get less number of collisions.
ConcurrentHashMap – It is used in concurrent programming. Multiple reader can access the Map concurrently  while a portion of Map gets locked for write operation. Its fail safe while doing iteration of elements which doesn’t throw ConcurrentModificationException.

CopyOnWriteArrayList achieves thread-safety by creating a separate copy of List for each write operation.Its similar to concurrenthashmap and can say it’s the replacement for synchronized arraylist.

BlockingQueue makes it easy to implement producer-consumer design pattern by providing inbuilt blocking support for put() and take() method. put() method will block if Queue is full while take() method will block if Queue is empty. ava 5 API provides two concrete implementation of BlockingQueue in form of ArrayBlockingQueue and LinkedBlockingQueue, both of them implement FIFO ordering of element. ArrayBlockingQueue is backed by Array and its bounded in nature while LinkedBlockingQueue is optionally bounded.

Deque and BlockingDeque
Deque interface is added in Java 6 and it extends Queue interface to support insertion and removal from both end of Queue referred as head and tail. Java6 also provides concurrent implementation of Deque like ArrayDeque and LinkedBlockingDeque. Deque Can be used efficiently to increase parallelism in program by allowing set of worker thread to help each other by taking some of work load from other thread by utilizing Deque double end consumption property.

ConcurrentSkipListMap and ConcurrentSkipListSet provide concurrent alternative for synchronized version of SortedMap and SortedSet. For example instead of using TreeMap or TreeSet wrapped inside synchronized Collection, You can consider using ConcurrentSkipListMap or ConcurrentSkipListSet from java.util.concurrent package.

NavigableMap in Java 6 is an extension of SortedMap  like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey.

Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other.
Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine; the reverse process of creating object from binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream

What is difference between start and run method? Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.

What is deadlock?
Answer is simple, when two or more threads are waiting for each other to release lock and get stuck for infinite time, situation is called deadlock . It will only happen in case of multitasking.
E.g.,
Method1(){
Synchronized(String.class){
System.out.println(“acquire lock for string class”);
Synchronized(Integer.class){
System.out.println(“acquire lock for integer class”)
}
       }
}
Method2(){
Synchronized(Integer.class){
System.out.println(“acquire lock for string class”);
Synchronized(String.class){
System.out.println(“acquire lock for integer class”)
}
       }
}

CountDownLatch and CyclicBarrier in Java are two important concurrency utility which is added on Java 5 Concurrency API. Both are used to implement scenario, where one thread has to wait for other thread before starting processing but there is difference between them. Key point to mention, while answering this question is that CountDownLatch is not reusable once count reaches to zero, while CyclicBarrier can be reused even after barrier is broken.

Wednesday, March 2, 2016

Difference between wait and sleep methods

1) wait() method must be called from synchronized context i.e. from synchronized method or block in Java. If you call wait method without synchronization, it will throw IllegalMonitorStateException in Java.

2) wait() method operates on Object and defined in Object class while sleep operates on current Thread and defined in java.lang.Thread class.

3) wait() method releases the lock of object on which it has called, it does release other locks if it holds any while sleep method of Thread class does not release any lock at all.

4) wait() is a non static method while sleep() is static method in Java.

Tuesday, March 1, 2016

3 ways to convert array to ArrayList

Yes. We can do it this from three ways.

1. Arrays.asList(...)
      e.g.,
             String[] array = {"value1", "value2", "value3", "value4"};
             List<String> arrayList = Arrays.asList(array);
 
2. Collections.addAll(...)
       e.g., Collections.addAll(exampleList, "Value1", "Value2" , "Value3");

3. In spring framework---> CollectionUtils.arrayToList(...)
      e.g.,
            String [] array = {"value1", "value2", "value3", "value4"};           
            List<String> arrayList = CollectionUtils.arrayToList(array);

Saturday, February 27, 2016

What happens if a class doesn't implement all the methods defined in the interface?


A class must implement all methods of the interface, unless the class is declared as abstract. There are only two choices:
  • 1.Implement every method defined by the interface.
  • 2.Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects. 

The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e., non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The supclass may not implement the interface at all and just method signature is matched. For example,
interface MyInterface {  
  void m() throws NullPointerException;
} 

class SuperClass {
//NOTE : SuperClass class doesn't implements MyInterface interface 
  public void m() {
    System.out.println("Inside SuperClass m()");
  }
}

class SubClass extends SuperClass implements MyInterface {
}

public class Program {  
  public static void main(String args[]) {
    SubClass s = new SubClass();
    s.m();
  }
}


SimpleDateFormat and DateFormat

SimpleDateFormat is a class used to format and parsing dates in a locale sensitive manner. It is used to format date into text and parse text into date.
SimpleDateFormat is extends DateFormat class which is an abstract class for date/time formatting subclasses and provides many class methods for obtaining date/time matters based on any given locale. package com.lea.oops;

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

public class SimpleDateFormatExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Date date = new Date();
       
        String str = date.toString();
        System.out.println(str);
       
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        System.out.println(dateFormat.format(date));
    }

}

Abstraction in Java

What is abstraction? Abstraction is the concept of segregate the implementation of interface. It will focus only on essential details instead of showing the full implementation details. Abstraction can be applied through abstract class and interface.
Abstract class is something which is incomplete and provide common information for the subclasses. You cannot create instance for abstract class. If you want to use it you need to make it complete or concrete by extending it.
When do you use abstraction? When you know something needs to be there but not sure how exactly it should like.
Abstraction key points
  • Use abstraction if you know something needs to be in class but implementation of that varies. 
  • You cannot create instance of abstract class using new operator. 
  •  Abstract class can have constructor 
  •  A class automatically become abstract class when any of its method declared as abstract. 
  •  Abstract method does not have method body 
  •  Variable cannot be made abstract. Its only for class and methods 
  •  If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be concrete class.

Friday, February 26, 2016

Why abstract class can have constructor in Java?

The main reason is, when any class extend abstract class, constructor of sub class will invoke constructor of super class either implicitly or explicitly.

Write a program to find the first non repeated character in a String?

package com.lea.oops;

import java.util.HashMap;
import java.util.Scanner;

public class FirstNonRepeatedCharacter {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
       
        char c = firstNonRepeatedCharacter(s);
       
        System.out.println(c);
       
    }

    public static Character firstNonRepeatedCharacter(String str){
       
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
       
        int i, length;
        Character c;
       
        length = str.length();
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
           
            if (hashMap.containsKey(c)) {
                hashMap.put(c, hashMap.get(c)+1);
            }else{
                hashMap.put(c, 1);
            }
        }
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
            if (hashMap.get(c) == 1) {
                return c;
            }
        }
       
        return null;
    }
}

Wednesday, February 24, 2016

Java Timer and TimerTask Tutorials

java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Timer class uses Object wait and notify methods to schedule the tasks. TimerTask is an abstract class and we inherit it to provide concrete implementation. TimerTask class implements Runnable interface so it is a thread and hence your implementation of TimerTask is also a thread.

Example to print a repeated task for 5 times.
package com.lea.oops;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {

    Timer timer;
   
    public TimerTaskExample() {
        timer = new Timer();
        timer.schedule(new MyReminder(),  0, 1 * 1000);
    }
   
    class MyReminder extends TimerTask{
        int loop = 5;
      
        @Override
        public void run() {
            if (loop > 0) {
                System.out.println("Message "+loop+ "..!\n");
                loop--;
            } else {
                System.out.println("\nThat's it.. Done..!");
                timer.cancel();
            }
           }
      
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        new TimerTaskExample();
        System.out.println("Task scheduled..");
    }

}

Friday, February 19, 2016

How to use static fields within Spring XML Configuration

When configuring Spring through XML, you can use static fields in a similar way you use instances defined in the same XML or elsewhere. This is possible by using the util namespace as highlighted below.

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.1.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

  <bean id="myObject" class="com.javacreed.examples.howto.spring.StaticInXml">
    <constructor-arg>
      <list>
        <util:constant static-field="com.javacreed.examples.howto.spring.MyFields.OBJECT_1" />
      </list>
    </constructor-arg>
  </bean>

</beans>

How to make @RequestParam Optional?

A @RequestParam can be set as optional, by simply providing a default value to it as shown in the following example

@Controller
public class MyController {

  @RequestMapping(value = "/myApp", method = { RequestMethod.POST, RequestMethod.GET })
  public String doSomething(@RequestParam(value = "name", defaultValue = "anonymous") final String name) {
  // Do something with the variable: name
  return "viewName";
  }

}

How to get Auto-Generated Key with JdbcTemplate

Spring provides GeneratedKeyHolder class which can be used to retrieve the auto generated values.

The following class shows how to retrieve the auto generated key after a new value is added to the table.

package com.javarewind.examples.spring;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class ExampleDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public long addNew(final String name) {
    final PreparedStatementCreator psc = new PreparedStatementCreator() {
      @Override
      public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
        final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)",
            Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        return ps;
      }
    };

    // The newly generated key will be saved in this object
    KeyHolder holder = new GeneratedKeyHolder();

    jdbcTemplate.update(psc, holder);

    long newNameId = holder.getKey().longValue();
    return newNameId;
  }
}

Thursday, February 18, 2016

OOPs Concepts


Abstaractions, Encapsulation, Inheritance, Polymorphism and Composition are the important concepts for the object oriented programming/designs.

Abstraction:

Abstraction focuses only on outside view of an object. Helps us to identify which information should be visible and which information should be hidden.

Encapsulation:

Its a mechanism to hide the data, internal structure, and implementation details of an object.

All interaction with the object is through a public interface of operations.

Encapsulation means any kind of hiding:

-- Data Hiding
-- Implementation of Hiding
-- Class Hiding (Behind abstarct class or interface)
-- Design Hiding
-- Instantiation hiding

       Data Hiding: Use private members and appropriate accessors and mutators when possible.

       For example:
      • Replace
                 public float accuracy;
      • With
               private float accuracy;
               public float getAccuracy ( ) {
                  return (accuracy);
              }
              public void setAccuracy (float acc) {
                  accuracy = acc;
             }

                   
Inheritance [IS-A Reletionship]:

Method of reuse in which new functionality is obtained by extending the implementation of an existing object.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Polymorphism:

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. 

Composition [HAS-A Relationship]:

Method of reuse in which new functionality is obtained by creating an object composed of other objects.

When we say “one object is composed with another object” we mean that they are related by a HAS-A
relationship.


The new functionality is obtained by delegating functionality to one of the objects being composed.
 

Composition encapsulates several objects inside another one.


 

Wednesday, February 3, 2016

What are checked and unchecked exceptions?

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
3) Checked Exception represent scenario with higher failure rate while Unchecked Exception are mostly programming mistakes.

Example of checked Exception 

IOException
DataAccessException
ClassNotFoundException
InvocationTargetException 

Example of unchecked Exception

NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Why synchronized method is throwing error in interface?

Interface methods are abstract and will not have implementation details but synchronization is part of the implementation. So that its throwing compile time error while declaring synchronized methods in interface.