Friday 8 July 2022

Advantage of Singleton Pattern over Static Class in Java

 

Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritanceand Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, it’s not possible to return different implementation for different JVM.


That’s all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.

Monday 26 August 2019

lambda expressions are not supported in -source 1.5 eclipse

Use below in your pom.xml

  <properties>
      <java.version>1.8</java.version>
      <maven.compiler.target>1.8</maven.compiler.target>
      <maven.compiler.source>1.8</maven.compiler.source>

  </properties>



or


<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
<build>

Monday 27 May 2019

/proc/cpuifo and /proc/meminfo

physical id     : 1 --> i.e. physical cpu number
siblings        : 8 --> total cores near
core id         : 7 --> my core id
cpu cores       : 8 --> total cores in this CPU



 cat /proc/meminfo
MemTotal:       16264672 kB
MemFree:        15244520 kB
MemAvailable:   15423132 kB

16 GB

free -g
[test@sandeep-20ne ~]$ free -g
              total        used        free      shared  buff/cache   available
Mem:             15           0          14           0           0          14
15 GB

 

Tuesday 21 May 2019

Thread dump analysis


Healthy thread:

WAITING for request


java.lang.Thread.State: RUNNABLE

runnable


BAD threads

:

java.lang.Thread.State: BLOCKED (on object monitor) : waiting for monitor entry



Oks

java.lang.Thread.State: TIMED_WAITING (parking) :waiting on condition


java.lang.Thread.State: TIMED_WAITING (on object monitor) :Object.wait()


java.lang.Thread.State: TIMED_WAITING (sleeping) :waiting on condition



Thread dump analysis :
1.  Search for BAD threads , Blocked states etc
2. determine the pattern
   like if all of them are waiting for some object<Object_ID> will be printed in stack trace, search with that key.

3. If many threads are waiting for one one specific object,
    do a seach "locked <<Object_Id>>

   you will find, which thread is holding that objects lock.

4. Analyse the stack trace (always bottom up) of that culprit thread.
5. See what is the last step that culprit thread execute (top line of thread)

 If last steps, where this thread was blocked, relates to some JVM related things, like parsing XML, loading some class, logging or reading some file.
Its typically relates to excessive use of Heap, heap running out of memory.

Like some threads "Stuck/Bloacked" in "init" space, that means, they are not able to get the memory they wants, hence the operation is stuck..

CONCLUSION

In such cases, now you need to analyse you heap dump, to see if there are enough space, memory leak etc.


Source
 Java Thread ID ex: tid=0x000000011e52a800 ** This is the Java Thread Id obtained via java.lang.Thread.getId() and usually implemented as an auto-incrementing long 1..n*



 

Wednesday 17 April 2019

Classpath | JAVA HOME | Classnotfound | main class not found


In window CMD,

1. When we type any commands, lets say "javac", How CMD will know, where exactly is this tool is located, you may type this in any directory, if you type this command, being inside the directiry where it resides, then it will work, else CMD will not know, where to look for.

Ans:

If you want "sandeep" to be recognized as cmd command by window, then you need to tell where to look for sandeep to window

Windows --> Set environment path --> add variable ,




Now I added "C:\..\jdk\bin\,  exact located path , till "bin", now i can type any tool under, which is under that bin folder, window will recognize it as tool, because, that folder in in the path to look for list of window, Sp the "javac" command will work anywhere in the cmd,



Compile time error:

No class found , No main found


How javac <file.java> performs search

How java <classname> performs search

I have "Test.java" and "Test.class", whose package is -->
package kafka.test.com.kafka_test;

Under this folder(its a maven project)

C:\Users\s.jaisawal\workspace\kafka-test\src\main\java\kafka\test\com\kafka_test

But when I go inside this directory via cmd, and run

C:\Users\s.jaisawal\workspace\kafka-test\src\main\java\kafka\test\com\kafka_test>java Test
Error: Could not find or load main class Test


C:\Users\s.jaisawal\workspace\kafka-test\src\main\java\kafka\test\com\kafka_test>
java kafka.test.com.kafka_test.Test
Error: Could not find or load main class kafka.test.com.kafka_test.Test

So I went back to a directory where package starts ,
C:\Users\s.jaisawal\workspace\kafka-test\src\main\java> java Test
Error: Could not find or load main class Test

Finally , from the start of package directory, I gave fully qualified name of my class

C:\Users\s.jaisawal\workspace\kafka-test\src\main\java>java kafka.test.com.kafka_test.Test
Main is running.....


So how does java seaches the classes while loading or executing ?


How a jar is run, how main in jar is found, why -classpath is used while running  a jar ?


Problem with maven eclipse project


Normal java eclipse project, you can right click on java file and "run as application", eclipse compiles and looks for main and runs, but in maven project,

You have to clean and install the pom.xml and then you can run any java (with main), each modification requires a clean build.


======================Problem with Eclipse ====================================

Issue: Project --> Build , doesn't build anything it show no output, 

Cause: 
Make sure that you create a Java project and that your Java files are in
a source folder of that project.



