JDBC Database Connection in hibernate

As an experiment in how Hibernate uses a database connection, remove or rename the file hibernate
.properties, or remove the database elements in hibernate.cfg.xml (if you’re using it), in either the stand-alone
or servlet application written in the previous chapter. When you’ve changed the file, execute the
application and attempt an action that accesses the database, such as showing all the CDs. Since our
error handling displays the stack trace, you should get a fairly large trace dump on the console window
where you launched the application. If you’re using the servlet example, you might need to open a log
file to see the errors.
At the top of the stack trace, you should see a message like “user needs to supply connection”. This error
tells you that Hibernate was unable to obtain a connection to any database for more than just a wrong
password. But, in fact, no hibernate.properties file or database elements are available to the application;
as such, the application doesn’t know how to connect to a database. This is obviously bad, because
Hibernate accomplishes most of its work through a database.
The point is, the developers of Hibernate developed the system in a manner that lets you handle a vari-ety
of design situations. In this case, Hibernate can either create its own connection to the underlying
database or use a connection that’s already in place. The examples in Chapter 3 show you how to use
Hibernate connections. If you’re developing an application from scratch, you’ll probably let Hibernate
handle the connection; there aren’t any glaring issues with this type of situation, and there are no perfor-mance
problems. So, why does Hibernate allow user-based connections? Primarily to handle legacy
issues.
Given the constant evolution of software systems, you won’t always be able to rewrite your code. In
some cases, you must refactor live systems. The application has already been written, and database con-nections
are established and available, so why not use them? You need to consider a couple of issues.
The first is connection pooling, which we discuss in detail later in this chapter. If you’re using a previ-ously
established connection, you’ll bypass any connection pooling defined in Hibernate. Second is the
issue of transactions. When you’re using a user-based connection, you can use Hibernate’s transaction
system (discussed in Chapter 10), or the application can handle transactions through the underlying
database using JDBC transactions or through JTA.
Here’s an example of the code for using a previously established connection:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost/accounts");
SessionFactory sessionFactory = Configuration.buildSessionFactory();
Session session = sessionFactory.openSession(connection);
} catch (Exception e) {}

Why we call start() method which in turns calls run method in java, why not we directly call run method ?

In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved.

You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.

Java serailization , transient , static concept in core java | core java interview questions

In core java interview questions, Serialization is one of the important topic in which we come across various questions like
What is Transient, Explain Serailization, What is serialversionUID, What is use of serialVersionUID, what is Serilization. (interface, class).
I have gone through various technical interview question websites and found that all answers are very short and dosent give idea of interrelated questions.

This tutorial will help beginners to understand everything related to serialization in one go.

Will first start with basic key points.
All objects in memory are exist only as long as java virtual machine running.
Serialization is process of writing objects to a stream and read from stream. Writing to a stream will make your object persistable. We can save object state on physical file system. and read it later whenever required and restore object state.
Using serialization we can maintain object state beyond java virtual machine lifetime.

Java provides mechnisam to persist the object.
Key points to use this mechanisam is. Your object should be serializable.
How can we make our object serializable? by implementing java.io.Serializble.
What about java library, system classes. Are all of them are serializable? No.
Most of the classes which makes sense to serialize are by default implementing Serializable. But some classes dosent make sense are not.
for E.g : String, Swing, AWT, Class implements Serializable.
Thread, ClassLoader, Socket, OutputStream ..dosent implement Serializable.

Key point to remember is why we need to implement Serializable explicitely? Because java.lang.Object dosent implement serializable. This facility is given to implementer.
What happens if your class is using one of the system class which is not serilizable..for e.g Thread, OutputStream?
Java provides transient keyword. (As mentioned earlier ..Making Thread serializable dosent make sense) so we can mark this member as transient and Serialization process will exclude this member from serialization.

What will be the value of transient variable when we read it back? it will be default value.. for string null.

Now we understood the concept of serialization, and what is use of transient.
Lets do simple example.
Create simple class.

package transientTest;

import java.io.Serializable;

