Friday, 12 October 2018


  • If your code is executing in a multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior.
  • Synchronization in Java will only be needed if shared object is mutable.
  • JVM guarantees that Java synchronized code will only be executed by one thread at a time
  • we can not have synchronized variable in java. Using synchronized keyword with a variable is illegal and will result in compilation error. You can use java synchronized keyword only on synchronized method or synchronized block.
  • we need to take care is that static synchronized method locked on class object lock and nonstatic synchronized method locks on current object (this). So it’s possible that both static and nonstatic java synchronized method running in parallel
  • public class Counter{ private static int count = 0; public static synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } }
  • In this example of Java, the synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on the same object and can run in parallel which may result in the incorrect count.
  • Whenever a thread enters into java synchronized method or blocks it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. The lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
  • Object level lock
    •  Java Thread acquires an object level lock when it enters into an instance synchronized java method 
  • Class level lock 
    • Acquires a class level lock when it enters into static synchronized java method.
  • Re-entrant Lock
    •  if a java synchronized method calls another synchronized method which requires the same lock then the current thread which is holding lock can enter into that method without acquiring the lock.
  • Locks
    • One Major disadvantage of Java synchronized keyword is that it doesn't allow concurrent read, which can potentially limit scalability. 
    • By using the concept of lock stripping and using different locks for reading and writing, you can overcome this limitation of synchronized in Java. You will be glad to know that java.util.concurrent.locks.ReentrantReadWriteLock provides ready-made implementation of ReadWriteLock in Java.
  • One more limitation of java synchronized keyword is that it can only be used to control access to a shared object within the same JVM. If you have more than one JVM and need to synchronize access to a shared file system or database, the Java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
  • Java synchronized block is better than java synchronized method in Java because by using synchronized block you can only lock critical section of code and avoid locking the whole method which can possibly degrade performance.
  • Do not synchronize on the non-final field on synchronized block in Java. because the reference of the non-final field may change anytime and then different thread might synchronizing on different objects i.e. no synchronization at all.
  • Locks vs Synchronisation
    • Synchronisation
      • One thread at a time and other threads waiting
      • Cannot do multi read even no write happening
      • Cannot interrupt any thread which is waiting for acquire lock
      • Cannot change priority of threads
    • Locks
      • Lock comes under java.util.concurrent.Lock
      • One thread at a time and other threads waiting
      • ReetantReadWriteLock.readLock
      • ReetantReadWriteLock.writeLock
      • Allows multiple reads as long as no write happens
      • tryLock ->if lock available lock it 
      • Fairness Policy
        • Longest waiting will get higher priority
      • Able interrupt thread

Thursday, 11 October 2018


  • S.O.L.I.D is an acronym for the first five object-oriented design(OOD) principles by Robert C. Martin, popularly known as Uncle Bob.
  • These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend
  • They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.
    • S - Single-responsiblity principle
    • O - Open-closed principle
    • L - Liskov substitution principle
    • I - Interface segregation principle
    • D - Dependency Inversion Principle
  • Single-responsibility Principle(like Encapsulation)
    • A class should have one and only one reason to change, meaning that a class should have only one job.
    • SOLID Principles and Design Patterns plays a key role in achieving all of the above points.
      • Each class and module should focus on a single task at a time
      • Everything in the class should be related to that single purpose
      • There can be many members in the class as long as they related to the single responsibility
      • With SRP, classes become smaller and cleaner
      • Code is less fragile
      • class Circle { public $radius; public function **construct($radius) { $this->radius = $radius; } } class Square { public $length; public function **construct($length) { $this->length = $length; } }
  • Open-closed Principle(like Abstraction)
    • Objects or entities should be open for extension, but closed for modification.
    • This simply means that a class should be easily extendable without modifying the class itself. 
    • Implementation
      •  The simplest way to apply OCP is to implement the new functionality on new derived (sub) classes that inherit the original class implementation.
      • Another way is to allow client  to access the original class with an abstract interface
  • Liskov substitution principle(like Aggregation)
    • Substitutability is a principle in object-oriented programming and it states that, in a computer program, if S is a Subtype of T, then objects of type T may be replaced with objects of type S
    •  This principle is just an extension of the Open Close Principle 
  • Interface segregation principle(avoid unused methods from interface)
    • The interface-segregation principle (ISP) states that "no client should be forced to depend on methods it does not use".
    • Which means, Instead of one fat interface many small interfaces are preferred based on groups of methods with each one serving one submodule 
  • Dependency Inversion principle
    • High-level modules should not depend on low-level modules. Both should depend on abstractions.
    • Abstractions should not depend on concrete. Concrete should depend on abstractions.
    • Exmaple:
      • The PasswordReminder class should not care what database your application uses, to fix this again we "code to an interface", since high level and low level modules should depend on abstraction, we can create an interface:

Tuesday, 9 October 2018


  • Prototype pattern refers to creating duplicate object 
  • This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.
  • // Prototype pattern public abstract class Prototype implements Cloneable { public Prototype clone() throws CloneNotSupportedException{ return (Prototype) super.clone(); } } public class ConcretePrototype1 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype1)super.clone(); } } public class ConcretePrototype2 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype2)super.clone(); } }


  • This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.
  • SingleObject class have its constructor as private and have a static instance of itself.                                         
  1. Create a Singleton Class.