=============Compile your single java file =======================================

1. In linux/window, find a folder where all jar files are present, typeically ../lib/ and include those lib folders in your class path 


javac -cp /home//lib/*: <java_File_name>.java

Similarly, you can include all different libs type directory with : separated in -cp



 

Error: Could not find or load main class


Tuesday 16 April 2019

Create a maven project | eclipse | kafka


In eclipse --> new --> project --> Maven --> Maven project

provide some default groupid and artifact name , ex:

<groupId>kafka.test.com</groupId>

<artifactId>kafka-test</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>



finish --> edit po.xml --> add your dependencies, save, it should download all dependencies in to

packages --> maven dependencies

now you can use all the java classes in to your project

Sunday 23 December 2018

Shallow Vs Deep copy

Simple words:

Default implementation of Object.clone() (btw you have to be clonable), provides a shallow copy,
i.e. the only primitive data type's of object will be copied but if object contains, some reference to another object, then the newly copied object will just copy the reference value of that Object.


Like

Class Employee {

int name;// this will be copied to a newly created object and set the value
int id; // this will be copied

IDepartment depart; // the newly created object will just copy the reference of the department object

//So of old object, which we are cloning/copying, changes the department object's values, the shallow copied object will also change, hence this is not 100% a freash independent copy.

}

Deep copy:
The only difference is, you are not allowed to write all the complex logic, of implementing/overriding the clone() method behaviour