public class TestClass implements Serializable{
 private String fName;
 public String getfName() {
  return fName;
 }
 public void setfName(String fName) {
  this.fName = fName;
 }
 public String getlName() {
  return lName;
 }
 public void setlName(String lName) {
  this.lName = lName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 private String lName;
 private transient String  password;
}
Test the class. Write to file and read from file.
package transientTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerialization {
 public static void main(String... st) throws Exception{
  ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
  TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  obj.close();
  ObjectInputStream objin= new ObjectInputStream(new FileInputStream(new File("Test.out")));
  TestClass ts1=(TestClass)objin.readObject();
  objin.close();
  System.out.println("ts.getfName():"+ts1.getfName());
  System.out.println("ts.getlName():"+ ts1.getlName());
  // returns null: because TestClass.password is transient.
  System.out.println("ts.getPassword():"+ ts1.getPassword());
  TestClass1 ts12= (TestClass1)ts1.getTestcls();
  System.out.println("test12:"+ts12.mname);
 }
}
Looks very simple .. yes!
But we need to look at the few real time scenario.
Suppose you create the object, set the state and write to stream. In same execution you change the state of the object and try to write it again. What will be the behavior... ?
TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  ts.setlName("-----");
  obj.writeObject(ts);
  obj.close();
 In above code, you have changed the lName to ---- and again wrote the same object to stream..
Key point to remember.. ObjectOutputStream maintain a reference to an object written to it. That means if the state of the object is written and then written again. the new state will not be saved.
There are two ways to do it.
use reset().
close the stream and write it once again.
obj.reset();
obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
obj.writeObject(ts);
obj.close();

There are few other points you need to consider is about GC. once object is written to stream. make sure that object is availble for GC.

One more key point to remember ...or consider scenario..
You have a class which is persisted, and when you try to read it ... by that time class is modified (added new member..). What will happen?
By default if your class is changed after write.. you will not be able to read it.. because your class is modified. serialization will throw exception java.io.invalidClassException().
How serialization identifies that class is modified.. ?
Best answer is ..all persistent capable classes (Implements Serializable) are automatically given a unique identifier. if the identifier of the class is \not equal to the identifier of saved object.
How to resolve this issue... ? answer is serialVersionUID.
You assign the serialVersionUID to the class which will remain same before and after modification.

Eg: Create a class using serialVersionUID.
package transientTest.readwritemodify;

import java.io.Serializable;

public class TestClass implements Serializable{
 static final long serialVersionUID= 1l;
 
 private String name;
 private String lname;
 public String getLname() {
  return lname;
 }

 public void setLname(String lname) {
  this.lname = lname;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}
Now.. even if your class is modified but the serialversionUID remains the same.. you will be able to read and write. only additioanl state you have added after modification will be set to null

How can you get serialVersionUID runtime?
use :
ObjectStreamClass.getSerialVersionUID(o.getClass());
serialver is one more utility can be used to get the class version.

What if a super class/interface implements a serializable and you dont want your implementing/extending class to provide this facility.
you can override 2 methods and throw exception.

private void writeObject(ObjectOutputStream out)throws IOException{
  throw new NotSerializableException("");
 }
 
 private void readObject(ObjectInputStream in) throws IOException{
  throw new NotSerializableException("");
 }

Binary Tree, Heap Concept Used in Java collection

A Binary Tree is made of nodes.
Each node contains left pointer and right pointer and a data element.





The root pointer points to the top most node in the tree.
Binary Search Tree (BST) or "Ordered Binary Tree" is a type of binary tree where the nodes are arranged in order for each node.
Elements in left sub tree are less ot equal to the node.
Elements in the right are greater that the node.


Binary tree has two possible branches. left and right.


Heap is complete binary tree. It is tree based datastructure.
There are two types of heap
Max Heap: Element with greatest key (value) is always in the root node.
Min Heap: Element with smallest key (value) is always in the root node.


Java 2 platform provides binary heap implementation with class PriorityQueue java collection framework.


In Java virtual machine heap (heap described above and JVM heap could be different, jvm specification does not provide such details. However the term used is same.) is the runtime data area from which memory for all class instances and array is allocated.
  • Heap is created on virtual machine startup.
  • Heap storage for objects is reclaimed by a automatic storage management system know as GC.
  • Heap is shared among all java virtual machine thread.
  • Heap is split up in to "generations"
  • "Young Generation" stores short lived objects.
  • "Old Generation" objects persist longer are stored in old generation.
  • "Permanent Generation" is used to store class definition and reflection related information and used by virtual machine itself.
  • -Xms (minimum) and -Xmx (Max) parameters are used to specify heap size.
Create Binary tree data structure in java.
package BinaryTree;

public class BinaryTreeExample {
 static class Node
 {
  Node left;
  Node right;
  int value;
  public Node(int value) {
   this.value = value;
  }
 }
 
