Sunday, December 10, 2017

Multithreading in Java

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU
Multitasking can be achieved by two ways:
  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)

Thread-based Multitasking (Multithreading)

Each process have its own address in memory
Threads share the same address space
heavyweight
lightweight
Cost of communication between the process is high
Cost of communication between the thread is low

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.


Process is an executing instance of an application. For example, when you double click MS Word icon in your computer, you start a process that will run this MS word application.



  
Creating a thread,
1)      By extending java.lang.Thread class.

public class ThreadExtended {
public static void main(String[] arg){
//Creating a thread and starting it 
MyThread mt1 = new MyThread();
mt1.start();
}
}

class MyThread extends Thread{
public void run(){
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}




2) By implementing java.lang.Runnable interface.

public class RunnableImplementation  {

public static void main(String[] arg){
//Creating a thread and starting it 
//MyThreadRI mt = new MyThreadRI();  // Creating an instance of  MyThreadRI
//Thread thread = new Thread(mt);  // Creating a thread using Runnable implemented object
//thread.start();
// Create a thread using Java 8
Thread t1 = new Thread(()->{
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
});
t1.start();
}
}

class MyThreadRI implements Runnable{
@Override
public void run() {
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}

Thursday, December 7, 2017

String in Java


String is an object that represents a sequence of characters. There are two ways of creating String,
1. by using String literal
2. by using new keyword
Strings created using “String Literal” are stored in “String Object Pool”. String Object Pool located in heap.
String Created using “new” keyword, stored String object in Heap memory (non pool) and create a literal in “String Object Pool”.




String is a final class in Java.

String is Immutable in Java hence can be safely used in multi threaded environment.
String Literals are used to get more memory efficient Because It don’t want create any object and if literal is already there it reuses it.

Why String objects are immutable in java?
Because String uses the concept of String literal. If String is mutable, When 5 variables refers to same String then Changing a variable value will affect to all the variables.

The Hypervisor

 The hypervisor is a piece of software that runs on top of hardware infrastructure that creates a virtualization platform. The hypervisor a...