Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
What does Java Inner class need?
|
Sometimes users need to program a class in such a way so that no other class can access it. Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class. That way all the outer class can access all the objects of the inner class.
|
What is the Difference between nested class and inner class in Java?
|
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
|
Can you give me the Types of Nested classes?
|
There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.
o Non-static nested class (inner class)
1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class
Type: Member inner class
Description: : A class created within class and outside method.
Type: : Anonymous inner class
DescriptionA class created for implementing an interface or extending class. The java compiler decides its name.
Type: local inner class
Description: A class was created within the method.
Type: static nested class
DescriptionA static class was created within the class.
Type: nested interface
Description: An interface created within class or interface.
|
What is Java Member Inner class?
|
A non-static class that is created inside a class but outside a method is called member inner class. It is also known as a regular inner class. It can be declared with access modifiers like public, default, private, and protected.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
|
Can you give me an example of Java Member Inner Class?
|
In this example, we are creating a msg() method in the member inner class that is accessing the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30
|
How to instantiate Member Inner class in Java?
|
An object or instance of a member's inner class always exists within an object of its outer class. The new operator is used to create the object of member inner class with slightly different syntax.
The general form of syntax to create an object of the member inner class is as follows:
Syntax:
OuterClassReference.new MemberInnerClassConstructor();
Example:
obj.new Inner();
|
What is the Internal working of Java member inner class?
|
The java compiler creates two class files in the case of the inner class. The class file name of the inner class is "Outer$Inner". If you want to instantiate the inner class, you must have to create the instance of the outer class. In such a case, an instance of inner class is created inside the instance of the outer class.
|
What is the Internal code generated by the compiler in Java?
|
The Java compiler creates a class file named Outer$Inner in this case. The Member inner class has the reference of Outer class that is why it can access all the data members of Outer class including private.
import java.io.PrintStream;
class Outer$Inner
{
final Outer this$0;
Outer$Inner()
{ super();
this$0 = Outer.this;
}
void msg()
{
System.out.println((new StringBuilder()).append("data is ")
.append(Outer.access$000(Outer.this)).toString());
}
}
|
What is Java Anonymous inner class?
|
Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:
1.Class (may be abstract or concrete).
2.Interface
|
Can you provide a Java anonymous inner class example using class?
|
TestAnonymousInner.java
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Output:
nice fruits
|
Can you provide a Java anonymous inner class example using interface?
|
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Output:
nice fruits
|
What is Java Local inner class?
|
A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block they are defined within, due to which local inner classes cannot have any access modifiers associated with them. However, they can be marked as final or abstract. These classes have access to the fields of the class enclosing it.
If you want to invoke the methods of the local inner class, you must instantiate this class inside the method.
|
Can you provide a Java local inner class example?
|
LocalInner1.java
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
Output:
30
|
What is Internal class generated by the compiler?
|
In such a case, the compiler creates a class named Simple$1Local that has the reference of the outer class.
import java.io.PrintStream;
class localInner1$Local
{
final localInner1 this$0;
localInner1$Local()
{
super();
this$0 = Simple.this;
}
void msg()
{
System.out.println(localInner1.access$000(localInner1.this));
}
}
Rule: Local variables can't be private, public, or protected.
|
What is the Rules for Java Local Inner class?
|
Rules for Java Local Inner class
1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in the local inner class.
|
Can you give me an Example of local inner class with local variable?
|
LocalInner2.java
class localInner2{
private int data=30;//instance variable
void display(){
int value=50;//local variable must be final till jdk 1.7 only
class Local{
void msg(){System.out.println(value);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner2 obj=new localInner2();
obj.display();
}
}
Output:
50
|
What is Java static nested class?
|
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.
-It can access static data members of the outer class, including private.
-The static nested class cannot access non-static (instance) data members or
|
Can you give me a Java static nested class example with instance method?
|
TestOuter1.java
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
|
Can you give me a Java static nested class example with a static method
|
If you have the static member inside the static nested class, you don't need to create an instance of the static nested class.
TestOuter2.java
public class TestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}
Output:
data is 30
|
What is Java Nested Interface?
|
An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can't be accessed directly.
|
What are the Points to remember for nested interfaces?
|
There are given some points that should be remembered by the java programmer.
-The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared within the class.
-Nested interfaces are declared static
|
What is the Syntax of nested interface which is declared within the interface?
|
interface interface_name{
...
interface nested_interface_name{
...
}
}
|
What is the Syntax of nested interface which is declared within the class?
|
class class_name{
...
interface nested_interface_name{
...
}
}
|
Can you give me an Example of nested interface which is declared within the interface?
|
In this example, we will learn how to declare the nested interface and how we can access it.
TestNestedInterface1.java
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}
public static void main(String args[]){
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}
Output:
hello nested interface
|
Can we define a class inside the interface?
|
Yes, if we define a class inside the interface, the Java compiler creates a static nested class. Let's see how can we define a class within the interface:
interface M{
class A{}
}
|
What is Multithreading in Java?
|
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
|
What is the Advantages of Java Multithreading?
|
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
|
What is Thread in java?
|
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
Java Multithreading
As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.
|
What is Java Thread class?
|
Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
|
What are the Java Thread Methods?
|
Java Thread class
Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
Java Thread Methods
Modifier and Type: void
Method: start()
Description: It is used to start the execution of the thread.
Modifier and Type: void
Method: run()
Description: It is used to do an action for a thread.
Modifier and Type: static void
Method: sleep()
Description: It sleeps a thread for the specified amount of time.
Modifier and Type: static Thread
Method: currentThread()
Description: It returns a reference to the currently executing thread object.
Modifier and Type: void
Method: join()
Description: It waits for a thread to die.
Modifier and Type: int
Method: getPriority()
Description: It returns the priority of the thread.
Modifier and Type: void
Method: setPriority()
Description: It changes the priority of the thread.
Modifier and Type: String
Method: getName()
Description: It returns the name of the thread.
Modifier and Type: void
Method: setName()
Description: It changes the name of the thread.
Modifier and Type: long
Method: getId()
Description: It returns the id of the thread.
Modifier and Type: boolean
Method: isAlive()
Description: It tests if the thread is alive.
Modifier and Type: static void
Method: yield()
Description: It causes the currently executing thread object to pause and allow other threads to execute temporarily.
Modifier and Type: void
Method: suspend()
Description: It is used to suspend the thread.
Modifier and Type: void
Method: resume()
Description: It is used to resume the suspended thread.
Modifier and Type: void
Method: stop()
Description: It is used to stop the thread.
Modifier and Type: void
Method: destroy()
Description: It is used to destroy the thread group and all of its subgroups.
Modifier and Type: boolean
Method: isDaemon()
Description: It tests if the thread is a daemon thread.
Modifier and Type: void
Method: setDaemon()
Description: It marks the thread as daemon or user thread.
Modifier and Type: void
Method: interrupt()
Description: It interrupts the thread.
Modifier and Type: boolean
Method: isinterrupted()
Description: It tests whether the thread has been interrupted.
Modifier and Type: static boolean
Method: interrupted()
Description: It tests whether the current thread has been interrupted.
Modifier and Type: static int
Method: checkAccess()
Description: It determines if the currently running thread has permission to modify the thread.
Modifier and Type: static boolean
Method: holdLock()
Description: It returns true if and only if the current thread holds the monitor lock on the specified object.
Modifier and Type: static void
Method: dumpStack()
Description: It is used to print a stack trace of the current thread to the standard error stream.
Modifier and Type: StackTraceElement[]
Method: getStackTrace()
Description: It returns an array of stack trace elements representing the stack dump of the thread.
Modifier and Type: static int
Method: enumerate()
Description: It is used to copy every active thread's thread group and its subgroup into the specified array.
Modifier and Type: Thread.State
Method: getState()
Description: It is used to return the state of the thread.
Modifier and Type: ThreadGroup
Method: getThreadGroup()
Description: It is used to return the thread group to which this thread belongs
Modifier and Type: String
Method: toString()
Description: It is used to return a string representation of this thread, including the thread's name, priority, and thread group.
Modifier and Type: void
Method: notify()
Description: It is used to give the notification for only one thread which is waiting for a particular object.
Modifier and Type: void
Method: notifyAll()
Description: It is used to give the notification to all waiting threads of a particular object.
Modifier and Type: void
Method: setContextClassLoader()
Description: It sets the context ClassLoader for the Thread.
Modifier and Type: ClassLoader
Method: getContextClassLoader()
Description: It returns the context ClassLoader for the thread.
Modifier and Type: static Thread.UncaughtExceptionHandler
Method: getDefaultUncaughtExceptionHandler()
Description: It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
Modifier and Type: static void
Method: setDefaultUncaughtExceptionHandler()
Description: It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.
|
What is the Life cycle of a Thread (Thread States)?
|
In Java, a thread always exists in any one of the following states. These states are:
1.New
2.Active
3.Blocked / Waiting
4.Timed Waiting
5.Terminated
|
Can you give me an Explanation of Different Thread States?
|
New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is runnable, and the other is running.
-Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
-Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
-When a thread has finished its job, then it exists or terminates normally.
-Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
Java thread life cycle
Implementation of Thread States
In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These constants are:
|
What are the Implementation of Thread States?
|
In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These constants are:
public static final Thread.State NEW
It represents the first state of a thread that is the NEW state.
public static final Thread.State RUNNABLE
It represents the runnable state.It means a thread is waiting in the queue to run.
public static final Thread.State BLOCKED
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
public static final Thread.State WAITING
It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to complete its task.
public static final Thread.State TIMED_WAITING
It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A thread invoking the following method reaches the timed waiting state.
-sleep
-join with timeout
-wait with timeout
-parkUntil
-parkNanos
public static final Thread.State TERMINATED
It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its execution.
|
Can you give me an example of Java Program for Demonstrating Thread States?
|
The following Java program shows some of the states of a thread defined above.
FileName: ThreadState.java
// ABC class implements the interface Runnable
class ABC implements Runnable
{
public void run()
{
// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ ThreadState.t1.getState());
// try-catch block
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
// ThreadState class implements the interface Runnable
public class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;
// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();
t1 = new Thread(obj);
// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());
// invoking the start() method on
// the thread t1
t1.start();
// thread t1 is moved to the Runnable state
System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
}
public void run()
{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);
// thread t2 is created and is currently in the NEW state.
System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
t2.start();
// thread t2 is moved to the runnable state
System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());
// try-catch block for the smooth flow of the program
try
{
// moving the thread t1 to the state timed waiting
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );
// try-catch block for the smooth flow of the program
try
{
// waiting for thread t2 to complete its execution
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());
}
}
Output:
The state of thread t1 after spawning it - NEW
The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED
|
Java Threads | How to create a thread in Java?
|
There are two ways to create a thread:
1.By extending Thread class
2.By implementing Runnable interface.
|
What are the Commonly used Constructors of Thread class?
|
Commonly used Constructors of Thread class:
-Thread()
-Thread(String name)
-Thread(Runnable r)
-Thread(Runnable r,String name)
|
What are the Commonly used methods of Thread class?
|
1.public void run(): is used to perform action for a thread.
2.public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3.public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
4.public void join(): waits for a thread to die.
5.public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6.public int getPriority(): returns the priority of the thread.
7.public int setPriority(int priority): changes the priority of the thread.
8.public String getName(): returns the name of the thread.
9.public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
15.public void suspend(): is used to suspend the thread(depricated).
16.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or user thread.
20.public void interrupt(): interrupts the thread.
21.public boolean isInterrupted(): tests if the thread has been interrupted.
22.public static boolean interrupted(): tests if the current thread has been interrupted.
|
What is Runnable interface?
|
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().
1.public void run(): is used to perform action for a thread.
|
How to Start a thread in Java?
|
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
-A new thread starts(with new callstack).
-The thread moves from New state to the Runnable state.
-When the thread gets a chance to execute, its target run() method will run.
|
Can you give me a Java Thread Example by extending Thread class?
|
FileName: Multi.java
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running...
|
Can you give me a Java Thread Example by implementing Runnable interface?
|
FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output:
thread is running...
|
How to use the Thread Class: Thread(String Name)?
|
We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Output:
My first thread
|
How to use the Thread Class: Thread(Runnable r, String name)?
|
Observe the following program.
FileName: MyThread2.java
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}
Output:
My new thread
Now the thread is running ...
|
What is Thread Scheduler in Java?
|
A component of Java that decides which thread to run or execute and which thread to wait is called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is in the runnable state. However, if there is more than one thread in the runnable state, it is up to the thread scheduler to pick one of the threads and ignore the other ones. There are some criteria that decide which thread will execute first. There are two factors for scheduling a thread i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means that thread has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority cannot be the factor to pick a thread from these two threads. In such a case, arrival time of thread is considered by the thread scheduler. A thread that arrived first gets the preference over the other threads.
|
What is the Working of the Java Thread Scheduler?
|
Let's understand the working of the Java thread scheduler. Suppose, there are five threads that have different arrival times and different priorities. Now, it is the responsibility of the thread scheduler to decide which thread will get the CPU first.
The thread scheduler selects the thread that has the highest priority, and the thread begins the execution of the job. If a thread is already in runnable state and another thread (that has higher priority) reaches in the runnable state, then the current thread is pre-empted from the processor, and the arrived thread with higher priority gets the CPU time.
When two threads (Thread 2 and Thread 3) having the same priorities and arrival time, the scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that arrives first gets the opportunity to execute first.
|
What is Thread.sleep() in Java?
|
The Java Thread class provides the two variant of the sleep() method. First one accepts only an arguments, whereas the other variant accepts two arguments. The method sleep() is being used to halt the working of a thread for a given amount of time. The time up to which the thread remains in the sleeping state is known as the sleeping time of the thread. After the sleeping time is over, the thread starts its execution from where it has left.
|
What is The sleep() Method Syntax in Java?
|
Following are the syntax of the sleep() method.
public static void sleep(long mls) throws InterruptedException
public static void sleep(long mls, int n) throws InterruptedException
The method sleep() with the one parameter is the native method, and the implementation of the native method is accomplished in another programming language. The other methods having the two parameters are not the native method. That is, its implementation is accomplished in Java. We can access the sleep() methods with the help of the Thread class, as the signature of the sleep() methods contain the static keyword. The native, as well as the non-native method, throw a checked Exception. Therefore, either try-catch block or the throws keyword can work here.
The Thread.sleep() method can be used with any thread. It means any other thread or the main thread can invoke the sleep() method.
|
What are the Important Points to Remember About the Sleep() Method?
|
Whenever the Thread.sleep() methods execute, it always halts the execution of the current thread.
Whenever another thread does interruption while the current thread is already in the sleep mode, then the InterruptedException is thrown.
If the system that is executing the threads is busy, then the actual sleeping time of the thread is generally more as compared to the time passed in arguments. However, if the system executing the sleep() method has less load, then the actual sleeping time of the thread is almost equal to the time passed in the argument.
|
Can you give me an Example of the sleep() method in Java : on the custom thread?
|
e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
|
Can you give me an Example of the sleep() Method in Java : on the main thread?
|
FileName: TestSleepMethod2.java
// important import statements
import java.lang.Thread;
import java.io.*;
public class TestSleepMethod2
{
// main method
public static void main(String argvs[])
{
try {
for (int j = 0; j < 5; j++)
{
// The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs
Thread.sleep(1000);
// displaying the value of the variable
System.out.println(j);
}
}
catch (Exception expn)
{
// catching the exception
System.out.println(expn);
}
}
}
Output:
0
1
2
3
4
|
Can you give me an Example of the sleep() Method in Java: When the sleeping time is -ive?
|
The following example throws the exception IllegalArguementException when the time for sleeping is negative.
FileName: TestSleepMethod3.java
// important import statements
import java.lang.Thread;
import java.io.*;
public class TestSleepMethod3
{
// main method
public static void main(String argvs[])
{
// we can also use throws keyword followed by
// exception name for throwing the exception
try
{
for (int j = 0; j < 5; j++)
{
// it throws the exception IllegalArgumentException
// as the time is -ive which is -100
Thread.sleep(-100);
// displaying the variable's value
System.out.println(j);
}
}
catch (Exception expn)
{
// the exception iscaught here
System.out.println(expn);
}
}
}
Output:
java.lang.IllegalArgumentException: timeout value is negative
|
Can we start a thread twice?
|
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Output:
running
Exception in thread "main" java.lang.IllegalThreadStateException
|
What if we call Java run() method directly instead start() method?
|
Each thread starts in a separate call stack.
Invoking the run() method from the main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
FileName: TestCallRun1.java
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}
Output:
running...
|
What is Java join() method?
|
The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish its execution. Suppose th be the object the class Thread whose thread is doing its execution currently, then the th.join(); statement ensures that th is finished before the program does the execution of the next statement. When there are more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period. However, similar to the sleep() method in Java, the join() method is also dependent on the operating system for the timing, so we should not assume that the join() method waits equal to the time we mention in the parameters. The following are the three overloaded join() methods.
|
Can you give me the Description of The Overloaded join() Method?
|
join(): When the join() method is invoked, the current thread stops its execution and the thread goes into the wait state. The current thread remains in the wait state until the thread on which the join() method is invoked has achieved its dead state. If interruption of the thread occurs, then it throws the InterruptedException.
|
Can you give me an Example of join() Method in Java?
|
The following program shows the usage of the join() method.
FileName: ThreadJoinExample.java
// A Java program for understanding
// the joining of threads
// import statement
import java.io.*;
// The ThreadJoin class is the child class of the class Thread
class ThreadJoin extends Thread
{
// overriding the run method
public void run()
{
for (int j = 0; j < 2; j++)
{
try
{
// sleeping the thread for 300 milli seconds
Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName());
}
// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
}
}
}
public class ThreadJoinExample
{
// main method
public static void main (String argvs[])
{
// creating 3 threads
ThreadJoin th1 = new ThreadJoin();
ThreadJoin th2 = new ThreadJoin();
ThreadJoin th3 = new ThreadJoin();
// thread th1 starts
th1.start();
// starting the second thread after when
// the first thread th1 has ended or died.
try
{
System.out.println("The current thread name is: "+ Thread.currentThread().getName());
// invoking the join() method
th1.join();
}
// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
// thread th2 starts
th2.start();
// starting the th3 thread after when the thread th2 has ended or died.
try
{
System.out.println("The current thread name is: " + Thread.currentThread().getName());
th2.join();
}
// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
// thread th3 starts
th3.start();
}
}
Output:
The current thread name is: main
The current thread name is: Thread - 0
0
The current thread name is: Thread - 0
1
The current thread name is: main
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1
|
What is The Join() Method: InterruptedException?
|
We have learnt in the description of the join() method that whenever the interruption of the thread occurs, it leads to the throwing of InterruptedException. The following example shows the same.
FileName: ThreadJoinExample1.java
class ABC extends Thread
{
Thread threadToInterrupt;
// overriding the run() method
public void run()
{
// invoking the method interrupt
threadToInterrupt.interrupt();
}
}
public class ThreadJoinExample1
{
// main method
public static void main(String[] argvs)
{
try
{
// creating an object of the class ABC
ABC th1 = new ABC();
th1.threadToInterrupt = Thread.currentThread();
th1.start();
// invoking the join() method leads
// to the generation of InterruptedException
th1.join();
}
catch (InterruptedException ex)
{
System.out.println("The exception has been caught. " + ex);
}
}
}
Output:
The exception has been caught. java.lang.InterruptedException
|
Can you give me Some More Examples of the join() Method?
|
Let' see some other examples.
Filename: TestJoinMethod1.java
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
|
Can you give me a join(long miliseconds) Method Example?
|
Filename: TestJoinMethod2.jav
class TestJoinMethod2 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:
1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
|
How to Name a Thread?
|
The Thread class provides methods to change and get the name of a thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName() method. The syntax of setName() and getName() methods are given below:
public String getName(): is used to return the name of a thread.
public void setName(String name): is used to change the name of a thread.
|
Can you give me an Example of naming a thread : Using setName() Method?
|
FileName: TestMultiNaming1.java
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:Sonoo Jaiswal
running...
running...
|
Can you give me an Example of naming a thread : Without Using setName() Method?
|
One can also set the name of a thread at the time of the creation of a thread, without using the setName() method. Observe the following code.
FileName: ThreadNamingExample.java
// A Java program that shows how one can
// set the name of a thread at the time
// of creation of the thread
// import statement
import java.io.*;
// The ThreadNameClass is the child class of the class Thread
class ThreadName extends Thread
{
// constructor of the class
ThreadName(String threadName)
{
// invoking the constructor of
// the superclass, which is Thread class.
super(threadName);
}
// overriding the method run()
public void run()
{
System.out.println(" The thread is executing....");
}
}
public class ThreadNamingExample
{
// main method
public static void main (String argvs[])
{
// creating two threads and settting their name
// using the contructor of the class
ThreadName th1 = new ThreadName("JavaTpoint1");
ThreadName th2 = new ThreadName("JavaTpoint2");
// invoking the getName() method to get the names
// of the thread created above
System.out.println("Thread - 1: " + th1.getName());
System.out.println("Thread - 2: " + th2.getName());
// invoking the start() method on both the threads
th1.start();
th2.start();
}
}
Output:
Thread - 1: JavaTpoint1
Thread - 2: JavaTpoint2
The thread is executing....
The thread is executing....
|
What is Current Thread?
|
The currentThread() method returns a reference of the currently executing thread.
public static Thread currentThread()
|
Can you give me an Example of currentThread() method?
|
FileName: TestMultiNaming2.java
class TestMultiNaming2 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
|
What is the Priority of a Thread (Thread Priority)?
|
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.
|
What is Setter & Getter Method of Thread Priority?
|
Let's discuss the setter and getter method of the thread priority.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
|
What are the 3 constants defined in Thread class?
|
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
|
Can you give me an Example of priority of a Thread?
|
FileName: ThreadPriorityExample.java
// Importing the required classes
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String argvs[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
// We did not mention the priority of the thread.
// Therefore, the priorities of the thread is 5, the default value
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// Setting priorities of above threads by
// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
|
Can you give me an Example of IllegalArgumentException?
|
We know that if the value of the parameter newPriority of the method getPriority() goes out of the range (1 to 10), then we get the IllegalArgumentException. Let's observe the same with the help of an example.
FileName: IllegalArgumentException.java
// importing the java.lang package
import java.lang.*;
public class IllegalArgumentException extends Thread
{
// the main method
public static void main(String argvs[])
{
// Now, priority of the main thread is set to 17, which is greater than 10
Thread.currentThread().setPriority(17);
// The current thread is retrieved
// using the currentThread() method
// displaying the main thread priority
// using the getPriority() method of the Thread class
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}
When we execute the above program, we get the following exception:
Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1141)
at IllegalArgumentException.main(IllegalArgumentException.java:12)
|
What is Daemon Thread in Java?
|
Daemon thread in Java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.
|
What are the Points to remember for Daemon Thread in Java?
|
-It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
-Its life depends on user threads.
-It is a low priority thread.
|
Why JVM terminates the daemon thread if there is no user thread?
|
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
|
What are the Methods for Java Daemon thread by Thread class?
|
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
Method: public void setDaemon(boolean status)
Description: is used to mark the current thread as daemon thread or user thread.
Method: public boolean isDaemon()
Description: is used to check that current is daemon.
|
Can you give me a Simple example of Daemon thread in java?
|
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
|
What is Java Thread Pool?
|
Java Thread pool represents a group of worker threads that are waiting for the job and reused many times.
In the case of a thread pool, a group of fixed-size threads is created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, the thread is contained in the thread pool again.
|
What are the Thread Pool Methods?
|
newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.
newCachedThreadPool(): The method creates a new thread pool that creates the new threads when needed but will still use the previously created thread whenever they are available to use.
newSingleThreadExecutor(): The method creates a new thread.
|
What is the Advantage of Java Thread Pool?
|
Better performance It saves time because there is no need to create a new thread.
|
Can you give me an Example of Java Thread Pool?
|
Let's see a simple example of the Java thread pool using ExecutorService and Executors.
File: WorkerThread.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
processmessage();//call processmessage method that sleeps the thread for 2 seconds
System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
}
private void processmessage() {
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
File: TestThreadPool.java
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);//calling execute method of ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
}
}
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
|
What are the Risks involved in Thread Pools?
|
The following are the risk involved in the thread pools.
Deadlock: It is a known fact that deadlock can come in any program that involves multithreading, and a thread pool introduces another scenario of deadlock. Consider a scenario where all the threads that are executing are waiting for the results from the threads that are blocked and waiting in the queue because of the non-availability of threads for the execution.
Thread Leakage: Leakage of threads occurs when a thread is being removed from the pool to execute a task but is not returning to it after the completion of the task. For example, when a thread throws the exception and the pool class is not able to catch this exception, then the thread exits and reduces the thread pool size by 1. If the same thing repeats a number of times, then there are fair chances that the pool will become empty, and hence, there are no threads available in the pool for executing other requests.
Resource Thrashing: A lot of time is wasted in context switching among threads when the size of the thread pool is very large. Whenever there are more threads than the optimal number may cause the starvation problem, and it leads to resource thrashing.
|
How to Tune the Thread Pool?
|
The accurate size of a thread pool is decided by the number of available processors and the type of tasks the threads have to execute. If a system has the P processors that have only got the computation type processes, then the maximum size of the thread pool of P or P + 1 achieves the maximum efficiency. However, the tasks may have to wait for I/O, and in such a scenario, one has to take into consideration the ratio of the waiting time (W) and the service time (S) for the request; resulting in the maximum size of the pool P * (1 + W / S) for the maximum efficiency.
|
What is ThreadGroup in Java?
|
Java provides a convenient way to group multiple threads in a single object. In such a way, we can suspend, resume or interrupt a group of threads by a single method call.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other thread group. The thread group creates a tree in which every thread group except the initial thread group has a parent.
A thread is allowed to access information about its own thread group, but it cannot access the information about its thread group's parent thread group or any other thread groups.
|
What are the Constructors of ThreadGroup class?
|
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
Constructor: ThreadGroup(String name)
Description: creates a thread group with given name.
Constructor: ThreadGroup(ThreadGroup parent, String name)
Description: creates a thread group with a given parent group and name.
|
What are the Methods of ThreadGroup class?
|
Methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of ThreadGroup methods is given below.
Modifier and Type: void
Method: checkAccess()
Description: This method determines if the currently running thread has permission to modify the thread group.
Modifier and Type: int
Method: activeCount()
Description: This method returns an estimate of the number of active threads in the thread group and its subgroups.
Modifier and Type: int
Method: activeGroupCount()
Description: This method returns an estimate of the number of active groups in the thread group and its subgroups.
Modifier and Type: void
Method: destroy()
Description: This method destroys the thread group and all of its subgroups.
Modifier and Type: int
Method: enumerate(Thread[] list)
Description: This method copies into the specified array every active thread in the thread group and its subgroups.
Modifier and Type: int
Method: getMaxPriority()
Description: This method returns the maximum priority of the thread group.
Modifier and Type: String
Method: getName()
Description: This method returns the name of the thread group.
Modifier and Type: ThreadGroup
Method: getParent()
Description: This method returns the parent of the thread group.
Modifier and Type: void
Method: interrupt()
Description: This method interrupts all threads in the thread group.
Modifier and Type: boolean
Method: isDaemon()
Description: This method tests if the thread group is a daemon thread group.
Modifier and Type: void
Method: setDaemon(boolean daemon)
Description: This method changes the daemon status of the thread group.
Modifier and Type: boolean
Method: isDestroyed()
Description: This method tests if this thread group has been destroyed.
Modifier and Type: void
Method: list()
Description: This method prints information about the thread group to the standard output.
Modifier and Type: boolean
Method: parentOf(ThreadGroup g
Description: This method tests if the thread group is either the thread group argument or one of its ancestor thread groups.
Modifier and Type: void
Method: suspend()
Description: This method is used to suspend all threads in the thread group.
Modifier and Type: void
Method: resume()
Description: This method is used to resume all threads in the thread group which was suspended using suspend() method.
Modifier and Type: void
Method: setMaxPriority(int pri)
Description: This method sets the maximum priority of the group.
Modifier and Type: void
Method: stop()
Description: This method is used to stop all threads in the thread group.
Modifier and Type: String
Method: toString()
Description: This method returns a string representation of the Thread group.
|
What is Java Shutdown Hook?
|
A special construct that facilitates the developers to add some code that has to be run when the Java Virtual Machine (JVM) is shutting down is known as the Java shutdown hook. The Java shutdown hook comes in very handy in the cases where one needs to perform some special cleanup work when the JVM is shutting down. Note that handling an operation such as invoking a special method before the JVM terminates does not work using a general construct when the JVM is shutting down due to some external factors. For example, whenever a kill request is generated by the operating system or due to resource is not allocated because of the lack of free memory, then in such a case, it is not possible to invoke the procedure. The shutdown hook solves this problem comfortably by providing an arbitrary block of code.
Taking at a surface level, learning about the shutdown hook is straightforward. All one has to do is to derive a class using the java.lang.Thread class, and then provide the code for the task one wants to do in the run() method when the JVM is going to shut down. For registering the instance of the derived class as the shutdown hook, one has to invoke the method Runtime.getRuntime().addShutdownHook(Thread), whereas for removing the already registered shutdown hook, one has to invoke the removeShutdownHook(Thread) method.
In nutshell, the shutdown hook can be used to perform cleanup resources or save the state when JVM shuts down normally or abruptly. Performing clean resources means closing log files, sending some alerts, or something else. So if you want to execute some code before JVM shuts down, use the shutdown hook.
|
When does the JVM shut down?
|
The JVM shuts down when:
-user presses ctrl+c on the command prompt
-System.exit(int) method is invoked
-user logoff
-user shutdown etc.
|
What is The addShutdownHook(Thread hook) method?
|
The addShutdownHook() method of the Runtime class is used to register the thread with the Virtual Machine.
Syntax:
public void addShutdownHook(Thread hook){}
The object of the Runtime class can be obtained by calling the static factory method getRuntime(). For example:
Runtime r = Runtime.getRuntime();
|
Can you give me a Simple example of Shutdown Hook?
|
FileName: MyThread.java
class MyThread extends Thread{
public void run(){
System.out.println("shut down hook task completed..");
}
}
public class TestShutdown1{
public static void main(String[] args)throws Exception {
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
System.out.println("Now main sleeping... press ctrl+c to exit");
try{Thread.sleep(3000);}catch (Exception e) {}
}
}
Output:
Now main sleeping... press ctrl+c to exit
shut down hook task completed.
|
What is Java Garbage Collection?
|
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
|
What is the Advantage of Garbage Collection?
|
-It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
-It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
|
How can an object be unreferenced?
|
There are many ways:
-By nulling the reference
-By assigning a reference to another
-By anonymous object etc.
|
Can you give me a Simple Example of garbage collection in java?
|
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
|
What is Java Runtime class?
|
Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.
|
What are the Important methods of Java Runtime class?
|
Important methods of Java Runtime class
Method: public static Runtime getRuntime()
Description: returns the instance of Runtime class.
Method: public void exit(int status)
Description: terminates the current virtual machine.
Method: public void addShutdownHook(Thread hook)
Description: registers new hook thread.
Method: public Process exec(String command)throws IOException
Description: executes given command in a separate process.
Method: public int availableProcessors()
Description: returns no. of available processors.
Method: public long freeMemory()
Description: returns amount of free memory in JVM.
Method: public long totalMemory()
Description: returns amount of total memory in JVM.
|
What is Java Runtime exec() method?
|
public class Runtime1{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("notepad");//will open a new notepad
}
}
|
How to shutdown system in Java?
|
You can use shutdown -s command to shutdown system. For windows OS, you need to provide full path of shutdown command e.g. c:\\Windows\\System32\\shutdown.
Here you can use -s switch to shutdown system, -r switch to restart system and -t switch to specify time delay.
public class Runtime2{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("shutdown -s -t 0");
}
}
|
How to shutdown windows system in Java?
|
public class Runtime2{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");
}
}
|
How to restart system in Java?
|
public class Runtime3{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec("shutdown -r -t 0");
}
}
|
What is Java Runtime freeMemory() and totalMemory() method?
|
In the given program, after creating 10000 instance, free memory will be less than the previous free memory. But after gc() call, you will get more free memory.
public class MemoryTest{
public static void main(String args[])throws Exception{
Runtime r=Runtime.getRuntime();
System.out.println("Total Memory: "+r.totalMemory());
System.out.println("Free Memory: "+r.freeMemory());
for(int i=0;i<10000;i++){
new MemoryTest();
}
System.out.println("After creating 10000 instance, Free Memory: "+r.freeMemory());
System.gc();
System.out.println("After gc(), Free Memory: "+r.freeMemory());
}
}
Total Memory: 100139008
Free Memory: 99474824
After creating 10000 instance, Free Memory: 99310552
After gc(), Free Memory: 100182832
|
What is Synchronization in Java?
|
Synchronization in Java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
|
Why use Synchronization?
|
The synchronization is mainly used to
1.To prevent thread interference.
2.To prevent consistency problem.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.