Question
stringlengths
1
113
Answer
stringlengths
22
6.98k
What are the Types of Synchronization?
There are two types of synchronization 1.Process Synchronization 2.Thread Synchronization Here, we will discuss only thread synchronization.
What is Thread Synchronization?
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)
What is Mutual Exclusive?
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
What is Concept of Lock in Java?
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 ...
Can you provide the Java Synchronized Method?
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.
Can you give me an Example of synchronized method by using annonymous class?
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....
What is Synchronized Block in Java?
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 sam...
Can you give me an Example of Synchronized Block?
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(Exc...
What is Static Synchronization?
If you make any static method as synchronized, the lock will be on the class not on object.
What is Problem without static synchronization?
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...
Can you give me an Example of Static Synchronization?
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); }c...
What is Deadlock in Java?
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 condit...
Can you provide an Example of Deadlock in Java?
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(...
Can you give me More Complicated Deadlocks?
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 ...
How to avoid deadlock?
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.
How to Avoid Deadlock in Java?
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 loc...
What is Inter-thread Communication in Java?
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 e...
Can you give me the wait() method?
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...
Can you give me the notify() method?
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()
Can you give me the notifyAll() method?
notifyAll() method Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.
What is the Difference between wait and sleep?
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-stati...
Can you provide an Example of Inter Thread Communication in Java?
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..."); ...
What is Interrupting a Thread?
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 doe...
Can you give me an Example of interrupting a thread that stops working?
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 TestInterruptingThread...
Can you provide an Example of interrupting a thread that doesn't stop working?
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...
Can you give me an Example of interrupting thread that behaves normally?
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.prin...
What about isInterrupted and interrupted method?
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++...
What is Reentrant Monitor in Java?
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.
What is the Advantage of Reentrant Monitor?
It eliminates the possibility of single thread deadlocking
What is Java I/O?
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.
What is Stream in Java?
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: sta...
What is OutputStream?
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.
What is InputStream?
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.
What is OutputStream class?
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.
Can you give me a Useful methods of OutputStream?
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 I...
What is InputStream class?
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
Can you provide a Useful method of InputStream?
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 cur...
What is Java FileOutputStream Class?
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 ...
How to use the FileOutputStream class declaration?
Let's see the declaration for Java.io.FileOutputStream class: public class FileOutputStream extends OutputStream
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 of...
What is Java FileInputStream Class?
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.
What is Java FileInputStream class declaration?
Let's see the declaration for java.io.FileInputStream class: public class FileInputStream extends InputStream
Can you give me the Java FileInputStream class methods?
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 ...
What is Java BufferedOutputStream Class?
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...
What is Java BufferedOutputStream class declaration?
Let's see the declaration for Java.io.BufferedOutputStream class: public class BufferedOutputStream extends FilterOutputStream
Can you provide the Java BufferedOutputStream class constructors?
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 bu...
What are the Java BufferedOutputStream class methods?
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...
What is Java BufferedInputStream Class?
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 str...
What is the class declaration for Java BufferedInputStream?
Let's see the declaration for Java.io.BufferedInputStream class: public class BufferedInputStream extends FilterInputStream
What are the Java BufferedInputStream class constructors?
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 ...
What are the Java BufferedInputStream class methods?
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. Met...
What is Java SequenceInputStream Class?
Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).
What is the class declaration for Java SequenceInputStream?
Let's see the declaration for Java.io.SequenceInputStream class: public class SequenceInputStream extends InputStream
What are the Constructors of SequenceInputStream class?
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 read...
What are the Methods of SequenceInputStream class?
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() Descri...
Can you give me a Java SequenceInputStream Example?
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"); FileInputStrea...
What is Java ByteArrayOutputStream Class?
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 automatic...
What is the class declaration for Java ByteArrayOutputStream?
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 automatic...
What are the Java ByteArrayOutputStream class constructors?
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,...
What are the Java ByteArrayOutputStream class methods?
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 decodi...
What is Java ByteArrayInputStream Class?
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 buf...
What are the Java ByteArrayInputStream class constructors?
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 ...
What are the Java ByteArrayInputStream class methods?
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 le...
What is Java DataOutputStream Class?
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.
What is the dedclaration for Java DataOutputStream?
Let's see the declaration for java.io.DataOutputStream class: public class DataOutputStream extends FilterOutputStream implements DataOutput
What are the Java DataOutputStream class methods?
Methods of Java DataOutputStream class Method: int size() Description: It is used to return the number of bytes written to the data output stream. Method: void write(int b) Description: It is used to write the specified byte to the underlying output stream. Method: void write(byte[] b, int off, int len) Desc...
What is Java DataInputStream Class?
Java DataInputStream class allows an application to read primitive data from the input 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.
What is the declaration for Java DataInputStream?
Let's see the declaration for java.io.DataInputStream class: public class DataInputStream extends FilterInputStream implements DataInput
What are the Java DataInputStream class Methods?
Methods of Java DataInputStream class Method: int read(byte[] b) Description: It is used to read the number of bytes from the input stream. Method: int read(byte[] b, int off, int len) Description: It is used to read len bytes of data from the input stream. Method: int readInt() Description: It is used to r...
What is Java FilterOutputStream Class?
Java FilterOutputStream class implements the OutputStream class. It provides different sub classes such as BufferedOutputStream and DataOutputStream to provide additional functionality. So it is less used individually.
What isi the class declaration for Java FilterOutputStream?
Let's see the declaration for java.io.FilterOutputStream class: public class FilterOutputStream extends OutputStream
What are the Java FilterOutputStream class Methods?
Methods of Java FilterOutputStream class Method: void write(int b) Description: It is used to write the specified byte to the output stream. Method: void write(byte[] ary) Description: It is used to write ary.length byte to the output stream. Method: void write(byte[] b, int off, int len) Description: It is...
What is Java FilterInputStream Class?
Java FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. So it is less used individually.
What is the class declaration for Java FilterInputStream?
Let's see the declaration for java.io.FilterInputStream class public class FilterInputStream extends InputStream
What are the Java FilterInputStream class Methods?
Methods of Java FilterInputStream class Method: int available() Description: It is used to return an estimate number of 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[] b) Description: It i...
What is Java - ObjectStreamClass?
ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.
What is Java ObjectStreamField class?
Fields of Java - ObjectStreamClass Modifier and Type: static ObjectStreamField[] Field: NO_FIELDS Description: serialPersistentFields value indicating no serializable fields
What is Java Console Class?
The Java Console class is be used to get input from console. It provides methods to read texts and passwords. If you read password using Console class, it will not be displayed to the user. The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.
What is the class declaration for Java Console?
Let's see the declaration for Java.io.Console class: public final class Console extends Object implements Flushable
What are the Java Console class methods?
Methods of Java Console class Method: Reader reader() Description: It is used to retrieve the reader object associated with the console Method: String readLine() Description: It is used to read a single line of text from the console. Method: String readLine(String fmt, Object... args) Description: It provi...
How to get the object of Console?
System class provides a static method console() that returns the singleton instance of Console class. public static Console console(){} Let's see the code to get the instance of Console class. Console c=System.console();
Can you give me a Java Console Example?
import java.io.Console; class ReadStringTest{ public static void main(String args[]){ Console c=System.console(); System.out.println("Enter your name: "); String n=c.readLine(); System.out.println("Welcome "+n); } } Output: Enter your name: Nakul Jain Welcome Nakul Jain
Can you give me a Java Console Example to read password?
import java.io.Console; class ReadPasswordTest{ public static void main(String args[]){ Console c=System.console(); System.out.println("Enter password: "); char[] ch=c.readPassword(); String pass=String.valueOf(ch);//converting char array into string System.out.println("Password is: "+p...
What is Java FilePermission Class?
Java FilePermission class contains the permission related to a directory or file. All the permissions are related with path. The path can be of two types: 1) D:\\IO\\-: It indicates that the permission is associated with all sub directories and files recursively. 2) D:\\IO\\*: It indicates that the permission is ...
What is the class declaration for Java FilePermission?
Let's see the declaration for Java.io.FilePermission class: public final class FilePermission extends Permission implements Serializable
What are the Methods of FilePermission class?
Methods of FilePermission class Method: ByteArrayOutputStream() Description: Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary. Method: ByteArrayOutputStream(int size) Description: Creates a new byte array output stream, with a buffer capacity o...
What are the Java FilePermission class methods?
Methods of Java FilePermission class Method: int hashCode() Description: It is used to return the hash code value of an object. Method: String getActions() Description: It is used to return the "canonical string representation" of an action. Method: boolean equals(Object obj) Description: It is used to ch...
Can you give me a Java FilePermission Example?
Let's see the simple example in which permission of a directory path is granted with read permission and a file of this directory is granted for write permission. package com.javatpoint; import java.io.*; import java.security.PermissionCollection; public class FilePermissionExample{ public sta...
What is Java Writer?
It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.
Can you give me a Java Writer Example?
import java.io.*; public class WriterExample { public static void main(String[] args) { try { Writer w = new FileWriter("output.txt"); String content = "I love my country"; w.write(content); w.close(); System.out.println("Do...
What is Java Reader?
Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both. Some of the implementation class are Buf...
What is Java FileWriter Class?
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java. Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
What is the declaration for Java FileWriter?
Let's see the declaration for Java.io.FileWriter class: public class FileWriter extends OutputStreamWriter
What are the Constructors of FileWriter class?
Constructors of FileWriter class Constructor: FileWriter(String file) Description: Creates a new file. It gets file name in string. Constructor: FileWriter(File file) Description: Creates a new file. It gets file name in File object.
What are the Methods of FileWriter class?
Methods of FileWriter class Method: void write(String text) Description: It is used to write the string into FileWriter. Method: void write(char c) Description: It is used to write the char into FileWriter. Method: void write(char[] c) Description: It is used to write char array into FileWriter. Method: v...
Can you give mee a Java FileWriter Example?
In this example, we are writing the data in the file testout.txt using Java FileWriter class. package com.javatpoint; import java.io.FileWriter; public class FileWriterExample { public static void main(String args[]){ try{ FileWriter fw=new FileWriter("D:\\testout.txt"); ...
What is Java FileReader Class?
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. It is character-oriented class which is used for file handling in java.
What is Java FileReader class declaration?
Let's see the declaration for Java.io.FileReader class: public class FileReader extends InputStreamReader
Can you give me the Constructors of FileReader class?
Constructors of FileReader class Constructor: FileReader(String file) Description: It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. Constructor: FileReader(File file) Description: It gets filename in file instance. It opens the given file...