Tuesday, May 24, 2022

Design Patterns: Builder Pattern

 From the Definition, “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” Builder pattern builds a product and it needs a direction with the help of a concrete building.

From the Quartz scheduler, we can find real-time examples like JobBuilder, TriggerBuilder, DateBuilder, etc., which can be found here Quartz Scheduler

In springboot you can find builder pattern in multiple places.

Example:  

    interface DocumentBuilder{

        void addTitle();

        void addParagraph();

    }

void createDocument(DocumentBuilder dBuilder) {
  dBuilder.addTitle("Builder pattern application..");
dBuilder.addParagraph("Is the Builder Pattern restricted...");
dBuilder.addParagraph("The builder pattern implementation ...");
}

  class WordDocumentBuilder implements DocumentBuilder {

   ..........

  WordDocument getResult();
}

WordDocumentBuilder b = new WordDocumentBuilder();
createDocument(b); WordDocument dom = b.getResult();


We can build any kind of document by creating a concrete object to each product.

Thursday, March 3, 2022

Difference Between Spring Stereotypes

 

Till now so many asked about the differences and similarities among stereotypes in spring. Let’s look at the similarity first.

With respect to scan-auto-detection and dependency injection for BeanDefinition all these annotations (viz., @Component, @Service, @Repository, @Controller) are the same. We can use one in place of another and can still get our way around.


Differences between @Component, @Repository, @Controller and @Service

@Component

This is a general-purpose stereotype annotation indicating that the class is a spring component.

Why @Component
<context:component-scan> only scans @Component and does not look for @Controller@Service and @Repository in general. They are scanned because they themselves are annotated with @Component.

Just take a look at @Controller@Service and @Repository annotation definitions:

@Component

public @interface Service {

    ….

}

 

@Component

public @interface Repository {

    ….

}

 

@Component

public @interface Controller {

    …

}

Thus, it’s not wrong to say that @Controller@Service and @Repository are special types of @Component annotation. <context:component-scan> picks them up and registers their following classes as beans, just as if they were annotated with @Component.

Special type annotations are also scanned, because they themselves are annotated with @Component annotation, which means they are also @Components. If we define our own custom annotation and annotate it with @Component, it will also get scanned with <context:component-scan>


@Repository

This is to indicate that the class defines a data repository.

Why @Repository?

In addition to pointing out, that this is an Annotation based Configuration@Repository’s job is to catch platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception. For this, we’re provided with PersistenceExceptionTranslationPostProcessor, that we are required to add in our Spring’s application context like this:

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

This bean post processor adds an advisor to any bean that’s annotated with @Repository so that any platform-specific exceptions are caught and then re-thrown as one of Spring’s unchecked data access exceptions.


@Controller

The @Controller annotation indicates that a particular class serves the role of a controller.  

Why  @Controller?

We cannot switch this annotation with any other like @Service or @Repository, even though they look same. The dispatcher scans the classes annotated with @Controller and detects methods annotated with @RequestMapping annotations within them. We can use @RequestMapping on/in only those methods whose classes are annotated with @Controller and it will NOT work with @Component@Service@Repository etc...


@Service

@Service beans hold the business logic and call methods in the repository layer.

Why @Service?

Apart from the fact that it's used to indicate, that it's holding the business logic, there’s nothing else noticeable in this annotation for now.

 

Wednesday, January 10, 2018

Object Oriented Principles

Object Oriented programming suggests to use the following principles during the design of a software.  

Encapsulation :

Manipulation of an object’s variables by other objects or classes is discouraged to ensure data encapsulation. A class should provide methods through which other objects could access variables.  Java deletes the no longer used objects(Garbage Collection).

Abstraction :

Means, first define a class containing the variables and the behavior (methods) and afterwards you create the real objects which then all behave like the class defined it.
A class is the definition of the behavior and data. A class can not be directly be used.
A object is an instance of this class and is the real object which can be worked with.

Polymorphism :

The ability of object variables to contain objects of different classes. 


Friday, November 10, 2017

Create Schedulers in Java

At a particular point of time every developer needs to run some task background.  In java we have background clean up program nothing but Garbage Collection.

Every developer can achieve these background tasks by using java threads concepts.

They are as follows,
  1. using Simple Thread
  2. using ScheduledExecutorService
  3. using timer task

Using Simple Thread :