 public void insert(Node node, int value){
  if (value < node.value) {
            if (node.left != null) {
                insert(node.left, value);
            } else {
                System.out.println("  Inserted " + value + " to left of node " + node.value);
                node.left = new Node(value);
            }
        } else if (value > node.value) {
            if (node.right != null) {
                insert(node.right, value);
            } else {
                System.out.println("  Inserted " + value + " to right of node " + node.value);
                node.right = new Node(value);
            }
        }

 }
 
 public void printInOrder(Node node) {
        if (node != null) {
            printInOrder(node.left);
            System.out.println("  Traversed " + node.value);
            printInOrder(node.right);
        }
    }

}


-----------------------------------

package BinaryTree;

public class Main {
 public static void main(String... str){
  BinaryTreeExample bnary= new BinaryTreeExample();
  BinaryTreeExample.Node node = new BinaryTreeExample.Node(50);
  bnary.insert(node, 6);
  bnary.insert(node, 20);
  bnary.insert(node, 9);
  bnary.insert(node, 9);
  bnary.insert(node, 20);
  bnary.insert(node, 14);
  bnary.insert(node, 15);
  bnary.insert(node, 22);
  bnary.printInOrder(node);
 }
}

Java Classloader concept | java class loader tutorial

Java ClassLoader

  1.     Java classloader is part of java runtime environment that dynamically loads java class in to java virtual machine.
  2.   Usually classes are loaded on demand.
  3. Java provides ClassLoader abstract class to extend class loading function.
  4.   User defined class loader should do basic functions as: Given the name of the class, a class loader attempt to locate or generate data that constitutes a definition for a class.
  5. Every class object contains reference to the classloader.

        TestLoad.class.getClassLoader()

 Class objects for Array classes are not created by class loader, but are created automatically by java runtime.
    ClassLoader uses delegation model to search for classes and resources.
    Method defineClass() converts an array of bytes in to instance of class.

cls = defineClass(className, classBytes, 0, classBytes.length);

    Various class loaders

Bootstrap Class Loader : Loads classes from JAVA_HOME/lib
Extension Class Loader (sun.misc.launcher$ExtClassLoader): Loads classes from extension directory.
System Class Loader (sun.misc.launcher$AppClassLoader): Loads classes from java.class.path.

    Methods to remember:

findClass(String name) : finds specified class
getParent(): Returns parent class loader for delegation.
getSystemClassLoader(): returns system classloader for delegation.
loadClass(): loads class with specified name.
resolveClass().

     User defined classloader needs permission to load system classes.

method to use defineClass(String name, byte[] b, int off, int len, ProtectionDomain domain).

Write custom class loader.
1) Create class which extends ClassLoader.
2) Override protected synchronized method LoadClass().
3) Use findLoadedClass() to identify if class is already loaded.
4) Handle security exception. for the system classes.
5) In case of security exception, call super.loadClass(). delegate to super classloader.
4) Create test class file.
5) Read the file as byte array.
6) Call define class method.

package classLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
 private static final int BUFFER_SIZE = 8192;

 protected synchronized Class loadClass(String className, boolean resolve)
   throws ClassNotFoundException {

  // 1. is this class already loaded?
  Class cls = findLoadedClass(className);
  if (cls != null) {
   System.out.println("Class is already available..");
   return cls;
  }

  // 2. get class file name from class name
  String clsFile = className.replace('.', '/') + ".class";

  // 3. get bytes for class
  byte[] classBytes = null;
  try {
   InputStream in = getResourceAsStream(clsFile);
   byte[] buffer = new byte[BUFFER_SIZE];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int n = -1;
   while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
    out.write(buffer, 0, n);
   }
   classBytes = out.toByteArray();
  } catch (IOException e) {
   System.out.println("ERROR loading class file: " + e);
  }

  if (classBytes == null) {
   throw new ClassNotFoundException("Cannot load class: " + className);
  }

  // 4. turn the byte array into a Class
  try {
  
   cls = defineClass(className, classBytes, 0, classBytes.length);
   if (resolve) {
    resolveClass(cls);
   }
   System.out.println("Loaded using CUSTOM class loader..:"+cls);
  } catch (SecurityException e) {
   cls = super.loadClass(className, resolve);
   System.out.println("Loaded using SYSTEM class loader..:"+cls);
  }

  return cls;
 }
}



