Tag Archives: garbage collection

JDK, JRE, JIT,SDK, JVM Introduction


JDK (Java  Development Kit)

JDK (Java Development Kit) is a superset of JRE (Java Runtime Environment), it contains everything that JRE has along with development tools such as compiler, debugger, etc.

JDK Java development Kit
Java Development Kit

See Also: Java: Program Execution

JRE (Java Runtime Environment)

JRE (Java Runtime Environment) provides the environment in which the JVM (Java Virtual Machine) runs. JRE contains JVM, class libraries, and other files excluding development tools such as compiler and debugger.

It means, you can run the code in JRE but you can’t develop and compile the code in JRE.

JDK and JRE Formulae

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) runs the program by using class, libraries, and files provided by JRE. JVM able to run a program written in Java and other languages also that are compiled to Java byte code. For Example Jython, Jruby, Closure, Apache, Groovy, Kotlin, etc.

JVM Architecture

Now discussed terminology used for JVM.

Class Loader

The class loader reads the .class file and saves the byte code in the method area.

Method Area

Method area holds class level information of .class file. JVM jave only one method area which is shared among all the classes.

Heap

Heap is a JVM memory part where objects are allocated. JVM creates an object for each .class Class file.

Stack

The stack is  JVM memory part but unlike Heap, it is used for storing temporary variables i.e method parameters.

PC Registers

PC Registers use to keeps the track of which instruction has been executed and which one is going to be executed. Because instructions are executed by threads, each thread has a separate PC register.

JIT Compiler

The JIT also called a Just-In-Time compiler. It used when a method is called. The JIT compiles the bytecode of that called method into native machine code. When a method has been compiled in native machine code, the JVM calls the compiled code of that method directly instead of interpreting it.

Native Method Stack

A native method used to access the runtime data areas of the virtual machine.

Native Method interface

It enables java code to call or be called by native applications wiritten in C or C++. Native applications are programs in low-level language that is specific to the hardware and OS of a system.

Garbage collection

Garbage Collection use for automatic memory management by JVM. It destroys unreferenced objects from Heap so that allocates more memory for new objects.

JDK Architecture & API’s Details

In this figure, you will get an idea of how these libraries and API’s are distributed on different levels.

JDK APIs Architecture

Difference between API and Methods

API (Application Programming Interface) interfaces that the rest of the world sees and can use. A Method can be part of the public interface or not. But an API executes a set of methods.

In java, APIs provide through the interface which is really a set of public methods. An API has contract like tells about method signatures and return type.

For Example List API’s provide different method signature and expected result as return type so that you can use according to your convenience.

Difference between JDK and SDK

JDK(Java Development Kit) is an extended subset of a SDK (Software Development Kit).

  • JDK includes tools for developing, debugging and monitoring of Java Program. It mainly responsible for the writing and running of Java programs.
  • SDK is composed of extra software related to a Web application or mobile application etc. such as Application Server, Documentation, Debuggers, Code Samples, Tutorials, GlassFish server, MySQL and IDE Netbeans.

Now, Oracle strongly suggests using the term JDK to refer to the Java SE Development Kit. The Java EE SDK is now available with or without the JDK, by which they specifically mean the Java SE 7 JDK.

See Also: Java Versions History

 

Java : java.lang.Object Class & Methods


java.lang.Object  is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class.

Methods of Object Class

Below are methods of Object Class for different purpose  as below:

  1. protected Object clone() : Creates and return copy of this object.
  2. boolean equals(Object obj) : Indicate weather other object is equal or not.
  3. protected void finalize() : To make object finalize for garbage collection.
  4. Class getClass() : Returns the runtime class of this Object.
  5. int hashCode() : Returns a hash code value of Object.
  6. void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  7. void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  8. String toString() : Returns string representation of object.
  9. void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  10. void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  11. void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

In this below examples you can see how to override and utilize these methods in different ways.

Example of clone() method

Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface. There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

Java : Shallow and Deep Object Cloning

Eample of finalize() method

Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

Java : Garbage Collection finalize() method example and uses

Example of hashCode(), equals() and toString() method

Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract

For example of toString(), hashcode() and equals() follow below link:

Java : How to remove duplicate objects from list?

Example of getClass() method

The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

import java.util.Calendar;

public class GetClassExample {

	public static void main(String[] args) {
		GetClassExample test=new GetClassExample();

		System.out.println("Class Name :"+test.getClass().getName());

		Calendar calendar=Calendar.getInstance();
		System.out.println("Calendar Class Name :"+calendar.getClass().getName());

		Integer integer=new Integer(10);
		System.out.println("Integer Class Name :"+integer.getClass().getName());

	}
}

Output


Class Name :com.Object.GetClassExample
Calendar Class Name :java.util.GregorianCalendar
Integer Class Name :java.lang.Integer

Example of wait(), notify() and notifyAll() method

Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

public class Order {
    private String msg;
    public Order(String msg){
        this.msg=msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String str) {
        this.msg=str;
    }
}

Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

public class Waiter implements Runnable{
    private Order msg;
    public Waiter(Order msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis());
            //process the order now
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

public class Notification implements Runnable {
    private Order msg;
    public Notification(Order msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg(name+" Notification work done");
                msg.notify();
                //use notify all when lots of thread are running
                // msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below test class having multiple threads of Waiter and notification to execute order.

public class WaitNotifyExample {
	public static void main(String[] args) {
		Order order= new Order("My Order");
	        Waiter waiter1 = new Waiter(order);
	        new Thread(waiter1,"waiter 1").start();

	        Waiter waiter2 = new Waiter(order);
	        new Thread(waiter2, "waiter 2").start();

	        Notification notification = new Notification(msg);
	        new Thread(notification, "notification").start();
	        System.out.println("All the threads are started");
	}
}

When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

Output


waiter 2 waiting to get notification at time:1552127934935
waiter 1 waiting to get notification at time:1552127934935
notification started
All the threads are started
waiter 2 waiter thread got notification at time:1552127935946
waiter 2 processed: notification Notification work done

or


waiter 1 waiting to get notification at time:1552127972873
All the threads are started
notification started
waiter 2 waiting to get notification at time:1552127972873
waiter 1 waiter thread got notification at time:1552127973876
waiter 1 processed: notification Notification work done

Conclusion

Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html