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.