package classLoader;

public class TestClassLoader {
 public static void main(String[] args) throws Exception {
        MyClassLoader loader1 = new MyClassLoader();
        Class testLoad = Class.forName("classLoader.TestLoad", true, loader1);
        System.out.println("TestLoad class: " + testLoad);
        if (TestLoad.class.equals(testLoad)) {
            System.out.println("TestLoad loaded through custom loader is the same as that loaded by System loader.");
        }
        else {
            System.out.println("TestLoad loaded through custom loader is NOT same as that loaded by System loader.");
        }
        java.lang.reflect.Method main = testLoad.getMethod("main",
                                                new Class[] {String[].class});
        main.invoke(null, new Object[]{ new String[]{} });
    }
}

Can you synchronize the constructor of object in Java

According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.

How many way we can break Singleton Class in java | Singleton design concept in java

Singleton Pattern ensures a class has only one instance and provides a global point of access to it.

The default constructor of the class is made private, which prevents the direct instantiation of the object by other classes.

A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance(){
  if(instance == null)
      instance = new BookingFactory();
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



In future if you get a requirement for having more than one instance then singleton allows multiple instances without affecting a singleton class's clients. Just you need to do is make a small change in Singleton Class, which doesn't effect the client's code.

Note that the singleton instance is only created when needed. This is called lazy instantiation.


public class SingletonDemo {
 
 public static void main(String args[]) {
   
 // Get a reference to the single instance of Singleton.
 BookingFactory bookingFactory = BookingFactory.getInstance();
 
 // Set the data value.
 bookingFactory.setData(34);
 
 System.out.println("First reference: " + bookingFactory);
 System.out.println("Singleton data value is: " +bookingFactory.getData());
 }
 
}



How can we break Singleton:

1. It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle.

Solution :

In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration.

Make the Instance access method Synchronized to prevent concurrent thread access.



public static synchronized BookingFactory getInstance()




Synchronization is expensive, however, and is really only needed the first time the unique instance is created.

Do an eager instantiation of the instance rather than a lazy instantiation.

You can also instantiate the Singleton as soon as the class loads. i.e You can place it in static block to ensure that it happens only once.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 static {
  instance = new BookingFactory();
 }
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance()
 {
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



Instead of synchronizing the whole method you can also make the instance variable as static final. It is thread-safe because static member variables created when declared are guaranteed to be created the first time they are accessed. You get a thread-safe implementation that automatically employs lazy instantiation.



public class BookingFactory {

   private final static BookingFactory instance = new BookingFactory();

   private BookingFactory() {
         // Exists only to defeat instantiation.
      }
}




But you loose the flexibility of having more than one instance in future without changing client's code.



2. if you are using multiple classloaders, this could defeat the Singleton implementation and result in multiple instances.

Solution:

Because multiple classloaders are commonly used in many situations—including servlet containers—you can wind up with multiple singleton instances no
matter how carefully you've implemented your singleton classes. If you want to make sure the same classloader loads your singletons, you must specify the
classloader yourself; for example:


private static Class getClass(String classname)
                                         throws ClassNotFoundException {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      if(classLoader == null)
         classLoader = Singleton.class.getClassLoader();
      return (classLoader.loadClass(classname));
   }
}



The preceding method tries to associate the classloader with the current thread; if that classloader is null, the method uses the same classloader that loaded a singleton base class. The preceding method can be used instead of Class.forName().



3. If SingletonClass implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

Solution:

To avoid the above you need to implement readResolve() method.


private Object readResolve() {
    return INSTANCE;
}



The previous singleton implementation returns the lone singleton instance from the readResolve() method; therefore, whenever the Singleton class is deserialized, it will return the same singleton instance.


4. We will be able to create a copy of the Object by cloning it using the Object’s clone method.

Solution:

Override the Object clone method to prevent cloning

This can be done as shown below


SingletonDemo clonedObject = (SingletonDemo) obj.clone();



This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.


public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}



When to use:
We can use this while creating objects of thread pools, caches etc to avoid wasting resources.