What is circuit breaking pattern?
https://microservices.io/patterns/reliability/circuit-breaker.html
Rotate sorted array?
https://www.geeksforgeeks.org/find-rotation-count-rotated-sorted-array/
Parallel streams in java 8.
https://examples.javacodegeeks.com/core-java/java-8-parallel-streams-example/
Profiles in Spring Boot?
https://www.baeldung.com/spring-profiles
whats-difference-between-enums-and-final-variables
https://stackoverflow.com/questions/20662018/whats-difference-between-enums-and-final-variables
How Does Spring @Transactional Really Work?
https://dzone.com/articles/how-does-spring-transactional
How to print even and odd numbers using threads in java
https://java2blog.com/print-even-odd-numbers-threads-java/
https://www.baeldung.com/java-even-odd-numbers-with-2-threads
3rd Most repeated work from 1 GB file
this is not the optimized solution though : P
https://javaconceptoftheday.com/find-most-repeated-word-in-text-file-in-java/
Serialize and Deserialize a Binary Tree
https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/
Just in time compiler :
StringBuilder and buffer
how String immutable and what makes
it immutable
String literal vs Object
generics
priority queue
https://www.geeksforgeeks.org/priority-queue-set-1-introduction/
class.forName : The forName()
method of Java Class class returns the Class object associated with the class
or interface with the given name in the parameter as String.
decompiler: djad
JVM arguments. (For memory GC)
what operation can be carried on
byte: Still looking
How do we implement Singleton class
in Spring framework? : scope="singleton or @Singletom in beans
Java Singleton per classloader
but spring singleton is per application context (per container only one
instance)
If a function is there with a try-catch-finally and returns an integer. If in try block some exception comes and in
catch block return 1 is there and in finally return 2 is there. What value will
be returned
only 2 will be returning
Capgemini telephonic and F2F
interview questions :
1. Explain Internal implementation
of concurrent hashmap
In ConcurrentHashMap, at a time any
number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which thread want to operate. This
type of locking mechanism is known as Segment locking or bucket locking. Hence
at a time, 16 update operations can be performed by threads.
null insertion is not possible in
ConcurrentHashMap as key or value.
2. Explain internal implementation
of hashmap: refer book
3. Why don't we use vector instead
of hashmap?
4. Is Date class immutable or
mutable? :
1. Mutable object – You can change
the states and fields after the object is created. For examples: StringBuilder,
java.util.Date and etc.
2. Immutable object – You cannot
change anything after the object is created. For examples: String, boxed
primitive objects like Integer, Long and etc.
5. When we create an object of Date
class using new operator then Date class from which package will be created and
why another package is not referred?
java.util.Date
but from java 8 LocalDate is useful
and common
6. What do you mean by object
oriented programming?
Abstraction: The process of picking
out (abstracting) common features of objects and procedures.
Class: A category of objects. The class defines all the common properties of the different objects that belong to
it.
Encapsulation: The process of
combining elements to create a new entity. A procedure is a type of
encapsulation because it combines a series of computer instructions.
Information hiding: The process of
hiding details of an object or function. Information hiding is a powerful
programming technique because it reduces complexity.
Inheritance: a feature that
represents the "is a" relationship between different classes.
Interface: the languages and codes
that the applications use to communicate with each other and with the hardware.
Messaging: Message passing is a
form of communication used in parallel programming and object-oriented
programming.
Object: a self-contained entity
that consists of both data and procedures to manipulate the data.
Polymorphism: A programming
language's ability to process objects differently depending on their data type
or class.
Procedure: a section of a program
that performs a specific task.
7. When a custom thread is created,
is it synchronous or asynchronous?
synchronous
8. How will you read an excel file
in java?
using POI library
9. What does calendar API do in
java
Java Calendar Class. Java Calendar
class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.
10. Can primary key be a composite
key? If yes then what's the benefit of a composite primary key?
Yes A primary key that is made by
the combination of more than one attribute is known as a composite key
11. What does bitwise shift
operator do?
Bitwise left and right shift
operators << >> The bitwise shift operators move the bit values of
a binary object. The left operand specifies the value to be shifted. The right
operand specifies the number of positions that the bits in the value are to be
shifted.
Example
0000111110110011
The expression left_op << 3
yields:
0111110110011000
The expression left_op >> 3
yields:
0000000111110110
12. Write a trigger
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
create trigger stud_marks
before INSERT
on
Student
for each row
set new.total = new.subj1 +
new.subj2 + new.subj3, new.per = new.total * 60 / 100;
What is deadlock and synchronized
DL: Deadlock is a situation where a
set of processes are blocked because each process is holding a resource and
waiting for another resource acquired by some other process.
synchronized is a technique to
overcome deadlock by making resource available once it is free
Reverse a string of size n in n/2
iterations
How to create a Singleton class
And the final question was the creation
of Singleton using spring: use @Singleton
or
There's an array list which has
following elements
5 4 1 3 6 8 9 10
Sort this ArrayList such as that
all odd numbers come first in a sorted manner (ascending) followed by sorted
even numbers. Use comparator to do that.
todo
Expected output :
1 3 5 9 4 6 8 10
One question from opus consulting
Class A implements Serializable
Class B extends Class A
Will class B also be
serializable? If Yes then how can you stop that behavior?
There is no direct way to prevent sub class from serialization in java. One possible way by which a programmer can
achieve this is by implementing the writeObject() and readObject() methods in
the subclass and needs to throw NotSerializableException from these methods.
These methods are executed during serialization and de-serialization
respectively. By overriding these methods, we are just implementing our own
custom serialization.
throw new
NotSerializableException();
WAP to find the number of
occurrences of numbers in an array and sort it based on the occurrences
There is a singly linked list of
numbers. If there are duplicates delete the last index from it :
Program to reverse a number using
recursion
List of the string is given..from this
how to get another list contains string starts with D or d using some Java
8 API (without any loop)
https://github.com/narendraraghu/TBJ2/blob/master/src/ListOfString.java
https://github.com/narendraraghu/TBJ2/blob/master/src/ListOfString.java
Difference between abstract class
and interfaces in which scenario to be used
Program to read and write files
(CSV, txt, xls, XML) using interface or abstract class and which will be the
best approach
FileInputReader/Outputreader
Difference between synchronized
block and synchronized method
How to define many to many
association in hibernate
@ManyToMany(cascade = {
CascadeType.ALL })
What is the role of dispatcher
servlet in MVC and how it works internally simple
What is dependency injection
LinkedList 1= 10-20-30
LinkedList 2= 15-17 both are sorted in ascending order. Write a program
to merge both lists to a single list which will return ascending order. Ex
list3=10-15-17-20-30
What are row type and type record
and the difference between them
What is trigger
What is cursor write any cursor
with using while loop to fetch the data
Type of cursor
What is trigger how to define it
what is the need of trigger
Type of exception
What are system defined exceptions
How to declare and raise
user-defined exception explain with an example
Caching in hibernate. Write a
singleton class No Idea :P
Write a program to calculate the
number of bytes required to flip one number to other. Ex num1=00101001
num2=00011001
https://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b/
Sort employee objects by employee
id. If ids are the same sort by name.
write a program that will accept a
number and print the number in words (123-one hundred twenty-three)
Annotations in hibernate.
Write a query to get the
names of students whose date of joining is between 1st June to 31st June, date
of joining and name are in two different tables.
What are the event handlers in
javascript?
Explain joins using Venn
diagrams.
Create a singleton class.
multi-thread program: write a
program with 3 threads, each thread should print their ids.
what will you do to create an only
a single instance of an object? create a singleton class.
what are the other design patterns
you know?
what is facade design pattern?
write a program that will read a
file(XML or text) from FTP server and update the date in the database.
design an application to transfer
amount from savings account to current account.
design an MVC architecture diagram
for the above application.
how will you write an HLD for the
above application?
is multiple inheritances allowed in
java?
Re-entrant lock
Atomic variables : https://stackoverflow.com/questions/9749746/what-is-the-difference-between-atomic-volatile-synchronized
Vertical Scaling
Vertical scaling refers to adding more resources (CPU/RAM/DISK) to your server (database or application server still remains one) as on-demand.
Vertical Scaling is most commonly used in applications and products of middle-range as well as small and middle-sized companies. One of the most common examples of Virtual Scaling is to buy expensive hardware and use it as a Virtual Machine hypervisor (VMWare ESX).
Vertical Scaling usually means an upgrade of server hardware. Some of the reasons to scale vertically include increasing IOPS (Input / Output Operations), amplifying CPU/RAM capacity, as well as disk capacity.
However, even after using virtualization, whenever an improved performance is targeted, the risk for downtimes with it is much higher than using horizontal scaling.
Horizontal Scaling
Horizontal Scaling is a must use technology – whenever a high availability of (server) services are required
Scaling horizontally involves adding more processing units or physical machines to your server or database. It involves growing the number of nodes in the cluster, reducing the responsibilities of each member node by spreading the keyspace wider and providing additional end-points for client connections. Horizontal Scaling has been historically much more used for the high level of computing and for application and services.
Although this does not alter the capacity of each individual node, the load is decreased due to the distribution between separate server nodes.
Some of the reasons why organizations should choose to scale horizontally include increasing I/O concurrency, reducing the load on existing nodes, and increasing disk capacity.
The Internet and particular web services have boosted the use of Horizontal Scaling. Most giant companies that provide well-known web services like Google (Gmail, YouTube), Yahoo, Facebook, eBay, Amazon, etc. are using heavily horizontal scaling.
The Difference
Horizontal-scaling is often based on the partitioning of the data in which each node contains only part of the data. In the case of vertical-scaling, the data resides on a single node. Scaling here is done through multi-core by spreading the load between the CPU and RAM resources.
Which is more Feasible?
Horizontal-scaling or scale dynamically is quite easy as you can add more machines into the existing pool. Vertical-scaling, on the contrary, is often limited to the capacity of a single machine. Scaling beyond that capacity results in downtime and comes with an upper limit.
One of the good examples of horizontal scaling is Cassandra, MongoDB and that of vertical scaling is MySQL. Scaling vertically can be achieved easily by switching from small to bigger machines. But this involves downtime.
If you need to achieve superior performance issues you can use either vertical scaling or horizontal scaling or both in cloud environments. There are few auto-scalable models that are comparatively far better than traditional scaling models and are known to offer best performances without any downtime.
SQL vs NoSql
https://www.thegeekstuff.com/2014/01/sql-vs-nosql-db/
Vertical scaling refers to adding more resources (CPU/RAM/DISK) to your server (database or application server still remains one) as on-demand.
Vertical Scaling is most commonly used in applications and products of middle-range as well as small and middle-sized companies. One of the most common examples of Virtual Scaling is to buy expensive hardware and use it as a Virtual Machine hypervisor (VMWare ESX).
Vertical Scaling usually means an upgrade of server hardware. Some of the reasons to scale vertically include increasing IOPS (Input / Output Operations), amplifying CPU/RAM capacity, as well as disk capacity.
However, even after using virtualization, whenever an improved performance is targeted, the risk for downtimes with it is much higher than using horizontal scaling.
Horizontal Scaling
Horizontal Scaling is a must use technology – whenever a high availability of (server) services are required
Scaling horizontally involves adding more processing units or physical machines to your server or database. It involves growing the number of nodes in the cluster, reducing the responsibilities of each member node by spreading the keyspace wider and providing additional end-points for client connections. Horizontal Scaling has been historically much more used for the high level of computing and for application and services.
Although this does not alter the capacity of each individual node, the load is decreased due to the distribution between separate server nodes.
Some of the reasons why organizations should choose to scale horizontally include increasing I/O concurrency, reducing the load on existing nodes, and increasing disk capacity.
The Internet and particular web services have boosted the use of Horizontal Scaling. Most giant companies that provide well-known web services like Google (Gmail, YouTube), Yahoo, Facebook, eBay, Amazon, etc. are using heavily horizontal scaling.
The Difference
Horizontal-scaling is often based on the partitioning of the data in which each node contains only part of the data. In the case of vertical-scaling, the data resides on a single node. Scaling here is done through multi-core by spreading the load between the CPU and RAM resources.
Which is more Feasible?
Horizontal-scaling or scale dynamically is quite easy as you can add more machines into the existing pool. Vertical-scaling, on the contrary, is often limited to the capacity of a single machine. Scaling beyond that capacity results in downtime and comes with an upper limit.
One of the good examples of horizontal scaling is Cassandra, MongoDB and that of vertical scaling is MySQL. Scaling vertically can be achieved easily by switching from small to bigger machines. But this involves downtime.
If you need to achieve superior performance issues you can use either vertical scaling or horizontal scaling or both in cloud environments. There are few auto-scalable models that are comparatively far better than traditional scaling models and are known to offer best performances without any downtime.
SQL vs NoSql
https://www.thegeekstuff.com/2014/01/sql-vs-nosql-db/
How Fail-Fast Iterators Work?
All Collection types maintain an internal array of objects ( Object[] ) to store the elements. Fail-Fast iterators directly fetch the elements from this array. They always consider that this internal array is not modified while iterating over its elements. To know whether the collection is modified or not, they use an internal flag called modCount which is updated each time a collection is modified. Every time when an Iterator calls the next() method, it checks the modCount. If it finds the modCount has been updated after this Iterator has been created, it throws ConcurrentModificationException.
https://www.journaldev.com/13521/java-spliterator
Spliterator is a Java Iterator,
which is used to iterate elements one-by-one from a List implemented object.
Some important points about Java Spliterator are:
Java Spliterator is an interface in Java Collection API.
Spliterator is introduced in Java 8 release in java.util package.
It supports Parallel Programming functionality.
We can use it for both Collection API and Stream API classes.
It provides characteristics about Collection or API objects.
We can NOT use this Iterator for Map implemented classes.
It uses tryAdvance() method to iterate elements individually in multiple Threads to support Parallel Processing.
It uses forEachRemaining() method to iterate elements sequentially in a single thread.
It uses trySplit() method to divide itself into Sub-Spliterators to support Parallel Processing.
Spliterator supports both Sequential and Parallel processing of data.
Spliterator itself does not provide parallel programming behavior. However, it provides some methods to support it. Developers should utilize Spliterator interface methods and implement parallel programming by using the Fork/Join Framework (one good approach).
Some important points about Java Spliterator are:
Java Spliterator is an interface in Java Collection API.
Spliterator is introduced in Java 8 release in java.util package.
It supports Parallel Programming functionality.
We can use it for both Collection API and Stream API classes.
It provides characteristics about Collection or API objects.
We can NOT use this Iterator for Map implemented classes.
It uses tryAdvance() method to iterate elements individually in multiple Threads to support Parallel Processing.
It uses forEachRemaining() method to iterate elements sequentially in a single thread.
It uses trySplit() method to divide itself into Sub-Spliterators to support Parallel Processing.
Spliterator supports both Sequential and Parallel processing of data.
Spliterator itself does not provide parallel programming behavior. However, it provides some methods to support it. Developers should utilize Spliterator interface methods and implement parallel programming by using the Fork/Join Framework (one good approach).
import
java.util.Spliterator;
import java.util.ArrayList;
import java.util.List;
public class SpliteratorSequentialIteration
{
public static void main(String[] args)
{
List names = new ArrayList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting Spliterator
Spliterator namesSpliterator = names.spliterator();
// Traversing elements
namesSpliterator.forEachRemaining(System.out::println);
}
}
import java.util.ArrayList;
import java.util.List;
public class SpliteratorSequentialIteration
{
public static void main(String[] args)
{
List names = new ArrayList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting Spliterator
Spliterator namesSpliterator = names.spliterator();
// Traversing elements
namesSpliterator.forEachRemaining(System.out::println);
}
}
The effect of the volatile keyword is approximate that each individual read or write operation on that variable is atomic.
Notably, however, an operation that requires more than one read/write -- such as i++, which is equivalent to i = i + 1, which does one read and one write -- is not atomic, since another thread may write to i between the read and the write.
The Atomic classes, like AtomicInteger and AtomicReference, provide a wider variety of operations atomically, specifically including increment for AtomicInteger.
CountDownLatch in Java
CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.
Working of CountDownLatch:
When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread is required to do the count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as the count reaches zero, the waiting task starts running.
public
class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
CountDownLatch latch = new CountDownLatch(4);
ThreadLatch t1 = new ThreadLatch(latch, "T1", 1000);
ThreadLatch t2 = new ThreadLatch(latch, "T2", 2000);
ThreadLatch t3 = new ThreadLatch(latch, "T3", 3000);
ThreadLatch t4 = new ThreadLatch(latch, "T4", 4000);
t1.start();
t2.start();
t3.start();
t4.start();
latch.await();
System.out.println("Latch Ends");
}
}
class ThreadLatch extends Thread {
CountDownLatch latch;
String name;
int delay;
ThreadLatch(CountDownLatch latch, String name, int delay) {
super(name);
this.latch = latch;
this.delay = delay;
}
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(latch.getCount());
latch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
CountDownLatch latch = new CountDownLatch(4);
ThreadLatch t1 = new ThreadLatch(latch, "T1", 1000);
ThreadLatch t2 = new ThreadLatch(latch, "T2", 2000);
ThreadLatch t3 = new ThreadLatch(latch, "T3", 3000);
ThreadLatch t4 = new ThreadLatch(latch, "T4", 4000);
t1.start();
t2.start();
t3.start();
t4.start();
latch.await();
System.out.println("Latch Ends");
}
}
class ThreadLatch extends Thread {
CountDownLatch latch;
String name;
int delay;
ThreadLatch(CountDownLatch latch, String name, int delay) {
super(name);
this.latch = latch;
this.delay = delay;
}
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(latch.getCount());
latch.countDown();
}
}
Facts about CountDownLatch:
Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually the number of invited parties (threads) for an event.
The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero.
countDown() method decrements the count and await() method blocks until count == 0
https://www.callicoder.com/java-8-completablefuture-tutorial/
To Research More Whenever time is there
FUTURE AND COMPLETABLE FUTURE
OAUTH2
OPEN ID
SPRING BOOT
MICROSERVICES
MICROSERVICES DESIGN PATTERNS
DATA STRUCTURES
TIME SPACE COMPLEXITIES
Database- SQL\PLSQL
=======
Hibernate Config and BaseDAO from old code
============================================================================
WebServices-Client
Code,Reflections Code to set the methods in utils
Method[] methodObj =
header.getClass().getDeclaredMethods();
for (i = 0; i < methodObj.length; ++i) {
try
{
Object temp;
if
(methodObj[i].getName().equals("getINSTRPRTYID")) {
temp = methodObj[i].invoke(header2,
new Object[0]);
if (temp != null)
inp.setINSTR_PRTY_ID(((Integer)temp).intValue());
}
}catch(Exception
e){}
}
============================================================================
Atomic Variable
============================================================================
Hashing
Concurrent hashMap
Synchronised HashMap
LinkedHashMap
============================================================================
Serializable and Deserialization with Example
============================================================================
Generics
class Test{
T obj;
Test(T obj){
this.obj=obj;
}
T getObj(){
return this.obj;
}
}
eg. Test iObj = new Test(15);
System.out.println(iObj.getObject());
class Test
{
T
obj1; // An object of type T
U
obj2; // An object of type U
//
constructor
Test(T
obj1, U obj2)
{
this.obj1
= obj1;
this.obj2
= obj2;
}
//
To print objects of T and U
public
void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
Test obj = new Test("GfG", 15);
obj.print();
Advantages of Generics
Code Reuse
Type Safety
Individual Type Casting is not needed
Implementing generic algorithms
============================================================================
Java8-New features in java8
Lambda expressions
1. Lambda expressions can have any number of attributes
2. For single argument lambda expression parenthesis are
optional
forEach
Streams
============================================================================
fail-safe and fail fast
============================================================================
Can a class be static in Java ?
The answer is YES, we can have static class in java. In
java, we have static instance variables as well as static methods and also
static block. Classes can also be made static in Java.
Java allows us to define a class within another class. Such
a class is called a nested class. The class which enclosed nested class is
known as Outer class. In java, we can’t make Top level class static. Only
nested classes can be static.
============================================================================
Program to read data from sftp
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("username",
"127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel =
session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel =
(ChannelSftp) channel;
sftpChannel.get("remotefile.txt", "localfile.txt");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
Create session using Java Secure Channel and connect to it.
Open a Channel and connect to it.
Typecast to sftp channel
get the files through sftp channel
exit from sftp channel
disconnect from session
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1,
column2, ... column_n);
Collections
CopyOnWriteArraylist- https://www.geeksforgeeks.org/copyonwritearraylist-in-java/
Synchronised verion of Arraylist- Created a cloned copy of
underlying Arraylist on every update. JVM will sync the cloned and actual copy
of the array list.
-------------------------------------------------------------------
The unmodifiableCollection() method is used to return an
unmodifiable view of the specified collection.And an attempt to modify the
collection will result in an UnsupportedOperationException.
=========================================================================================================
Hibernate
Object States in Hibernate
1. Transient Object State:
An object which is not associated with hibernate session and
does not represent a row in the database is considered as transient. It will be
garbage collected if no other object refers to it.
An object that is created for the first time using the new()
operator is in transient state. When the object is in transient sate then it
will not contain any identifier (primary key value). You have to use save,
persist or saveOrUpdate methods to persist the transient object.
Emp emp= new Emp();
e.setName("Anuj");
//emp object in transient state
2. Persistent Object State:
An object that is associated with the hibernate session is
called as Persistent object. When the object is in persistent state, then it
represent one row of the database and consists of an identifier value.You can
make a transient instance persistent by associating it with a Session.
Long id = (Long) session.save(emp);
// emp object is now in a persistent state
3. Detached Object State:
Object which is just removed from hibernate session is
called as detached object.The sate of the detached object is called as detached
state.
When the object is in detached sate then it contain identity
but you can’t do persistence operation with that identity.
Any changes made to the detached objects are not saved to
the database. The detached object can be reattached to the new session and save
to the database using update, saveOrUpdate and merge methods.
session.close();
//object in detached state
=========================================================================================================
Set and bag
A is an unordered collection, which can contain
duplicated elements. That means if you persist a bag with some order of
elements, you cannot expect the same order retains when the collection is
retrieved. There is not a “bag” concept in Java collections framework, so we
just use a java.util.List corresponds to a .
A is similar to except that it can
only store unique objects. That means no duplicate elements can be contained in
a set. When you add the same element to a set for second time, it will replace
the old one. A set is unordered by default but we can ask it to be sorted. The
corresponding type of a in Java is java.util.Set.
Examples
Mapping
inverse="true"
lazy="true" fetch="select">
Mapping
inverse="true"
lazy="true" fetch="select">
Thus, both are mapped exactly same way in hbm file. But
differs only in the way it handles duplicate records.
JVM Architecture-Class Loaders- Application Class Loader,
Extension Class Loader, Bootstrap
Memory Management-Java (JVM) Memory Model – Memory
Management in Java and Garbage Collection
Young Generation- Eden, Survivor1, Survivor2
Old Generation
Perm Generation-contains the application metadata required
by the JVM to describe the classes and methods used in the application
Method Area-Method Area is part of space in the Perm Gen and
used to store class structure (runtime constants and static variables) and code
for methods and constructors
Memory Pool
Runtime Constant Pool
Java Stack Memory
Java Garbage Collection
Marking: This is the first step where garbage collector
identifies which objects are in use and which ones are not in use.
Normal Deletion: Garbage Collector removes the unused
objects and reclaim the free space to be allocated to other objects.
Deletion with Compacting: For better performance, after
deleting unused objects, all the survived objects can be moved to be together.
This will increase the performance of allocation of memory to newer objects.
Java Garbage Collection Types
Serial GC (-XX:+UseSerialGC)
Parallel GC (-XX:+UseParallelGC):
Parallel Old GC (-XX:+UseParallelOldGC):
Concurrent Mark Sweep (CMS) Collector
(-XX:+UseConcMarkSweepGC)
G1 Garbage Collector (-XX:+UseG1GC)
=========================================================================================================
Stop the World Event
All the Garbage Collections are “Stop the World” events
because all application threads are stopped until the operation completes.
Since Young generation keeps short-lived objects, Minor GC
is very fast and the application doesn’t get affected by this.
However Major GC takes longer time because it checks all the
live objects. Major GC should be minimized because it will make your
application unresponsive for the garbage collection duration. So if you have a
responsive application and there are a lot of Major Garbage Collection
happening, you will notice timeout errors.
The duration taken by garbage collector depends on the
strategy used for garbage collection. That’s why it’s necessary to monitor and
tune the garbage collector to avoid timeouts in the highly responsive
applications.
=========================================================================================================
Heap and Stack
1. Heap memory is used by all the parts of the application
whereas stack memory is used only by one thread of execution.
2. Whenever an object is created, it’s always stored in the
Heap space and stack memory contains the reference to it. Stack memory only
contains local primitive variables and reference variables to objects in heap
space.
3. Objects stored in the heap are globally accessible
whereas stack memory can’t be accessed by other threads.
4. Memory management in stack is done in LIFO manner whereas
it’s more complex in Heap memory because it’s used globally. Heap memory is
divided into Young-Generation, Old-Generation etc, more details at Java Garbage
Collection.
5. Stack memory is short-lived whereas heap memory lives
from the start till the end of application execution.
6. We can use -Xms and -Xmx JVM option to define the startup
size and maximum size of heap memory. We can use -Xss to define the stack
memory size.
7. When stack memory is full, Java runtime throws
java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError:
Java Heap Space error.
8. Stack memory size is very less when compared to Heap
memory. Because of simplicity in memory allocation (LIFO), stack memory is very
fast when compared to heap memory.
=========================================================================================================
String Pool
=========================================================================================================
JDK
Java Development Kit is the core component of Java
Environment and provides all the tools, executables and binaries required to
compile, debug and execute a Java Program. JDK is a platform specific software
and thats why we have separate installers for Windows, Mac and Unix systems. We
can say that JDK is superset of JRE since it contains JRE with Java compiler,
debugger and core classes. Current version of JDK is 1.7 also known as Java 7.
JRE
JRE is the implementation of JVM, it provides platform to
execute java programs. JRE consists of JVM and java binaries and other classes
to execute any program successfully. JRE doesn’t contain any development tools
like java compiler, debugger etc. If you want to execute any java program, you
should have JRE installed but we don’t need JDK for running any java program.
JVM
JVM is the heart of java programming language. When we run a
program, JVM is responsible to converting Byte code to the machine specific
code. JVM is also platform dependent and provides core java functions like
memory management, garbage collection, security etc. JVM is customizable and we
can use java options to customize it, for example allocating minimum and
maximum memory to JVM. JVM is called virtual because it provides a interface
that does not depend on the underlying operating system and machine hardware.
This independence from hardware and operating system is what makes java program
write-once run-anywhere.
JDK vs JRE vs JVM
JDK is for development purpose whereas JRE is for running
the java programs.
JDK and JRE both contains JVM so that we can run our java
program.
JVM is the heart of java programming language and provides
platform independence.
=========================================================================================================
Java is Pass by Value
The changes are not reflected back if we change the object
itself to refer some other location or object
Changes are reflected back if we do not assign reference to
a new location or object:
============================================================================
SynchronizedMap
private static class SynchronizedMap implements Map,
Serializable {
private final
Map m; // references original map
final Object
mutex; // serves the purpose of mutex in sychronized methods.
SynchronizedMap(Map
m) {
this.m
= Objects.requireNonNull(m);
mutex
= this;//Object of this SynMap Class
}
public
V put(K key, V value) {
synchronized
(mutex)
{
return
m.put(key, value);
}
}
}