Class Employee {


public Object clone() {

e = new employee();

Idepartment dep = new Department()

dep.name = this.department.getName()

more complex and nightmare code, of department also contains some other reference object and so on.


}


so this is deep copy but implementation is complex, to make it easy, we need to follow serialization, forcing all the participant to implement serialization, like Employee, Department,and its objects.

then just serialize and de-serialize the object and you will have two independent object with exactly same values.

again, of one of participant object doesn't implement serialize, its value will not be saved and result as null.(Confirm again)




 

Transient variable

Object's attributes marked as "transient" will not be "serialized" during serialization, and during de-serialized its value will be "null/default"

use for fields, like password, or which you don't want to store or send across.

S.O.L.I.D | SOLID Design principle



S: Single Responsibility Principle

Idea : Do not touch the code due to changes in unrelated things, keep everyone's responsibility separate

In DATABASE Example 
- Wrong design - If DB Reader starts performing some transformation, Later of changes in tranformation logic, we have to touch Reader code, which is risky as changes something which is not related to new requirement.
 
Correct design :
These leads to each class having own specific task and functions, like Separate class for Reader [read() function] and Transformer  [performTransform()]




Everyone does its won task with taking other task , independently and secretly(i.e. Encapsulated way).
This principle leads to concept of Containerization of modules as PODs in K8




Example :

A DB Manager may have DBSession Object and DB interactor object.
DBSession just creates a session by loading the conf, 
A DB Interactor just takes session object and perform read and write.

Benefits :
1. Maintainability 
2. Easy to extend the functionality
3. Loosely coupled interaction, Change in one functionality requires minimum/no changes in others code 



O: Open for extension and Closed for Modification

You must design your inheritance structure, Interfaces and classes in such a way that, when you want to add a new functionality.
 You should be able to do it without touching an existing implementation.

Open for extension : 
Must provide an behavior which can be extended

Closed for modification:
The new extended logic, must not impact the existing code and you should not be required to change the existing parent code, in order to accommodate new extension.





Liskovs Substitute principle:

The new extension must be replaceable/passable in any function, which takes a Base type reference

Ex:

public testBordCapabilities(IBird bird) {

bird.speek();
bird.fly();
}

//but lets says you create a wooden bird, and pass that object, then your wooden bird can also fly,
which is bad, for that now either you have to makes changes in this testFly() to handle instanceOf check(violation of OCP), or in your woodenBird's fly() method, you have  to either do nothing and throw exception, that is also bad.


Solution during the design:
IBird{

speek(); // or any other functionality, which you things all Bird should have
}

IFyableBird implements IBird{

fly()
}

So in this case any existing method (testBirdCapabilities(IBird), which takes reference of IBird, will be able to call only speek() method not fly();
and you can pass your Iflyable object to that method as well, i.e. effectively your object is substitutable to your parent.

and other method, who wants to make use of  your flying capabilities, work on your IFlyable reference not on IBird reference

public testFly(IFlyable  flyingBird){

flyingBird.fly();
}


Breaking Liskov :

- Throw a new Exception from implemented(Super Class/Interface defined) method from your subclass.
i.e. your subclass is not completely replaceable .

What you do ?
-Create one more Sub Interface, which throws those exception

I: Interface Segregation Principle

Effectively same/taken care, if you had followed Single responsibility and Liskovs Substitute priciple which protect your "Close for modification" property.

But read in a another way.

Read the same IBird, example as above.
If you provide fly() method in IBird, forcing all non flying bird to implement fly() method, by providing some empty implementation or throwing exception, that dont call fly() on non flying Birds.

Then, if your actual flying bird, lets PigeonBird, wants to change the signature of fly(), then it will require change in IBird --> fly() method, this is not OK, but real problem as per "Interface Segregation principle" is, once you change the signature of fly() in Ibird, this will force a change in other non flying birds class  signature, say in Penguin, which is already complaining by throwing exception in its unnecessary implementation fly().

Hence  "Clients should not be forced to depend upon interfaces that they do not use  "

Here the Client is, Non flying birds like "PenguinBird" and it's force to depend on "fly()" method/interface which it doesn't need".


Solution:

Just like solution for Liskov's, segregate in to single responsibility interfaces.

IBird{

speek(); // or any other functionality, which you things all Bird should have
}

IFyableBird implements IBird{

fly()
}



So, if there is change in IFlyable class's fly() method, other NonFlyableBird which implements IBirds, doesn't need to go through any change.


D: Dependency Inversion Principle 

Basically says about, how a High level class , which contains of talks to a low Level class, should not directly depend upon it, rather talk to it via abstraction/interface, so that if new types of low level class can be introduced without any single change in high level class.



Bad design:

Here manager, is highly/directly dependent on low level "Worker" class, if new worker type is added, the mamager also need lots of changes, assume the manager class is too complex with lots of reference of worker instance, you need to change lots of place, may break many functionality, test it again etc etc



// Dependency Inversion Principle - Bad example

class Worker {

 public void work() {

  // ....working

 }

}



class Manager {

 Worker worker;



 public void setWorker(Worker w) {
  worker = w;
 }

 public void manage() {
  worker.work();
 }
}

class SuperWorker {
 public void work() {
  //.... working much more
 }
}



// Dependency Inversion Principle - Good example
interface IWorker {
 public void work();
}

class Worker implements IWorker{
 public void work() {
  // ....working
 }
}

class SuperWorker  implements IWorker{
 public void work() {
  //.... working much more
 }
}

class Manager {
 IWorker worker;

 public void setWorker(IWorker w) {
  worker = w;
 }

 public void manage() {
  worker.work();
 }
}









OOPS basics



Abstraction:

remember it from example of Hypervisor, the way Hypervisor Abstract the underlying resource on same SERVER, and provide basic interface for VM creation , VM feels as if it owns the server.



Abstraction in Java is provided with "Interface".

Example:

ICar < -- MarutiCar
ICar <-- HondaCar

The client will be provide with reference to only Car interface, even though actual object ca be of any type.

Client can invoke, only those operation, which are defined in interface.

Hence abtracting the underlying different implementation of different car types.

at run time only it will be called .
Hence abstracting the underlying complexity of actual implementation

Encapsulation


Can be seen as a strategy used in order to provide abstraction.
Hide private variable, protect them from getting visible to subclasses.
and visible to the clients, when they hold the object reference, they shouldn't be able to access your internal private attributes and change it.

Its a way to implement "Single Responsibility" principle from SOLID design principle
i.e. you complete one task by your self without leaking your data hence allowing your responsibilities to be managed/alters by someone else

How Encapsulation helps

Implementation 


 Can you access non static variable in static context ?

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. 






Saturday 22 December 2018

Saving Singleton

Protect from reflection


Declare the instance

private constructor set be set public by reflection


 Constructor constructor = ReflectionSingleton.class.getDeclaredConstructor();
// Below code will change constructor access level from private to public

  constructor.setAccessible(true);

// Creating second instance
 ReflectionSingleton instanceTwo = (ReflectionSingleton) constructor.newInstance();


private fields can be accessed by reflection

If you try to protect constructor, by throwing exception like below

     private ReflectionSingleton() {
        if (instance != null) {
            throw new IllegalStateException("instance already created.");
        }
        System.out.println("Singleton instance is being created.");

    }

Private static field's value can also be changed by reflection , like below


Field instance = ReflectionSingleton.class.getDeclaredField("instance");
instance.setAccessible(true); instance.set(instance, null); So apart from above constructor, make the field final, so that its value can not be changed even via reflection private static final ReflectionSingleton instance = new ReflectionSingleton();


Protect from deserialization

The singleton class need to implement(Not override) readResolve()

 protected Object readResolve()
    {
        return instance;
    }

The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered


Question:
If Object is loaded in a new JVM instance, where static singleton instance field is never initialised, how can it return the "instance" from readResolve().
even when Singlen is loaded and the static field will have the default value null, in lazy initialization strategy, of is eager strategy is used, this can work.

ANSWER:
readResolve() will work, if you try to serialize your already instantiated ("instance") singleton, in same JVM, and in same JVM you try to deserialised, it will return static reference of "instance" variable.

But if in different JVM ?

It seems, during deserialization, the object's would anyway have "instance" variable, which was serialsed and stored in file, same "instance" variable reference will be return.
For now its ok, explore more.



3. CLONING protection

Just throw exception from your singleton class


@Override
  protected Object clone() throws CloneNotSupportedException 
  {
    throw new CloneNotSupportedException();
  }





Sources : 

/DesignPatterns


https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-serialization-cloning/