hereral/Clara-Training-Data huggingface dataset:
Question: How to Tune the Thread Pool?
Answer: 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.
Question: What is ThreadGroup in Java?
Answer: 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.
Question: What are the Constructors of ThreadGroup class?
Answer: 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.
Question: What are the Methods of ThreadGroup class?
Answer: 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.
Question: What is Java Shutdown Hook?
Answer: 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.
Question: When does the JVM shut down?
Answer: The JVM shuts down when:

-user presses ctrl+c on the command prompt
-System.exit(int) method is invoked
-user logoff
-user shutdown etc.
Question: What is The addShutdownHook(Thread hook) method?

Answer: 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();
Question: Can you give me a Simple example of Shutdown Hook?
Answer: 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.
Question: What is Java Garbage Collection?
Answer: 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.
Question: What is the Advantage of Garbage Collection?
Answer: -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.
Question: How can an object be unreferenced?
Answer: There are many ways:

-By nulling the reference
-By assigning a reference to another
-By anonymous object etc.
Question: Can you give me a Simple Example of garbage collection in java?
Answer: 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
Question: What is Java Runtime class?
Answer: 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.
Question: What are the Important methods of Java Runtime class?
Answer: 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.
Question: What is Java Runtime exec() method?
Answer: public class Runtime1{  
 public static void main(String args[])throws Exception{  
  Runtime.getRuntime().exec("notepad");//will open a new notepad  
 }  
}
Question: How to shutdown system in Java?
Answer: 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");  
 }  
}
Question: How to shutdown windows system in Java?
Answer: public class Runtime2{  
 public static void main(String args[])throws Exception{  
  Runtime.getRuntime().exec("c:\\Windows\\System32\\shutdown -s -t 0");  
 }  
}
Question: How to restart system in Java?
Answer: public class Runtime3{  
 public static void main(String args[])throws Exception{  
  Runtime.getRuntime().exec("shutdown -r -t 0");  
 }  
}
Question: What is Java Runtime freeMemory() and totalMemory() method?
Answer: 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
Question: What is Synchronization in Java?
Answer: 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.
Question: Why use Synchronization?
Answer: The synchronization is mainly used to

1.To prevent thread interference.
2.To prevent consistency problem.
Question: What are the Types of Synchronization?
Answer: There are two types of synchronization

1.Process Synchronization
2.Thread Synchronization
Here, we will discuss only thread synchronization.
Question: What is Thread Synchronization?
Answer: There are two types of thread synchronization mutual exclusive and inter-thread communication.

1.Mutual Exclusive
  1.Synchronized method.
   2.Synchronized block.
   3.Static synchronization.
2.Cooperation (Inter-thread communication in java)
Question: What is Mutual Exclusive?
Answer: Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:

1.By Using Synchronized Method
2.By Using Synchronized Block
3.By Using Static Synchronization
Question: What is Concept of Lock in Java?
Answer: Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
Question: Can you provide the Java Synchronized Method?
Answer: f you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
Question: Can you give me an Example of synchronized method by using annonymous class?
Answer: In this program, we have created the two threads by using the anonymous class, so less coding is required.

TestSynchronization3.java

//Program of synchronized method by using annonymous class  
class Table{  
 synchronized void printTable(int n){//synchronized method  
   for(int i=1;i<=5;i++){  
     System.out.println(n*i);  
     try{  
      Thread.sleep(400);  
     }catch(Exception e){System.out.println(e);}  
   }  
  
 }  
}  
  
public class TestSynchronization3{  
public static void main(String args[]){  
final Table obj = new Table();//only one object  
  
Thread t1=new Thread(){  
public void run(){  
obj.printTable(5);  
}  
};  
Thread t2=new Thread(){  
public void run(){  
obj.printTable(100);  
}  
};  
  
t1.start();  
t2.start();  
}  
}  
Output:

       5
       10
       15
       20
       25
       100
       200
       300
       400
       500
Question: What is Synchronized Block in Java?
Answer: Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Question: Can you give me an Example of Synchronized Block?
Answer: Let's see the simple example of synchronized block.

TestSynchronizedBlock1.java