This simple thread is very easy to implement. Create a thread and put it in a while loop to execute forever. This will run the thread forever at back end. Provide thread methods to provide interval for running.

public class SimpleThreadTask{
public static void main(String[] args) {
  // run in for every 10 seconds
  final long timeInterval = 10000;
  Runnable runnable = new Runnable() {
  public void run() {
    while (true) {
      // ------- YOur code to run a task 
      System.out.println("Hello !!");
      // ------- ends code
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  Thread thread = new Thread(runnable);
  thread.start();
  }
}



Using ScheduledExecutorService:

This ScheduledExecutorService is provide in Java 5. 

Friday, March 4, 2016

Difference between Static binding and Dynamic binding in java ?

Difference between Static binding and Dynamic binding in java ?

Static binding : Occurs during compile time . Uses type(Class) information for binding.
      Actors :  Overloaded methods
Dynamic binding :   Occurs during run-time. Uses instance of class(Object) to resolve calling of method at run-time.
      Actors : Overridden methods

Call By Value and Call By Reference

How Java pass parameters to method ? Call by Reference or Call by Value ?


One of the tricky parts of java to understand, whether it support call by value or call by reference while using methods. Java supports both of them based on the type of the passed parameter. Let's dive into that.

Call By Value and Call By Reference :

There are two ways to pass an argument to a method
  1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.
  2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.
Here is the point to remember :  In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.
That's it Happy Learning!!!!!!

Friday, February 5, 2016

How hashCode and equals method works in HashMap or HashTable


How hashCode and equals method works in HashMap or HashTable?

Ans)  HashMap or HashTable or ConcurrentHashMap are used based on requirements when there are key value storage needed.  We should remember HashMap is backed by array in Java we will call it as bucket. 
whenever you use a get(key) method of hashcode the following are happened. 
1. Key.hashCode() method is used to find the bucket location in backing array. 
2.    In bucket, key and values are stored in form of a nested class called Entry.  If there is only one Entry at bucket location then, value from that entry is returned. 
Till now it's easy.. right? Now if the two keys has same hashcode then, we need a bit tricky to get the value for proposed key.  In this situation,  during put() operation collision had occurred, which means multiple Entry object stored in a bucket location. Each Entry keep track of another Entry, forming a  linked list data structure there.
Now the trace goes as follows,
1.   Call hashCode() method of key to find bucket location.
2.   Traverse through linked list, comparing keys in each entries using keys.equals() until it return true.
So, we use equals() method of key object to find correct entry and then return value from that. Remember key.equals() method. Many programmers mention value.equals(), which may be due to interview nervousness, but that’s incorrect. Since you don't have value object passed to get() method, there is no question of calling equals and hashCode() method on value object.  

That's it... Happy Learning!!!!



Wednesday, March 11, 2015

when to use ThreadLocal class in java

MultiThreaded Programming is always special in java. It has lot to do. In such cases we will face problems like sharing of variables (which has static specifier in my case). Synchronization is not exactly suitable then we can use thread local.
Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

ThreadLocal class is extend in Java 8 with a new method withInitial() that takes Supplier functional interface as argument. So we can use lambda expressions to easily create the ThreadLocal instance.
Here is a small example showing use of ThreadLocal and proving that every thread has it’s own copy of ThreadLocal variable.
public class XmlParserProcessor {
//Variable for each thread stack when more number of threads running simultaneously .
    public static final ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue()
        {
            return 0;
        }
    }; 

 public static void set(int skippedCount) {    
        skippedListCount.set(skippedCount);    
    }
    public static void unset() {    
        skippedListCount.remove();    
    }
    public static int get() {        
        return skippedListCount.get();    
    }

}

Tuesday, December 23, 2014

Java Memory Areas

Java Memory Areas



Java program has one or more threads. Each thread has its own stack.  All threads share same heap 




JVM Machine Architecture


Java Implementation :




  • Compiler and Virtual Machine
  • Compiler produces bytecode
  • Virtual machine loads classes on demand, verifies bytecode properties, interprets bytecode
  • Why this design?  Bytecode interpreter/compilers used before Pascal “pcode”; Smalltalk compilers use bytecode Minimize machine-dependent part of implementation Do optimization on bytecode when possible Keep bytecode interpreter simple For Java, this gives portability Transmit bytecode across network.