Tag Archives: JVM

Java : Program Execution


Java is a high level programming language. To run a java program (.java file) first need to compile by javac compiler that convert java code to byte code (.class file). Machine language for JVM is byte code that is same for all type JVM machines (i.e OS). After running java command, JVM executes the byte code gennerated by compiler and produce output.

For Example : Byte code generated on windows machine can be run on Mac or Linux OS and vice versa.

Java program exceution

JVM makes java portable (write once, run anywhere) and platform independent. Because each operating system has different JVM, however the machine language is byte code output they produce after execution of byte code is same across all operating systems.

See Also: JDK, JRE, JIT,SDK, JVM Introduction

 

Advertisements

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

 

[Solved] CloneNotSupportedException


java.lang.CloneNotSupportedException throws when object’s class does not implement the cloneable interface and  clone method in class Object has been called to clone an object.
Some applications that override the clone method can also throw this exception to indicate that an object could not or should not be cloned.

Cloneable is marker interface which is not having any method to implement. When implement marker interface in class it indicate to JVM how to treat with this objects.
For more info about marker interface , it’s type and how to create check below link.

Marker Interface in Java, Use and Custom Marker Interface

clone() is protected method of object class which is super class of all the classes. if need to use clone() method have to override it .

Constructors :

  • CloneNotSupportedException()

Create a CloneNotSupportedException object with no detail message.

  • CloneNotSupportedException(String message)

Create a CloneNotSupportedException object with  exception detail message.

Example

In below example creating clone object of Employee class from object there is no any compile time error because we have override clone method of Object Class in Employee class but it will throw CloneNotSupportedException while execution because as per

Contract : if cloneable interface is implemented then only clone method will call otherwise  JVM will throw CloneNotSupportedException.

Here we are doing Shallow cloning of object. For more info on shallow and deep cloning follow below link.

Employee Class

public class Employee {
private String firstName;
private String lastName;
private int age;
private double salary;
private Address address;

public Employee(String firstName, String lastName, int age, double salary, Address address) {
	super();
	this.firstName = firstName;
	this.lastName = lastName;
	this.age = age;
	this.salary = salary;
	this.address = address;
}
public String getFirstName() {
	return firstName;
}
public void setFirstName(String firstName) {
	this.firstName = firstName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public double getSalary() {
	return salary;
}
public void setSalary(double salary) {
	this.salary = salary;
}
public Address getAddress() {
	return address;
}
public void setAddress(Address address) {
	this.address = address;
}

@Override
public String toString() {
	return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", salary=" + salary
			+ ", address=" + address + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
	return super.clone();
}

}


Address Class


public class Address {
	private String addressLine1;
	private String city;
	private String state;
	private String contry;
	private String pincode;

	public Address(String addressLine1, String city, String state, String contry, String pincode) {
		super();
		this.addressLine1 = addressLine1;
		this.city = city;
		this.state = state;
		this.contry = contry;
		this.pincode = pincode;
	}

	public String getAddressLine1() {
		return addressLine1;
	}

	public void setAddressLine1(String addressLine1) {
		this.addressLine1 = addressLine1;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getContry() {
		return contry;
	}

	public void setContry(String contry) {
		this.contry = contry;
	}

	public String getPincode() {
		return pincode;
	}

	public void setPincode(String pincode) {
		this.pincode = pincode;
	}

	@Override
	public String toString() {
		return "Address [addressLine1=" + addressLine1 + ", city=" + city + ", state=" + state + ", contry=" + contry
				+ ", pincode=" + pincode + "]";
	}

}


Test for ClassNotSupportedException


public class CloneExample {

	public static void main(String[] args) {
		Address address = new Address("Next to Metro Station", "Noida", "UP", "India", "201301");
		Employee employee = new Employee("Saurabh", "Gupta", 30, 50000, address);
		System.out.println("Employee Object Before Clone :");
		System.out.println(employee);
		try {
                        System.out.println("Employee Object After Clone :");
			Employee employeeCopy = (Employee) employee.clone();

			System.out.println(employeeCopy);
		} catch (CloneNotSupportedException ex) {
			ex.printStackTrace();
		}

	}

}


Output

Employee Object Before Clone :
Employee [firstName=Saurabh, lastName=Gupta, age=30, salary=50000.0, address=Add
ress [addressLine1=Next to Metro Station, city=Noida, state=UP, contry=India, pi
ncode=201301]]
Employee Object After Clone :
java.lang.CloneNotSupportedException: Employee
	at java.lang.Object.clone(Native Method)
	at Employee.clone(Employee.java:55)
	at CloneExample.main(CloneExample.java:11)

Solutions :

To solve this CloneNotSupportedException we have to implement cloneable interface in Employee class as below and run this program again.

public class Employee implements Cloneable<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>{

}

Summary :