class Table  
{      
 void printTable(int n){    
   synchronized(this){//synchronized block    
     for(int i=1;i<=5;i++){    
      System.out.println(n*i);    
      try{    
       Thread.sleep(400);    
      }catch(Exception e){System.out.println(e);}    
     }    
   }    
 }//end of the method    
}    
    
class MyThread1 extends Thread{    
Table t;    
MyThread1(Table t){    
this.t=t;    
}    
public void run(){    
t.printTable(5);    
}    
    
}    
class MyThread2 extends Thread{    
Table t;    
MyThread2(Table t){    
this.t=t;    
}    
public void run(){    
t.printTable(100);    
}    
}    
    
public class TestSynchronizedBlock1{    
public static void main(String args[]){    
Table obj = new Table();//only one object    
MyThread1 t1=new MyThread1(obj);    
MyThread2 t2=new MyThread2(obj);    
t1.start();    
t2.start();    
}    
}    
Output:

       5
       10
       15
       20
       25
       100
       200
       300
       400
       500
Question: What is Static Synchronization?
Answer: If you make any static method as synchronized, the lock will be on the class not on object.
Question: What is Problem without static synchronization?
Answer: Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock. But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. We don't want interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.
Question: Can you give me an Example of Static Synchronization?
Answer: In this example we have used synchronized keyword on the static method to perform static synchronization.

TestSynchronization4.java

class Table  
{     
 synchronized static void printTable(int n){    
   for(int i=1;i<=10;i++){    
     System.out.println(n*i);    
     try{    
       Thread.sleep(400);    
     }catch(Exception e){}    
   }    
 }    
}    
class MyThread1 extends Thread{    
public void run(){    
Table.printTable(1);    
}    
}    
class MyThread2 extends Thread{    
public void run(){    
Table.printTable(10);    
}    
}    
class MyThread3 extends Thread{    
public void run(){    
Table.printTable(100);    
}    
}    
class MyThread4 extends Thread{    
public void run(){    
Table.printTable(1000);    
}    
}    
public class TestSynchronization4{    
public static void main(String t[]){    
MyThread1 t1=new MyThread1();    
MyThread2 t2=new MyThread2();    
MyThread3 t3=new MyThread3();    
MyThread4 t4=new MyThread4();    
t1.start();    
t2.start();    
t3.start();    
t4.start();    
}    
}    

Output:

       1
       2
       3
       4
       5
       6
       7
       8
       9
       10
       10       
       20
       30
       40
       50
       60
       70
       80
       90
       100
       100
       200
       300
       400
       500
       600
       700
       800
       900
       1000
       1000
       2000
       3000
       4000
       5000
       6000
       7000
       8000
       9000
       10000
Question: What is Deadlock in Java?
Answer: Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Question: Can you provide an Example of Deadlock in Java?
Answer: TestDeadlockExample1.java

public class TestDeadlockExample1 {  
  public static void main(String[] args) {  
    final String resource1 = "ratan jaiswal";  
    final String resource2 = "vimal jaiswal";  
    // t1 tries to lock resource1 then resource2  
    Thread t1 = new Thread() {  
      public void run() {  
          synchronized (resource1) {  
           System.out.println("Thread 1: locked resource 1");  
  
           try { Thread.sleep(100);} catch (Exception e) {}  
  
           synchronized (resource2) {  
            System.out.println("Thread 1: locked resource 2");  
           }  
         }  
      }  
    };  
  
    // t2 tries to lock resource2 then resource1  
    Thread t2 = new Thread() {  
      public void run() {  
        synchronized (resource2) {  
          System.out.println("Thread 2: locked resource 2");  
  
          try { Thread.sleep(100);} catch (Exception e) {}  
  
          synchronized (resource1) {  
            System.out.println("Thread 2: locked resource 1");  
          }  
        }  
      }  
    };  
  
      
    t1.start();  
    t2.start();  
  }  
}       
Output:

Thread 1: locked resource 1
        Thread 2: locked resource 2
Question: Can you give me More Complicated Deadlocks?
Answer: A deadlock may also include more than two threads. The reason is that it can be difficult to detect a deadlock. Here is an example in which four threads have deadlocked:

Thread 1 locks A, waits for B

Thread 2 locks B, waits for C

Thread 3 locks C, waits for D

Thread 4 locks D, waits for A

Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread 4 waits for thread 1.
Question: How to avoid deadlock?
Answer: A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the resources A and B, is the main issue. To solve the issue we will have to simply re-order the statements where the code is accessing shared resources.
Question: How to Avoid Deadlock in Java?
Answer: Deadlocks cannot be completely resolved. But we can avoid them by following basic rules mentioned below:

Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for a deadlock condition. It normally happens when you give locks to multiple threads.
Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to the unnecessary threads that cause the deadlock condition.
Using Thread Join: A deadlock usually happens when one thread is waiting for the other to finish. In this case, we can use join with a maximum time that a thread will take.
Question: What is Inter-thread Communication in Java?
Answer: Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:

-wait()
-notify()
-notifyAll()
Question: Can you give me the wait() method?
Answer: wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.

Method: public final void wait()throws InterruptedException
Description: It waits until object is notified.


Method: public final void wait(long timeout)throws InterruptedException
Description: It waits for the specified amount of time.
Question: Can you give me the notify() method?
Answer:  notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

Syntax:

public final void notify()
Question: Can you give me the notifyAll() method?
Answer: notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()
Question: Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Answer: It is because they are related to lock and object has a lock.
Question: What is the Difference between wait and sleep?
Answer: Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.

Wait(): The wait() method releases the lock.
Sleep(): The sleep() method doesn't release the lock.

Wait(): It is a method of Object class
Sleep(): It is a method of Thread class

Wait(): It is the non-static method
Sleep(): It is the static method

Wait(): It should be notified by notify() or notifyAll() methods
Sleep(): After the specified amount of time, sleep is completed.
Question: Can you provide an Example of Inter Thread Communication in Java?
Answer: Let's see the simple example of inter thread communication.

Test.java

class Customer{    
int amount=10000;    
    
synchronized void withdraw(int amount){    
System.out.println("going to withdraw...");    
    
if(this.amount<amount){    
System.out.println("Less balance; waiting for deposit...");    
try{wait();}catch(Exception e){}    
}    
this.amount-=amount;    
System.out.println("withdraw completed...");    
}    
    
synchronized void deposit(int amount){    
System.out.println("going to deposit...");    
this.amount+=amount;    
System.out.println("deposit completed... ");    
notify();    
}    
}    
    
class Test{    
public static void main(String args[]){    
final Customer c=new Customer();    
new Thread(){    
public void run(){c.withdraw(15000);}    
}.start();    
new Thread(){    
public void run(){c.deposit(10000);}    
}.start();    
    
}}    
Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Question: What is Interrupting a Thread?
Answer: If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread class for thread interruption.

The 3 methods provided by the Thread class for interrupting a thread

-public void interrupt()
-public static boolean interrupted()
-public boolean isInterrupted()
Question: Can you give me an Example of interrupting a thread that stops working?
Answer: In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don't want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's first see the example where we are propagating the exception.

TestInterruptingThread1.java

class TestInterruptingThread1 extends Thread{  
public void run(){  
try{  
Thread.sleep(1000);  
System.out.println("task");  
}catch(InterruptedException e){  
throw new RuntimeException("Thread interrupted..."+e);  
}  
  
}  
  
public static void main(String args[]){  
TestInterruptingThread1 t1=new TestInterruptingThread1();  
t1.start();  
try{  
t1.interrupt();  
}catch(Exception e){System.out.println("Exception handled "+e);}  
  
}  
}  

download this example
Output:

Exception in thread-0  
       java.lang.RuntimeException: Thread interrupted...
       java.lang.InterruptedException: sleep interrupted
       at A.run(A.java:7)
Question: Can you provide an Example of interrupting a thread that doesn't stop working?
Answer: In this example, after interrupting the thread, we handle the exception, so it will break out the sleeping but will not stop working.

TestInterruptingThread2.java