public class SingleObject { //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } }
  1. Get the only object from the singleton class.
public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject(); //Get the only object available SingleObject object = SingleObject.getInstance(); //show the message object.showMessage(); } }

  • Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
  • In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.
  • We are going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We create an abstract factory class AbstractFactory as next step. Factory classes ShapeFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.
  • Step 1
  • public interface Shape { void draw(); }
  • Step 2
  • public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }

  • public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }

  • public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
  • Step 3
  • public interface Color { void fill(); }
  • Step 4
  • public class Red implements Color { @Override public void fill() { System.out.println("Inside Red::fill() method."); } }

  • public class Blue implements Color { @Override public void fill() { System.out.println("Inside Blue::fill() method."); } }

  • public class Green implements Color { @Override public void fill() { System.out.println("Inside Green::fill() method."); } }
  • Step 5
  • public abstract class AbstractFactory { abstract Color getColor(String color); abstract Shape getShape(String shape) ; }
  • Step 6
  • public class ShapeFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); }else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); }else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } @Override Color getColor(String color) { return null; } }

  • public class ColorFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ return null; } @Override Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("RED")){ return new Red(); }else if(color.equalsIgnoreCase("GREEN")){ return new Green(); }else if(color.equalsIgnoreCase("BLUE")){ return new Blue(); } return null; } }
  • Step 7
  • public class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("SHAPE")){ return new ShapeFactory(); }else if(choice.equalsIgnoreCase("COLOR")){ return new ColorFactory(); } return null; } }
  • Step 8
  • public class AbstractFactoryPatternDemo { public static void main(String[] args) { //get shape factory AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE"); //get an object of Shape Circle Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Shape Circle shape1.draw(); //get an object of Shape Rectangle Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Shape Rectangle shape2.draw(); //get an object of Shape Square Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of Shape Square shape3.draw(); //get color factory AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR"); //get an object of Color Red Color color1 = colorFactory.getColor("RED"); //call fill method of Red color1.fill(); //get an object of Color Green Color color2 = colorFactory.getColor("Green"); //call fill method of Green color2.fill(); //get an object of Color Blue Color color3 = colorFactory.getColor("BLUE"); //call fill method of Color Blue color3.fill(); } }
  • Step 2



  • The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.
  • Design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
  • The Factory Method design pattern solves problems like
    • How can an object be created so that subclasses can redefine which class to instantiate?
  • Creating an object directly within the class that requires (uses) the object is inflexible because it commits the class to a particular object and makes it impossible to change the instantiation independently from (without having to change) the class.
  • Factory Method design pattern will,
    • Define a separate operation (factory method) for creating an object.
    • Create an object by calling a factory method.
  • In this way subcalss can redefine which class to initiate

  • Step 1
    • Create an interface.
    • public interface Shape { void draw(); }
  • Step 2
    • Create concrete classes implementing the same interface.
    • Rectangle.java
    • public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
    • Square.java
    • public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
    • public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
        
  • Step 3
    • Create a Factory to generate object of concrete class based on given information
    • ShapeFactory.java
    • public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
  • Step 4
    • Use the Factory to get object of concrete class by passing an information such as type.
    • FactoryPatternDemo.java
    • public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of square shape3.draw(); } }


    • The Builder is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. 
    • The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
    • The Builder design pattern solves problems like
      • Create different representations of a complex object
      • Creating a complex object be simplified
    sasasasasasasa
    /** * Represents the product created by the builder. */ class Car { private int wheels; private String color; public Car() { } public String getColor() { return color; } public void setColor(final String color) { this.color = color; } public int getWheels() { return wheels; } public void setWheels(final int wheels) { this.wheels = wheels; } @Override public String toString() { return "Car [wheels = " + wheels + ", color = " + color + "]"; } } /** * The builder abstraction. */ interface CarBuilder { Car build(); CarBuilder setColor(final String color); CarBuilder setWheels(final int wheels); } class CarBuilderImpl implements CarBuilder { private Car car; public CarBuilderImpl() { car = new Car(); } @Override public Car build() { return car; } @Override public CarBuilder setColor(final String color) { car.setColor(color); return this; } @Override public CarBuilder setWheels(final int wheels) { car.setWheels(wheels); return this; } } public class CarBuildDirector { private CarBuilder builder; public CarBuildDirector(final CarBuilder builder) { this.builder = builder; } public Car construct() { return builder.setWheels(4) .setColor("Red") .build(); } public static void main(final String[] arguments) { final CarBuilder builder = new CarBuilderImpl(); final CarBuildDirector carBuildDirector = new CarBuildDirector(builder); System.out.println(carBuildDirector.construct()); } }
    • Steps:
      • Create car builder interface
      • Car builder implementation
        • Create car object in constructor and use this object for all car object manipulation like buildCar, setCarColour ,setCarWheel etc
      • Create CarBuildDirector class with
        • initiate car builder object
        • create car using car builder methods like below
          • car builder.buildcar.setWheels(2).setColor("Red")
    • Advantages
      • Allows you to vary a product’s internal representation.
      • Encapsulates code for construction and representation.
      • Provides control over steps of construction process.
    • Disadvantages
      • Requires creating a separate ConcreteBuilder for each different type of product.
      • Requires the builder classes to be mutable.
      • Data members of class aren't guaranteed to be initialized.
      • Dependency injection may be less supported.



    Search This Blog

    Contact us

    Name

    Email *

    Message *