  • Explain about CloneNotSupportedException by example and how it happen.
  • Constructors of CloneNotSupportedException.
  • How to fix CloneNotSupportedException.
  • Cloneable Marker Interface.

References :

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

Marker Interface in Java and Use


Marker interface is main frequently asked question to JAVA interview. Generally interviewer asked this question to check internal know knowledge of JAVA developer some times ask on architect level also because it’s follow the Marker Interface Design pattern. Here I have covered everything to crack questions related to Marker Interface.

What is a Marker Interface?

Marker Interfaces are empty interface it does not contains any properties and behaviors to implement. It’s also called as marker or the tag interface.

Why Marker Interface and Who Implement it?

Custom Marker Interface Example
Custom Marker Interface

Marker interface functionality is predefined implicitly in JVM. When a class implement a marker interface then class is not expected to implement anything to adhere to the contract defined by the interface. In contrast it is a tag to indicate the JVM regarding an expected functionality to perform implicitly.

For Example :

java.io.Serializable : If class implements the Serializable interface then JVM perform some special operation on it and writes the state of the object into object stream then this object stream will available to read by another JVM.

java.lang.Cloneable: Same way if class is implementing Cloneable interface then it perform some special operation to clone object by copy all fields

What are available Marker Interfaces in JAVA?

Mainly used built-in marker interfaces are as below :

  • java.lang.Cloneable
  • java.io.Serializable
  • java.rmi.Remote
  • java.util.EventListener (its officially know as ‘tagging interface’)

There are some more marker interface present in Java.

  • java.util.concurrent.CompletableFuture.AsynchronousCompletionTask
  • java.sql.ParameterMetaData
  • javax.xml.stream.events.EndDocument
  • javax.management.loading.PrivateClassLoader
  • java.security.KeyStore.Entry
  • java.security.KeyStore.LoadStoreParameter
  • java.security.KeyStore.ProtectionParameter
  • java.security.Policy.Parameters
  • javax.security.auth.callback.Callback
  • javax.security.auth.login.Configuration.Parameter

Can we create custom marker interfaces ?

Yes

How to Create Custom marker Interfaces?

Custom Marker Interface is nothing to do specially with JVM end . It’s to mentioned in class methods to treat this object specially so that perform some special operations.

Steps to create marker interface :

  • Create an interface with no properties and method on it.
  • Implements this interface on class.
  • Perform any operation in method if object instance of type marker interface.

See below example for more detail

Create Empty  Interface

public interface MyMarker {
//no properties and method
}

Write a class to implement interface

public class MyClass implements MyMarker{
//define properties and method
}

Class to check Marker Interface to perform special operation

public class TestMarker {

	public static void main(String[] args) {
		MyClass myClass=new MyClass();

		if(myClass instanceof MyMarker)
		{
			System.out.println("I am special treat me VIP");
		}

	}

}

Output :

I am special treat me VIP

Summary

  • Explained about Marker Interface and how JVM handle Marker Interface.
  • Available Marker Interface in Java with some example.
  • Creation of Custom Marker Interface and use.

 

[Solved] Exception UnsupportedOperationException Example


java.lang.UnsupportedOperationException is RuntimeException and Unchecked Exception which expected to thrown by JVM(Java Virtual Machine) when try to perform an “optional operation” which is not allowed an object .

The Java framework contains plenty of these, especially in the Collections framework. For example “add” is an optional operation, because immutable collections should not allow it. Throwing UnsupportedOperationException is exactly what you should do if you don’t want to write one of these methods.

Constructors :

  • UnsupportedOprationException() : Constructs an UnsupportedOperationException with no detail message.
  • UnsupportedOprationException(String message) : Constructs an UnsupportedOperationException with specified detail message.
  • UnsupportedOprationException(String message, Throwable cause) : Constructs an UnsupportedOperationException with specified detail message and cause.
  • UnsupportedOprationException(Throwable cause) : Constructs a new exception with the  specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Example :

In below example problem is List returned from Arrays.AsList() is not like java.util.ArrayList. Arrays.asList() returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException Exception.

package exceptionhandeling;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		/**
		 * By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList.
		 * When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

		 * Not every List implementation support add method because Arrays.asList() returned
		 * immutable list of fixed size
		 */
		for(String emp:empList)
		{
			empList.add("Sachin");
			System.out.println(emp);
		}

	}

}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at example.UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:21)