class TestInterruptingThread2 extends Thread{  
public void run(){  
try{  
Thread.sleep(1000);  
System.out.println("task");  
}catch(InterruptedException e){  
System.out.println("Exception handled "+e);  
}  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
TestInterruptingThread2 t1=new TestInterruptingThread2();  
t1.start();  
  
t1.interrupt();  
  
}  
}  

Output:

Exception handled  
       java.lang.InterruptedException: sleep interrupted
       thread is running...
Question: Can you give me an Example of interrupting thread that behaves normally?
Answer: If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.

TestInterruptingThread3.java

class TestInterruptingThread3 extends Thread{  
  
public void run(){  
for(int i=1;i<=5;i++)  
System.out.println(i);  
}  
  
public static void main(String args[]){  
TestInterruptingThread3 t1=new TestInterruptingThread3();  
t1.start();  
  
t1.interrupt();  
  
}  
}  
Output:

1
       2
       3
       4 
       5
Question: What about isInterrupted and interrupted method?
Answer: The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.

TestInterruptingThread4.java

public class TestInterruptingThread4 extends Thread{  
  
public void run(){  
for(int i=1;i<=2;i++){  
if(Thread.interrupted()){  
System.out.println("code for interrupted thread");  
}  
else{  
System.out.println("code for normal thread");  
}  
  
}//end of for loop  
}  
  
public static void main(String args[]){  
  
TestInterruptingThread4 t1=new TestInterruptingThread4();  
TestInterruptingThread4 t2=new TestInterruptingThread4();  
  
t1.start();  
t1.interrupt();  
  
t2.start();  
  
}  
}  
Output:

Code for interrupted thread
       code for normal thread
       code for normal thread
       code for normal thread
Question: What is Reentrant Monitor in Java?
Answer: According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same monitor for different synchronized methods if method is called from the method.
Question: What is the Advantage of Reentrant Monitor?
Answer: It eliminates the possibility of single thread deadlocking
Question: What is Java I/O?
Answer: Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.
Question: What is Stream in Java?
Answer: A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

System.out.println("simple message");  
System.err.println("error message");  
Let's see the code to get input from console.

int i=System.in.read();//returns ASCII code of 1st character  
System.out.println((char)i);//will print the character
Question: What is OutputStream?
Answer: Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.
Question: What is InputStream?
Answer: Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.
Question: What is OutputStream class?
Answer: OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Question: Can you give me a Useful methods of OutputStream?
Answer: Useful methods of OutputStream
Method: public void write(int)throws IOException
Description: is used to write a byte to the current output stream.

Method: public void write(byte[])throws IOException
Description: is used to write an array of byte to the current output stream.

Method: public void flush()throws IOException
Description: flushes the current output stream.

Method: public void close()throws IOException
Description: is used to close the current output stream.
Question: What is InputStream class?
Answer: InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
Question: Can you provide a Useful method of InputStream?
Answer: Useful methods of InputStream
Method: public abstract int read()throws IOException
Description: reads the next byte of data from the input stream. It returns -1 at the end of the file.

Method: public int available()throws IOException
Description: returns an estimate of the number of bytes that can be read from the current input stream.

Method: public void close()throws IOException
Description: is used to close the current input stream.
Question: What is Java FileOutputStream Class?
Answer: Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
Question: How to use the FileOutputStream class declaration?
Answer: Let's see the declaration for Java.io.FileOutputStream class:

public class FileOutputStream extends OutputStream
Answer: FileOutputStream class methods
Method: protected void finalize()
Description: It is used to clean up the connection with the file output stream.

Method: void write(byte[] ary)
Description: It is used to write ary.length bytes from the byte array to the file output stream.
 
Method: void write(byte[] ary, int off, int len)
Description: It is used to write len bytes from the byte array starting at offset off to the file output stream.

Method: void write(int b)
Description: It is used to write the specified byte to the file output stream.

Method: FileChannel getChannel()
Description: It is used to return the file channel object associated with the file output stream.

Method: FileDescriptor getFD()
Description: It is used to return the file descriptor associated with the stream.

Method: void close()
Description:  It is used to closes the file output stream.
Question: What is Java FileInputStream Class?
Answer: Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Question: What is Java FileInputStream class declaration?
Answer: Let's see the declaration for java.io.FileInputStream class:

