5.which Algorithm Garbage Collector Uses To Perform Garbage Collection?
5.which Algorithm Garbage Collector Uses To Perform Garbage Collection?
Heap area:- It is the runtime data area in which objects are allocated.
Method area:- It stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
JVM language stack:- It stores frames.It holds local variables and partial results,
and plays a part in method invocation and return.Each thread has a private JVM
stack, created at the same time as thread.A new frame is created each time a
method is invoked. A frame is destroyed when its method invocation completes.
PC (program counter) register:-. It contains the address of the Java virtual
machine instruction currently being executed.
Native Methods Stack:- Native method stacks is called C stacks.It support native
methods (methods written in a language other than the Java programming
language), typically allocated to each thread when the thread is created.The size of
native method stacks can be either fixed or dynamic.
5.Which algorithm garbage collector uses to perform garbage collection?
Sweep Phase
As the name suggests it sweeps the unreachable objects i.e. it clears the heap
memory for all the unreachable objects. All those objects whose marked value is
set to false are cleared from the heap memory, for all other objects (reachable
objects) the marked bit is set to false.
Now the mark value for all the reachable objects is set to false, since we will run
the algorithm (if required) and again we will go through the mark phase to mark all
the reachable objects.
Algorithm Sweep Phase
Sweep()
For each object p in heap
If markedBit(p) = true then
markedBit(p) = false
else
heap.release(p)
It handles the case with cyclic references, even in case of a cycle, this algorithm
never ends up in an infinite loop.
There are no additional overheads incurred during the execution of the algorithm.
Disadvantages of Mark and Sweep Algorithm
The main disadvantage of the mark-and-sweep approach is the fact that that normal
program execution is suspended while the garbage collection algorithm runs.
Other disadvantage is that, after the Mark and Sweep Algorithm is run several
times on a program, reachable objects end up being separated by many, small
unused memory regions. Look at the below figure for better understanding.
Figure:
Here white blocks denote the free memory, while the grey blocks denote the
memory taken by all the reachable objects.
Now the free segments (which are denoted by white color) are of varying size lets
say the 5 free segments are of size 1, 1, 2, 3, 5 (size in units).
Now we need to create an object which takes 10 units of memory, now assuming
that memory can be allocated only in contiguous form of blocks, the creation of
object isnt possible although we have an available memory space of 12 units and it
will cause OutOfMemory error. This problem is termed as Fragmentation. We
have memory available in fragments but we are unable to utilize that memory
space.
We can reduce the fragmentation by compaction; we shuffle the memory content to
place all the free memory blocks together to form one large block. Now consider
the above example, after compaction we have a continuous block of free memory
of size 12 units so now we can allocate memory to an object of size 10 units.
6. How many times finalize method is called on an Object?
Finalize() method is called only one time just before the object is garbage
collected.
7. Is it mandatory to define main method() in a class?
Its not mandatory to define main method .For example web application does not
have main method.If we want any program to execute then main method is
required.For standalone application we need main() method because it is the entry
point we dont have any entry point as we have for web applications.
8. If we dont define a main method and execute a class do we get any error?
main() method is not needed for compiling a program but we need it for executing
a program.When we try to execute a class without main method we get runtime
execution.
9. public static void main(String args[])
{
System.out.println(args[0]);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Java 6:
Vector = 10
Arraylist = 10
Hashtable = 11
Hashmap = 16
Hashset = 16
Java 7:
Vector = 10
Arraylist = 0. Size will change to 10 once we add the element in the list
Hashtable = 11
Hashmap = 0. Size will change to 16 once we add the element in the map
Hashset = 0. Size will change to 16 once we add the element in the set
System.exit() is called.
}
private static String getRomanEquivalentOfInteger(int number){
if(number<=0){
return "not defined";
}
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");
String romanEqui="";
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
if(number/key!=0){
for (int i = 0; i < (number/key); i++) {
romanEqui = romanEqui + map.get(key);
}
number = number % key;
}
}
return romanEqui;
}
}
15. Why do we need polymorphism? When, where and how can we use it
Polymorphism is everywhere in daily life. Object oriented programming concepts
are developed from real life hence we can find several examples of every concept
of OOP in real life.
// int Literal
// String
// Double
Hence you can see that we have to remember only one function name (reducing
our complexity) to print all the different values instead of having different
functions to print the values of different data types
16.length vs length()
length --- arrays (int[], double[], String[]) ---- to know the length of the arrays.
length() --- String related Object (String, StringBuilder etc)to know the length of
the String
size() --- Collection Object (ArrayList, Set etc)to know the size of the Collection
23. Why does Java not show an error for double semicolon at the
end of a statement?
Writes and reads of volatile long and double values are always atomic.
Writes to and reads of references are always atomic, regardless of whether
they are implemented as 32-bit or 64-bit values.
Some implementations may find it convenient to divide a single write action
on a 64-bit long or double value into two write actions on adjacent 32-bit
values. For efficiencys sake, this behavior is implementation-specific; an
implementation of the Java Virtual Machine is free to perform writes
to long and double values atomically or in two parts.
Implementations of the Java Virtual Machine are encouraged to avoid
splitting 64-bit values where possible. Programmers are encouraged to declare
shared 64-bit values as volatile or synchronize their programs correctly to
avoid possible complications.
So point is, in Java, long and double arent thread safe. When multiple threads are
going to access a long or a double value without synchronization, it can cause
problems. To ensure atomic/thread safety, it is essential to use volatile to ensure
changes made by one thread are visible to other threads. Thats how we can ensure
the read/write is atomic and thread safe.
However, if all reads and writes of 64-bit long and double values occur within a
synchronized block, the atomicity of the read/write is guaranteed.
26. java primitive data types atomic, reliable, threadsafe in multi threaded
programming ?
primitive datatypes are not threadsafe in java !!
Use AtomicIntger for threadsafe.
27. What is AtomicInteger class and how it's functioning is different from
using a volatile or synchronized?
AtomicInteger uses combination of volatile & CAS (compare and swap) to achieve
thread-safety for Integer Counter. It is non-blocking in nature and thus highly
usable in writing high throughput concurrent data structures that can be used under
low to moderate thread contention.
Compare-And-Swap
In computer science, compare-and-swap (CAS) is an atomic instruction used in
multi-threading to achieve synchronization. It compares the contents of a memory
location to a given value and, only if they are the same, modifies the contents of
that memory location to a given new value. This is done as a single atomic
operation. The atomicity guarantees that the new value is calculated based on upto-date information
Thread Contention
Essentially thread contention is a condition where one thread is waiting for a
lock/object that is currently being held by another thread. Wwaiting thread cannot
use that object until the other thread has unlocked that particular object.
Read & write to volatile variables have same memory semantics as that of
acquiring and releasing a monitor using synchronized code block. So the visibility
of volatile field is guaranteed by the JMM (Java Memory Model).
AtomicInteger class stores its value field in a volatile variable, thus it is a decorator
over the traditional volatile variable, but it provides unique non-blocking
mechanism for updating the value after requiring the hardware level support for
CAS (compare and set/swap). Under low to moderate thread contention, atomic
updates provides higher throughput compared to synchronized blocking increment
operation.
Here is the implementation for getAndIncrement() method of AtomicInteger Class
(as of Java 7).
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
You can see that no lock is acquired to increment the value, rather CAS is used
inside infinite loop to update the new value, thats why it can be used to write
scalable application where thread contention is low to medium