public class FileInputStream extends InputStream
Question: Can you give me the Java FileInputStream class methods?
Answer: Java FileInputStream class methods
Method:  int available()
Description: It is used to return the estimated number of bytes that can be read from the input stream.

Method:  int read()
Description: It is used to read the byte of data from the input stream.

Method: int read(byte[] b)
Description: It is used to read up to b.length bytes of data from the input stream

Method: int read(byte[] b, int off, int len)
Description: It is used to read up to len bytes of data from the input stream.

Method:  long skip(long x)
Description: It is used to skip over and discards x bytes of data from the input stream.

Method:  FileChannel getChannel()
Description: 	It is used to return the unique FileChannel object associated with the file input stream.

Method:  FileDescriptor getFD()
Description: It is used to return the FileDescriptor object.

Method:  protected void finalize()
Description: It is used to ensure that the close method is call when there is no more reference to the file input stream.

Method:  void close()
Description: It is used to closes the stream.
Question: What is Java BufferedOutputStream Class?
Answer: Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));
Question: What is Java BufferedOutputStream class declaration?
Answer: Let's see the declaration for Java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream
Question: Can you provide the Java BufferedOutputStream class constructors?
Answer: Java BufferedOutputStream class constructors
Constructor: BufferedOutputStream(OutputStream os)
Description: It creates the new buffered output stream which is used for writing the data to the specified output stream.

Constructor:  BufferedOutputStream(OutputStream os, int size)
Description: It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.
Question: What are the Java BufferedOutputStream class methods?
Answer: Java BufferedOutputStream class methods
Method: void write(int b)
Description: It writes the specified byte to the buffered output stream.

Method: void write(byte[] b, int off, int len)
Description: It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset

Method: void flush()
Description: It flushes the buffered output stream.
Question: What is Java BufferedInputStream Class?
Answer: Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

The important points about BufferedInputStream are:

-When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
-When a BufferedInputStream is created, an internal buffer array is created.
Question: What is the class declaration for Java BufferedInputStream?
Answer: Let's see the declaration for Java.io.BufferedInputStream class:

public class BufferedInputStream extends FilterInputStream
Question: What are the Java BufferedInputStream class constructors?
Answer: Java BufferedInputStream class constructors
Constructor: BufferedInputStream(InputStream IS)
Description: It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.

Constructor: BufferedInputStream(InputStream IS, int size)
Description: It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.
Question: What are the Java BufferedInputStream class methods?
Answer: Java BufferedInputStream class methods
Method: int available()
Description: It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.

Method: int read()
Description: It read the next byte of data from the input stream.

Method: int read(byte[] b, int off, int ln)
Description: It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.

Method: void close()
Description: It closes the input stream and releases any of the system resources associated with the stream.

Method: void reset()
Description: It repositions the stream at a position the mark method was last called on this input stream.

Method: void mark(int readlimit)
Description: It sees the general contract of the mark method for the input stream.

Method: long skip(long x)
Description: It skips over and discards x bytes of data from the input stream.

Method: boolean markSupported()
Description: It tests for the input stream to support the mark and reset methods.
Question: What is Java SequenceInputStream Class?
Answer: Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).
Question: What is the class declaration for Java SequenceInputStream?
Answer: Let's see the declaration for Java.io.SequenceInputStream class:

public class SequenceInputStream extends InputStream
Question: What are the Constructors of SequenceInputStream class?
Answer: Constructors of SequenceInputStream class
Constructor: SequenceInputStream(InputStream s1, InputStream s2)
Description: creates a new input stream by reading the data of two input stream in order, first s1 and then s2.

Constructor: SequenceInputStream(Enumeration e)
Description: creates a new input stream by reading the data of an enumeration whose type is InputStream.
Question: What are the Methods of SequenceInputStream class?
Answer: Methods of SequenceInputStream class
Method: int read()
Description:  It is used to read the next byte of data from the input stream.


Method: int read(byte[] ary, int off, int len)
Description: It is used to read len bytes of data from the input stream into the array of bytes.

Method: int available()
Description: It is used to return the maximum number of byte that can be read from an input stream.

Method: void close()
Description: It is used to close the input stream.
Question: Can you give me a Java SequenceInputStream Example?
Answer: In this example, we are printing the data of two files testin.txt and testout.txt.

package com.javatpoint;  
  
import java.io.*;  
class InputStreamExample {    
  public static void main(String args[])throws Exception{    
   FileInputStream input1=new FileInputStream("D:\\testin.txt");    
   FileInputStream input2=new FileInputStream("D:\\testout.txt");    
   SequenceInputStream inst=new SequenceInputStream(input1, input2);    
   int j;    
   while((j=inst.read())!=-1){    
    System.out.print((char)j);    
   }    
   inst.close();    
   input1.close();    
   input2.close();    
  }    
}    
Here, we are assuming that you have two files: testin.txt and testout.txt which have following information:

testin.txt:

Welcome to Java IO Programming.
testout.txt:

It is the example of Java SequenceInputStream class.
After executing the program, you will get following output:

Output:

Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.
Question: What is Java ByteArrayOutputStream Class?
Answer: Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

The buffer of ByteArrayOutputStream automatically grows according to data.
Question: What is the class declaration for Java ByteArrayOutputStream?
Answer: Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

The buffer of ByteArrayOutputStream automatically grows according to data.
Question: What are the Java ByteArrayOutputStream class constructors?
Answer: Constructors of Java ByteArrayOutputStream class
Constructor: ByteArrayOutputStream()
Description: Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.

Constructor: ByteArrayOutputStream(int size)
Description: Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
Question: What are the Java ByteArrayOutputStream class methods?
Answer: Methods of Java ByteArrayOutputStream class
Method: int size()
Description: It is used to returns the current size of a buffer.

Method: byte[] toByteArray()
Description: It is used to create a newly allocated byte array.

Method: String toString()
Description: It is used for converting the content into a string decoding bytes using a platform default character set.

Method: String toString(String charsetName)
Description: It is used for converting the content into a string decoding bytes using a specified charsetName.

Method: void write(int b)
Description: It is used for writing the byte specified to the byte array output stream.

Method: void write(byte[] b, int off, int len
Description: It is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.

Method: void writeTo(OutputStream out)
Description: It is used for writing the complete content of a byte array output stream to the specified output stream.

Method: void reset()
Description: It is used to reset the count field of a byte array output stream to zero value.

Method: void close()
Description: It is used to close the ByteArrayOutputStream.
Question: What is Java ByteArrayInputStream Class?
Answer: The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the name suggests, it can be used to read byte array as input stream.

Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array.

The buffer of ByteArrayInputStream automatically grows according to data.
Question: What are the Java ByteArrayInputStream class constructors?
Answer: Constructors of Java ByteArrayInputStream class
Constructor: ByteArrayInputStream(byte[] ary)
Description: Creates a new byte array input stream which uses ary as its buffer array.

Constructor: ByteArrayInputStream(byte[] ary, int offset, int len)
Description: Creates a new byte array input stream which uses ary as its buffer array that can read up to specified len bytes of data from an array.
Question: What are the Java ByteArrayInputStream class methods?
Answer: Methods of Java ByteArrayInputStream class
Method: int available()
Description: It is used to return the number of remaining bytes that can be read from the input stream.

Method: int read()
Description: It is used to read the next byte of data from the input stream.

Method: int read(byte[] ary, int off, int len)
Description: It is used to read up to len bytes of data from an array of bytes in the input stream.

Method: boolean markSupported()
Description: It is used to test the input stream for mark and reset method.

Method: long skip(long x)
Description: 	It is used to skip the x bytes of input from the input stream.

Method: void mark(int readAheadLimit)
Description: It is used to set the current marked position in the stream.

Method: void reset()
Description: It is used to reset the buffer of a byte array.

Method: void close()
Description: It is used for closing a ByteArrayInputStream.
Question: What is Java DataOutputStream Class?
Answer: Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.
Question: What is the dedclaration for Java DataOutputStream?
Answer: Let's see the declaration for java.io.DataOutputStream class:

public class DataOutputStream extends FilterOutputStream implements DataOutput