Java Biotesgaxpo12
Java Biotesgaxpo12
Garvit notes
ackage is also a collection of classes interfaces and sub sub packages etc.
Java support more than 18 international languages so java take 2 byte for characters, because
for 18 international language 1 byte of memory is not sufficient for storing all characters and
symbols present in 18 languages. Java supports Unicode but c support ascii code. In ascii code
only English language are present, so for storing all English latter and symbols 1 byte is
sufficient.
Java and javac are tools or application programs or exe files developed by sun micro system
and supply as a part of jdk 1.5/1.6/1.7/1.8 in bin folder. Java tool are used for run the java
program and javac tool are used for compile the java program.
Different Java programmers can have different styles and approaches to write program. By
using standard Java naming conventions they make their code easier to read for themselves
and for other programmers. Readability of Java code is important because it means less time is
spent trying to figure out what the code does, and leaving more time to fix or modify it.
Java follows camelcase syntax for naming the class, interface, method and variable.
What is JVM ?
What is classloader ?
Class loader subsystem will load the .class file into java stack and later sufficient memory will
be allocated for all the properties of the java program into following five memory locations.
• Heap area
• Method area
• Java stack
• PC register
• Native stack
The main aim of JIT compiler is to speed up the execution of java program.
Boolean data type takes zero bytes of main memory space because Boolean data type of java
implemented by Sun Micro System with a concept of flip - flop. A flip - flop is a general
purpose register which stores one bit of information (one true and zero false).
• Java is use Bytecode which is more faster than ordinary pointer code so
Performance of java is high.
• Garbage collector, collect the unused memory space and improve the
performance of java application.
• Java have no pointers so that using java program we can develop an
application very easily.
• It support multithreading, because of this time consuming process can
be reduced to execute the program.
Java is a platform independent programming language, Because when you install jdk software
on your system then automatically jvm are install on your system. For every operating system
separate jvm is available which is capable to read .class file or byte code. When we compile
your java code then .class file is generated by javac compiler these code are readable by jvm
and every operating system have its own jvm so jvm is platform dependent but due to jvm java
language is become platform independent.
Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
A class has to be loaded in main memory before we start using it. Static block is executed
during class loading. This is the reason why a static block executes before the main method.
The dot operator(.) is used to access the instance variables and methods of class objects.It is
also used to access classes and sub-packages from a package.
The main purpose of using this keyword is to differentiate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are similar
then jvm get ambiguity (no clarity between formal parameter and member of the class)
To differentiate between formal parameter and data member of the class, the data member of
the class must be preceded by "this".
Whenever the derived class is inherits the base class features, there is a possibility that base
class features are similar to derived class features and JVM gets an ambiguity. In order to
differentiate between base class features and derived class features must be preceded by super
keyword.
What is the difference between this. (this dot) and this() (this off).
this. can be used to differentiate variable of class and formal parameters of method or
constructor.
this() can be used to call one constructor within the another constructor without creation of
objects multiple time for the same class.
Difference between static and final keyword
static keyword always fixed the memory that means that will be located only once in the
program where as final keyword always fixed the value that means it makes variable values
constant.
Because object is not required to call static method if main() is non-static method, then jvm
create object first then call main() method due to that face the problem of extra memory
allocation.
Path variable is set for use all the tools like java, javac, javap, javah, jar, appletviewer etc.
Classpath variable is used for set the path for all classes which is used in our program so we
set classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed
rt.jar file we get all .class files.
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, Pascal are treated as non-portable language. JAVA is a
portable language.
Why use Import keyword in java ?
Import is a keyword in java language used to import the predefined properties of java API into
current working java program. Read more......
For each and every fundamental data type there exist a pre-defined class, Such predefined
class is known as wrapper class.
Public
Default
Default
protected members of class is accessible within the same class and other class of same
package and also accessible in inherited class of other package.
private members of class in not accessible any where in program these are only accessible
within the class. private are also called class level access specifier.
Write a program in java which prints the numbers from 1 to 100. But, multiples of 3 should be
replaced with "Fizz", multiples of 5 should be replaced with "Buzz" and multiples of both 3
and 5 should be replaced with "FizzBuzz"?.
Constructor
The main purpose of create a constructor is, for placing user defined values in place of default
values.
Constructor will never return any value even void, because the basic aim constructor is to
place value in the object
Why constructor definition should not be static ?
Constructor definition should not be static because constructor will be called each and every
time when object is created. If you made constructor is static then the constructor before object
creation same like main method.
Constructor will not be inherited from one class to another class because every class
constructor is created for initialize its own data members.
The purpose of default constructor is to create multiple object with respect to same class for
placing same value.
The purpose of parametrized constructor is to create multiple object with respect to same class
for placing different value of same type or different type or both.
Is constructor inherited?
The default constructor provides the default values to the objects. The java compiler creates a
default constructor only if there is no constructor in the class.
Constructor are calling from bottom to top and executing from top to bottom.
The scope of constructor is within the class so that it is not possible to achieved overriding at
constructor level.
Method
Constructor
1
Method can be any user defined name
Constructor must be class name
2
Method should have return type
It should not have any return type (even void)
3
Method should be called explicitly either with object reference or class reference
It will be called automatically whenever object is created
1
Method is not provided by compiler in any case.
The java compiler provides a default constructor if we do not have any constructor.
String Handling
The basic aim of String Handling concept is storing the string data in the main memory
(RAM), manipulating the data of the String, retrieving the part of the String etc. String
Handling provides a lot of concepts that can be performed on a string such as concatenation of
string, comparison of string, find sub string etc.
equals() method always used to comparing contents of both source and destination String. It
return true if both string are same in meaning and case otherwise it returns false.
== Operator is always used for comparing references of both source and destination objects
but not their contents.
String
StringBuffer
1
The data which enclosed within double quote (" ") is by default treated as String class.
The data which enclosed within double quote (" ") is not by default treated as StringBuffer class
2
String class object is immutable
StringBuffer class object is mutable
3
When we create an object of String class by default no additional character memory space is
created.
When we create an object of StringBuffer class by default we get 16 additional character
memory space.
• If the content is fixed and would not change frequently then we use
String.
• If content is not fixed and keep on changing but thread safety is
required then we use StringBuffer
• If content is not fixed and keep on changing and thread safety is not
required then we use StringBuilder
• Both of them are belongs to public final. so that they never participates
in inheritance that is is-A relationship is not possible but they can always participates
in As-A and Uses-A relationship.
• We can not override the method of String and StringBuffer.
All the things between StringBuffer and StringBuilder are same only difference is StringBuffer
is synchronized and StringBuilder is not synchronized. synchronized means one thread is
allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time
so it not thread safe.
StringBuffer
StringBuilder
1
It is thread safe.
It is not thread safe.
2
Its methods are synchronized and provide thread safety.
Its methods are not synchronized and unable to provide thread safety.
3
Relatively performance is low because thread need to wait until previous process is complete.
Relatively performance is high because no need to wait any thread it allows multiple thread at a
time.
1
Introduced in 1.0 version.
Introduced in 1.5 version.
What is StringTokenizer ?
It is a pre defined class in java.util package can be used to split the given string into tokens
(parts) based on delimiters (any special symbols or spaces). Read more......
Exception Handling
The process of converting system error messages into user friendly error message is known as
Exception handling.
What is Exception ?
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's Instructions.
Yes, One try block can contains another try block that is nested or inner try block can be
possible.
The ArithmeticException is thrown when integer is divided by zero or taking the remainder of
a number by zero. It is never thrown in floating-point operations.
throw
throws
1
throw is a keyword used for hitting and generating the exception which are occurring as a part of
method body
throws is a keyword which gives an indication to the specific method to place the common
exception methods as a part of try and catch block for generating user friendly error messages
2
The place of using throw keyword is always as a part of method body.
The place of using throws is a keyword is always as a part of method heading
3
When we use throw keyword as a part of method body, it is mandatory to the java programmer to
write throws keyword as a part of method heading
When we write throws keyword as a part of method heading, it is optional to the java
programmer to write throw keyword as a part of method body.
Error
Exception
1
Can be handle.
Can not be handle.
2
Example:
NoSuchMethodError
OutOfMemoryError
Example:
ClassNotFoundException
NumberFormateException
Multithreading
What is thread ?
Thread is a lightweight components and it is a flow of control. In other words a flow of control
is known as thread.
What is multithreading ?
• New State
• Ready State
• Running State
• Waiting State
• Halted or dead State
Read more.........
If the thread is in new or dead state no memory is available but sufficient memory is available
if that is in ready or running or waiting state.
Sleep() can be used to convert running state to waiting state and automatically thread convert
from waiting state to running state once the given time period is completed. Where as
suspend() can be used to convert running state thread to waiting state but it will never return
back to running state automatically.
Allowing only one thread at a time to utilized the same resource out of multiple threads is
known as thread synchronization or thread safe.
Whenever multiple threads are trying to use same resource than they may be chance to of
getting wrong output, to overcome this problem thread synchronization can be used.
How to achieve Thread Synchronization in java ?
• Synchronized block
• Synchronized method
A class has to be loaded in main memory before we start using it. Static block is executed
during class loading. This is the reason why a static block executes before the main method.
because static method is bound with class where as instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
The main purpose of using this keyword is to differentiate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are similar
then jvm get ambiguity (no clarity between formal parameter and member of the class)
To differentiate between formal parameter and data member of the class, the data member of
the class must be preceded by "this".
What is the difference between this. (this dot) and this() (this off).
this. can be used to differentiate variable of class and formal parameters of method or
constructor.
this() can be used to call one constructor within the another constructor without creation of
objects multiple time for the same class.
static keyword always fixed the memory that means that will be located only once in the
program where as final keyword always fixed the value that means it makes variable values
constant.
Because object is not required to call static method if main() is non-static method, then jvm
create object first then call main() method due to that face the problem of extra memory
allocation.
Non-Static method
Static method
1
These method never be preceded by static keyword
Example:
void fun1()
{
......
......
}
These method always preceded by static keyword
Example:
staticvoid fun2()
{
......
......
}
2
Memory is allocated multiple time whenever method is calling.
Memory is allocated only once at the time of loading.
3
It is specific to an object so that these are also known as instance method.
These are common to every object so that it is also known as member method or class method.
4
These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5
If any method wants to be execute multiple time that can be declare as non static.
If any method wants to be execute only once in the program that can be declare as static .
super() and super(..) are used for establishing the communication between base class and
derived class constructor.
this() and this(...) are used for establishing the communication between current class
constructor.
Abstract classes definitions should not be made as final because abstract classes always
participate in inheritance classes.
Difference between non-static and static variable ?
Non-Static method
Static method
1
These method never be preceded by static keyword
Example:
void fun1()
{
......
......
}
These method always preceded by static keyword
Example:
staticvoid fun2()
{
......
......
}
2
Memory is allocated multiple time whenever method is calling.
Memory is allocated only once at the time of loading.
3
It is specific to an object so that these are also known as instance method.
These are common to every object so that it is also known as member method or class method.
4
These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5
If any method wants to be execute multiple time that can be declare as non static.
If any method wants to be execute only once in the program that can be declare as static .
A new keyword is used to allocate memory at runtime, new keyword is used for create an
object of class
The main advantage of Volatile keyword is we can resolve data inconsistency problems.
The main dis-advantage of Volatile keyword is, crating and maintaining a separate copy for
every thread, increases complexity of the programming and effects performance of the system.
Synchronized Keyword is used for when we want to allowed only one thread at a time then
use Synchronized modifier. If a method or block declared as a Synchronized then at a time
only one thread is allowed to operate on the given object.
The main advantage of Synchronized keyword is we can resolve data inconsistency problem.
The main dis-advantage of Synchronized keyword is it increased the waiting time of thread
and effect performance of the system, Hence if there is no specific requirement it is never
recommended to use synchronized keyword.
StringUtils.isEmpty("") = true
StringUtils.isEmpty(null) = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("fix") = false
StringUtils.isEmpty(" fix ") = false
StringUtils.hasLength("") = false
StringUtils.hasLength(null) = false
StringUtils.hasLength(" ") = true
StringUtils.hasLength("Hello") = true
import org.apache.commons.lang.StringUtils;
//determine if String is empty using length method , also checks if string is null
System.out.println("checking if String empty using length");
System.out.println("String " + input1 + " is empty :" +isStringEmpty(input1) );
System.out.println("String " + input2 + " is empty :" +isStringEmpty(input2) );
System.out.println("String " + input3 + " is empty :" +isStringEmpty(input3) );
Output:
checking if String empty using length
String is empty :true
String null is empty :false
String abc is empty :false
That’s all on How to check if String is empty in Java. I thing Java 6 isEmpty() method is more
readable than any other option but it’s not null safe which means either write your own method
or use hasLength() from Spring Framework. By the way be careful with null String as some
programmer consider null string as empty String and even Apache
commons StringUtils.isEmpty() method return true for null String.
Property
checked exception
unchecked exception
1
Also known as
checked exceptions are also known as compileTime exceptions.
unchecked exceptions are also known as runtime exceptions.
2
Should be solved at compile or runtime?
Checked exceptions are those which need to be taken care at compile time.
Unchecked exceptions are those which need to be taken care at runtime.
3
Benefit/ Advantage
We cannot proceed until we fix compilation issues which are most likely to happen in program,
this helps us in avoiding runtime problems upto lot of extent.
Whenever runtime exception occurs execution of program is interrupted, but by handling these
kind of exception we avoid such interruptions and end up giving some meaningful message to
user.
4
Creating custom/own exception
5
Exception propagation
For propagating checked exceptions method must throw exception by using throws keyword.
unchecked exceptions are automatically propagatedin java.
6
handling checked and unchecked exception while overriding superclass method
If superclass method throws/declare checkedexception >
• overridden method of subclass can declare/thrownarrower (subclass of)
checked exception (As shown in Program), or
• overridden method of subclass cannot declare/throwbroader (superclass
of) checked exception (As shown in Program), or
• overridden method of subclass can declare/throw any unchecked
/RuntimeException (As shown in Program)
If superclass method throws/declare unchecked>
• overridden method of subclass can declare/throw any unchecked
/RuntimeException (superclass or subclass) (As shown in Program), or
• overridden method of subclass cannot declare/throwany checked
exception (As shown in Program),
Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition.
Property
Exception
Error
1
serious problem?
Exception does not indicate any serious problem.
Error indicates some serious problems that our application should not try to catch.
2
divided into
checked and unchecked
Exception are divided into checked and unchecked exceptions.
Error are not divided further into such classifications.
3
Which classes are which type of exception? either
checked orunchecked exception?
The class Exception and all its subclasses that are not also subclasses of RuntimeException
are checked exceptions.
The class RuntimeException and all its subclasses are unchecked exceptions.
Likewise,
The class Error and all its subclasses are unchecked exceptions.
Error and its subclasses are regarded as unchecked exceptions
4
Most frequently faced exception and errors
checked exceptions>
SQLException,
IOException,
ClassNotFoundException
unchecked exceptions>
NullPointerException, ArithmeticException,
VirtualMachineError, IOError, AssertionError, ThreadDeath,
OutOfMemoryError, StackOverflowError.
5
Why to catch or not to catch?
Application must catch the Exception because they does not cause any major threat to
application.
Application must not catch the Error because they does cause any major threat to application.
Example >
Let’s say errors like OutOfMemoryError and StackOverflowError occur and are caught then
JVM might not be able to free up memory for rest of application to execute, so it will be better if
application don’t catch these errors and is allowed to terminate.
throws is written in method’s definition to indicate that method can throw exception.
Above code throws NullPointerException (unChecked exception) and didn’t handled it from
where method m() was called and no compilation error was thrown.
throw
throws
1
throwkeyword is used to throw an exception explicitly.
throwskeyword is used to declare an exception.
2
throwis used inside method.
Example >
staticvoid m(){
thrownew FileNotFoundException();
}
throwsis used inmethod declaration.
Example >
staticvoid m() throws FileNotFoundException{
}
3
throwis always followed byinstanceof Exception class.
Example >
thrownew FileNotFoundException()
throwsis always followed by name of Exception class.
Example >
throwsFileNotFoundException
4
throwcan be used to throw only one exception at time.
Example >
thrownew FileNotFoundException()
throwscan be used to throw multiple exception at time.
Example >
throwsFileNotFoundException, NullPointerException
Please see these programs to understand how exception is propagated to calling method.
Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and
handling it in try-catch block from where call to method m() was made.
Program 2- Throwing Exception from m() method and then again throwing it from calling
method [ i.e. main method]
Question 10. How to create user defined checked and unchecked Exception in java?
Answer.
Creating user defined checkedexception >
class UserDefinedException extends Exception {
UserDefinedException(String s) {
super(s);
}
}
By extending java.lang.Exception, we can create checked exception.
Question 11. How to use try-catch-finally ? Can we use try,catch or finally block alone?
Answer.
We can enclose exception prone code in >
• try-catch block, or
• try-finally block, or
• try-catch-finally block.
Likewise, we cannot use catch block alone, it always follows try block.
Using only catch block will causecompilation error
catch{
//only catch block will cause compilation error
}
Likewise, we cannot use finally block alone, it always follows try block.
Using only finally block will causecompilation error
finally{
//only finally block will cause compilation error
}
try{
inti=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException");
}catch(RuntimeException re){
System.out.println("Exception handled - RuntimeException");
}catch(Exception e){
System.out.println("Exception handled - Exception");
}
}
}
/*OUTPUT
Exception handled - ArithmeticException
*/
Question 15. Now, question comes why we need not to close file when we are using Try-
with-resources?
Answer. Because FileInputStream implements java.lang.AutoCloseableinterface
(AutoCloseable interface’s close method automatically closes resources which are no longer
needed.)
Which classes can be used inside Try-with-resources?
All the classes which implements AutoCloseable interface can be used inside Try-with-
resources.
• try-catch-finally block.
try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}
finally block can can only exist if try or try-catch block is there, finally block can’t be used alone
in java.
Nested try-catch block means using try-catch block inside another try-catch block.
try{
inti=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException");
}
}
}
Question 18. Discuss which checked and unchecked exception can be thrown/declared by
subclass method while overriding superclass method in java?
Answer.
If superclass method throws/declare unchecked/RuntimeException>
• overridden method of subclass can declare/throw any unchecked
/RuntimeException (superclass or subclass), or
• overridden method of subclass cannot declare/throwany checked
exception, or
• overridden method of subclass can declare/throwsame exception, or
• overridden method of subclass may not declare/throw any exception.
For programs please refer >Throw/declare checked and unchecked exception while
overriding superclass method in java
Question 19. What will happen when catch and finally block both return value, also when
try and finally both return value?
Answer.
When catch and finally block both return value, method will ultimately return value
returned by finally block irrespective of value returned by catch block.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
publicclass ExceptionTest {
publicstaticvoid main(String[] args) {
System.out.println("method return -> "+m());
}
}
}
/*OUTPUT
method return -> finally
*/
In above program, i=10/0 will throw ArithmeticException and enter catch block to return
"catch", but ultimately control will enter finally block to return "finally".
Likewise, when try and finally block both return value, method will ultimately return value
returned by finally block irrespective of value returned by try block. For program please refer.
Question 22. Why shouldn’t you use Exception for catching all exceptions in java?
Answer. Catching Exception rather than handling specific exception can be vulnerable to our
application. Multiple catch blocks must be used to catch specific exceptions, because handling
specific exception gives developer the liberty of taking appropriate action and develop robust
application.
Question 23. What is Difference between multiple catch block and multi catch syntax?
Answer.
try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}
with the help of multi catch syntax we can catch IOException and SQLException in one catch
block using multi catch syntax like this >
4
When multiple catch blocks are used , first catch block could be subclass of Exception class
handled in following catch blocks like this >
IOException is subclass of Exception.
If Multi catch syntax is used to catch subclass and its superclass than compilation error will be
thrown.
IOException and Exception in multi catch syntax will cause compilation error “The exception
IOException is already caught by the alternative Exception”.
Solution >
We must use only Exception to catch its subclass like this >
5
Does not provide such features.
Features of multi catch syntax >
• Has improved way of catching multiple exceptions.
• This syntax does not looks clumsy.
• Reduces developer efforts of writing multiple catch blocks.
• Allows us to catch more than one exception in one catch block.
• Helps in automatic resource management.
For more read : Difference between multiple catch block and multi catch syntax
Program >
import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
publicclass ExceptionTest {
• Either log the exception or bubble it, but don't do both. Logging an
exception often indicates that the exception stack has been completely unwound,
indicating that no further bubbling of the exception has occurred. Hence, it is not
recommended to do both at the same time, as it often leads to a frustrating experience in
debugging.
• Application should not try to catch Error - Because, in most of cases
recovery from an Error is almost impossible. So, application must be allowed to
terminate.
Example>
Let’s say errors like OutOfMemoryError and StackOverflowError occur and are caught then
JVM might not be able to free up memory for rest of application to execute, so it will be better if
application don’t catch these errors and is allowed to terminate.
Read : Complete list of Exception handling best practices and guidelines for using
exceptions in java
final
finally
finalize
1
final can be applied to variable, method and class in java.
finally is a block.
finalize is a method.
2
Final memberVariable of class must be initialized at time of declaration, once initialized final
memberVariable cannot be assigned a new value.
Final variables are called constants in java.
class FinalTest {
finalintx=1; //memberVariable/instanceVariable
}
If constructor is defined then final memberVariable can be initialized in constructor but once
initialized cannot be assigned a new value.
class FinalTest {
finalintx; //memberVariable/instanceVariable
FinalTest() {
x = 1; //final memberVariable can be initialized in constructor.
}
}
Final local variable can be left uninitialized at time of declaration and can be initialized later,
but once initialized cannot be assigned a new value.
class FinalTest {
void method(){
finalint x; //uninitialized at time of declaration
x=1;
}
}
Final static variable of class must be initialized at time of declaration or can be initialized in
static block, once initialized final static variable cannot be assigned a new value.
If static block is defined then final static variable can be initialized in static block, once
initialized final static variable cannot be assigned a new value.
class FinalTest {
finalstaticintx; //static variable
static{ //static block
x=1;
}
}
Runtime polymorphism is not applicable on final methods because they cannot be inherited.
try-catch-finally block.
try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}
finally block can can only exist if try or try-catch block is there, finally block can’t be used alone
in java.
@Override
protectedvoid finalize() throws Throwable {
try {
System.out.println("in
finalize() method, "
+
"doing cleanup activity");
3
-
finally block can only exist if try or try-catch block is there, finally block can’t be used alone in
java.
We can force early garbage collection in java by using following methods >
System.gc(); Runtime.getRuntime().gc();
System.runFinalization(); Runtime.getRuntime().runFinalization();
4
-
finally is always executed irrespective of exception thrown.
If any uncaught exception is thrown inside finalize method -
exception is ignored,
thread is terminated and
object is discarded.
Note : Any exception thrown by the finalize method causes the finalization of this object to be
halted, but is otherwise ignored.
5
-
Currently executing thread calls finally method.
JVM does not guarantee which daemonthread will invoke the finalize method for an object.
6
final is a keyword in java.
finally Is a keyword in java.
finalize is not a keyword in java.
Also Read : Top and most important Interview Questions and answers in Java
Thread are subdivision of Process. One or more Threads runs in the context of process. Threads
can execute any part of process. And same part of process can be executed by multiple Threads.
Processes have their own copy of the data segment of the parent process while Threads have
direct access to the data segment of its process.
Processes have their own address while Threads share the address space of the process that
created it.
Process creation needs whole lot of stuff to be done, we might need to copy whole parent
process, but Thread can be easily created.
Processes can easily communicate with child processes but interprocess communication is
difficult. While, Threads can easily communicate with other threads of the same process
using wait() and notify() methods.
In process all threads share system resource like heap Memory etc. while Thread has its own
stack.
Any change made to process does not affect child processes, but any change made to thread can
affect the behavior of the other threads of the process.
Example to see where threads on are created on different processes and same process.
Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution
is an individual process that has its own call stack. Thread are lightweight process in java.
2) And then create Thread object by calling constructor and passing reference of Runnable
interface i.e. runnable object :
Question 4 . Does Thread implements their own Stack, if yes how? (Important)
Answer. Yes, Threads have their own stack. This is very interesting question, where interviewer
tends to check your basic knowledge about how threads internally maintains their own stacks.
I’ll be explaining you the concept by diagram.
Question 5. We should implement Runnable interface or extend Thread class. What are
differences between implementing Runnable and extending Thread?
Answer. Well the answer is you must extend Thread only when you are looking to modify
run() and other methods as well. If you are simply looking to modify only the run() method
implementing Runnable is the best option (Runnable interface has only one abstract method
i.e. run() ).
To achieve we are going to create 2 threads on same Runnable Object, create for loop in run()
method and start both threads. There is no surety that which threads will complete first, both
threads will enter anonymously in for loop.
Question 7 . When threads are not lightweight process in java?
Answer. Threads are lightweight process only if threads of same process are executing
concurrently. But if threads of different processes are executing concurrently then threads
are heavy weight process.
Question 8. How can you ensure all threads that started from main must end in order in
which they started and also main should end in last? (Important)
Answer. Interviewers tend to know interviewees knowledge about Thread methods. So this is
time to prove your point by answering correctly. We can use join() methodto ensure all threads
that started from main must end in order in which they started and also main should end in last.In
other words waits for this thread to die. Calling join() method internally calls join(0);
DETAILED DESCRIPTION : Join() method - ensure all threads that started from main must
end in order in which they started and also main should end in last. Types of join() method with
programs- 10 salient features of join.
Question 9.What is difference between starting thread with run() and start() method?
(Important)
Answer. This is quite interesting question, it might confuse you a bit and at time may make you
think is there really any difference between starting thread with run() and start() method.
When you call start() method, main thread internally calls run() method to start newly
created Thread, so run() method is ultimately called by newly created thread.
When you call run() method main thread rather than starting run() method with newly thread it
start run() method by itself.
If a field is declared volatile, in that case the Java memory model ensures that all threads
see a consistent value for the variable.
Question 11. Differences between synchronized and volatile keyword in Java? (Important)
Answer.Its very important question from interview perspective.
Synchronized block:
void method2(){
synchronized (this) {
//code inside synchronized block.
}
}
• Volatile variables are not cached, but variables used inside synchronized
method or block are cached.
Question 13. What is race condition in multithreading and how can we solve it?
(Important)
Answer. This is very important question, this forms the core of multi threading, you should be
able to explain about race condition in detail.
When more than one thread try to access same resource without synchronization causes race
condition.
So we can solve race condition by using either synchronized block or synchronized method.
When no two threads can access same resource at a time phenomenon is also called as mutual
exclusion.
Question 15. Why wait(), notify() and notifyAll() are in Object class and not in Thread
class? (Important)
Answer.
• Every Object has a monitor, acquiring that monitors allow thread to hold
lock on object. But Thread class does not have any monitors.
• Wait(), notify() and notifyAll() method being in Object class allows all the
threads created on that object to communicate with other. [As multiple threads may
exist on same object].
• As multiple threads exists on same object. Only one thread can hold
object monitor at a time. As a result thread can notify other threads of same object that
lock is available now. But, thread having these methods does not make any sense because
multiple threads exists on object its not other way around (i.e. multiple objects exists on
thread).
• Now let’s discuss one hypothetical scenario, what will happen if Thread
class contains wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods means Thread class also must have their
monitor.
Every thread having their monitor will create few problems -
>Thread communication problem.
>Synchronization on object won’t be possible- Because object has monitor, one object can
have multiple threads and thread hold lock on object by holding object monitor. But if each
thread will have monitor, we won’t have any way of achieving synchronization.
>Inconsistency in state of object (because synchronization won't be possible).
Question 16. Is it important to acquire object lock before calling wait(), notify() and
notifyAll()?
Answer.Yes, it’s mandatory to acquire object lock before calling these methods on object. As
discussed above wait(), notify() and notifyAll() methods are always called from
Synchronized block only, and as soon as thread enters synchronized block it acquires object
lock (by holding object monitor). If we call these methods without acquiring object lock i.e. from
outside synchronize block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws compile time exception i.e.
InterruptedException.
Question 17. How can you solve consumer producer problem by using wait() and notify()
method? (Important)
Answer. Here come the time to answer very very important question from interview
perspective. Interviewers tends to check how sound you are in threads inter communication.
Because for solving this problem we got to use synchronization blocks, wait() and notify()
method very cautiously. If you misplace synchronization block or any of the method that
may cause your program to go horribly wrong. So, before going into this question first i’ll
recommend you to understand how to use synchronized blocks, wait() and notify() methods.
consumerThread.start();
consumerThread will enter run method and call consume() method. There it will check for
sharedQueue’s size.
-if size is equal to 0 that means producer hasn’t produced any product, wait for producer to
produce by using below piece of code-
synchronized (sharedQueue) {
while (sharedQueue.size() == 0) {
sharedQueue.wait();
}
}
-if size is greater than 0, consumer will start consuming by using below piece of code.
synchronized (sharedQueue) {
Thread.sleep((long)(Math.random() * 2000));
System.out.println("consumed : "+ sharedQueue.remove(0));
sharedQueue.notify();
}
producerThread.start();
producerThread will enter run method and call produce() method. There it will check for
sharedQueue’s size.
-if size is equal to 2 (i.e. maximum number of products which sharedQueue can hold at a time),
wait for consumer to consume by using below piece of code-
synchronized (sharedQueue) {
while (sharedQueue.size() == maxSize) { //maxsize is 2
sharedQueue.wait();
}
}
-if size is less than 2, producer will start producing by using below piece of code.
synchronized (sharedQueue) {
System.out.println("Produced : " + i);
sharedQueue.add(i);
Thread.sleep((long)(Math.random() * 1000));
sharedQueue.notify();
}
Another illustration with program : How to solve Consumer Producer problem by using wait()
and notify() methods, where consumer can consume only when production is over.
Question 18. How to solve Consumer Producer problem without using wait() and notify()
methods, where consumer can consume only when production is over.?
Answer. In this problem, producer will allow consumer to consume only when 10 products have
been produced (i.e. when production is over).
We will approach by keeping one boolean variable productionInProcess and initially setting it
to true, and later when production will be over we will set it to false.
Question 19. How can you solve consumer producer pattern by using BlockingQueue?
(Important)
Answer. Now it’s time to gear up to face question which is most probably going to be followed
up by previous question i.e. after how to solve consumer producer problem using wait() and
notify() method. Generally you might wonder why interviewer's are so much interested in asking
about solving consumer producer problem using BlockingQueue, answer is they want to know
how strong knowledge you have about java concurrent Api’s, this Api use consumer producer
pattern in very optimized manner, BlockingQueue is designed is such a manner that it offer us
the best performance.
BlockingQueue is a interface and we will use its implementation class
LinkedBlockingQueue.
publicvoid run() {
synchronized (String.class) {
Thread.sleep(100);
synchronized (Object.class) {
}
}
}
publicvoid run() {
synchronized (Object.class) {
Thread.sleep(100);
synchronized (String.class) {
}
}
}
Here comes the important part, how above formed deadlock could be solved :
Thread-1 acquires lock on String.class and then calls sleep() method which gives Thread-2 the
chance to execute immediately after Thread-1 has acquired lock on String.class and Thread-2
tries to acquire lock on String.class but lock is holded by Thread-1. Meanwhile, Thread-1
completes successfully. As Thread-1 has completed successfully it releases lock on String.class,
Thread-2 can now acquire lock on String.class and complete successfully without any deadlock
formation.
Conclusion: No deadlock is formed.
Code called by Thread-1
publicvoid run() {
synchronized (String.class) {
Thread.sleep(100);
synchronized (Object.class) {
}
}
}
publicvoid run() {
synchronized (String.class) {
Thread.sleep(100);
synchronized (Object.class) {
}
}
}
• Use join() method: If possible try touse join() method, although it may
refrain us from taking full advantage of multithreading environment because threads will
start and end sequentially, but it can be handy in avoiding deadlocks.
Question 21. Have you ever generated thread dumps or analyzed Thread Dumps?
(Important)
Answer. Answering this questions will show your in depth knowledge of Threads. Every
experienced must know how to generate Thread Dumps.
VisualVM is most popular way to generate Thread Dump and is most widely used by
developers. It’s important to understand usage of VisualVM for in depth knowledge of
VisualVM. I’ll recommend every developer must understand this topic to become master in multi
threading.
It helps us in analyzing threads performance, thread states, CPU consumed by threads, garbage
collection and much more. For detailed information see Generating and analyzing Thread
Dumps using VisualVM - step by step detail to setup VisualVM with screenshots
jstack is very easy way to generate Thread dump and is widely used by developers. I’ll
recommend every developer must understand this topic to become master in multi threading. For
creating Thread dumps we need not to download any jar or any extra software. For detailed
information see Generating and analyzing Thread Dumps using JSATCK - step by step
detail to setup JSTACK with screenshots.
Question 22. What is life cycle of Thread, explain thread states? (Important)
Answer. Thread states/ Thread life cycle is very basic question, before going deep into
concepts we must understand Thread life cycle.
New : When instance of thread is created using new operator it is in new state, but the start()
method has not been invoked on the thread yet, thread is not eligible to run yet.
Running : Thread scheduler selects thread to go fromrunnable to running state. In running state
Thread starts executing by entering run() method.
You may like to have in depth knowledge of Thread states/ Thread life cycle in java &
explanation of thread methods which method puts thread from which state to which state.
Question 23. Are you aware of preemptive scheduling and time slicing?
Answer. In preemptive scheduling, the highest priority thread executes until it enters into the
waiting or dead state.
In time slicing, a thread executes for a certain predefined time and then enters runnable
pool. Than thread can enter running state when selected by thread scheduler.
• Daemon threads are service oriented threads, they serves all other
threads.
• These threads are created before user threads are created and die after
all other user threads dies.
• You may like to see how daemon threads work, for that you can use
VisualVM or jStack. I have provided Thread dumps over there which shows daemon
threads which were intermittently running in background.
Some of the daemon threads which intermittently run in background are >
"RMI TCP Connection(3)-10.175.2.71" daemon
"RMI TCP Connection(idle)" daemon
"RMI Scheduler(0)" daemon
"C2 CompilerThread1" daemon
"GC task thread#0 (ParallelGC)"
Suspend() method puts thread from running to waiting state. And thread can go from
waiting to runnable state only when resume() method is called on thread. It is deprecated
method.
Resume() method is only used with suspend() method that’s why it’s also deprecated method.
Question 27. As stop() method is deprecated, How can we terminate or stop infinitely
running thread in java? (Important)
Answer. This is very interesting question where interviewees thread basics basic will be tested.
Interviewers tend to know user’s knowledge about main thread’s and thread invoked by main
thread.
We will try to address the problem by creating new thread which will run infinitely until certain
condition is satisfied and will be called by main Thread.
Question 28. what is significance of yield() method, what state does it put thread in?
yield() is a native method it’s implementation in java 6 has been changed as compared to its
implementation java 5. As method is native it’s implementation is provided by JVM.
In java 5, yield() method internally used to call sleep() method giving all the other threads of
same or higher priority to execute before yielded thread by leaving allocated CPU for time gap of
15 millisec.
But java 6, calling yield() method gives a hint to the thread scheduler that the current
thread is willing to yield its current use of a processor. The thread scheduler is free to
ignore this hint. So, sometimes even after using yield() method, you may not notice any
difference in output.
Question 29.What is significance of sleep() method in detail, what state does it put thread in
?
• Waiting time : yield() method stops thread for unpredictable time, that
depends on thread scheduler. But sleep() method have got few options.
• sleep(long millis) - Causes the currently executing thread to sleep
for the specified number of milliseconds
• sleep(long millis, int nanos) - Causes the currently executing
thread to sleep for the specified number of milliseconds plus the specified number
of nanoseconds.
>yield() and sleep() method can be called from outside synchronized block.
> yield() and sleep() method are called on Threads not objects.
Question 32. Mention some guidelines to write thread safe code, most important point we
must take care of in multithreading programs?
Answer. In multithreading environment it’s important very important to write thread safe code,
thread unsafe code can cause a major threat to your application. I have posted many articles
regarding thread safety. So overall this will be revision of what we have learned so far i.e.
writing thread safe healthy code and avoiding any kind of deadlocks.
• Even static variables are not thread safe, they are used in static methods
and if static methods are not synchronized then thread on same or different object can
enter method concurrently. Multiple threads may exist on same or different objects of
class but only one thread can enter static synchronized method at a time, we must
consider making static methods as synchronized.
• Final variables are thread safe because once assigned some reference of
object they cannot point to reference of other object.
publicclass MyClass {
finalinti=0;
void method(){
i=0; //compilation error, i cannot point to new value.
}
}
publicclass MyClass {
void method(){
inti=0; //Local variable, is thread safe.
}
}
• Using thread safe collections : Rather than using ArrayList we must Vector
and in place of using HashMap we must use ConcurrentHashMap or HashTable.
• Rather than StringBuffer try using immutable classes such as String. Any
change to String produces new String.
Question 33. How thread can enter waiting, sleeping and blocked state and how can they go
to runnable state ?
Answer. This is very prominently asked question in interview which will test your knowledge
about thread states. And it’s very important for developers to have in depth knowledge of this
thread state transition. I will try to explain this thread state transition by framing few sub
questions. I hope reading sub questions will be quite interesting.
Suspend() method can be used to put thread in waiting state and resume() method is the only
way which could put thread in runnable state.
Thread also may go from running to waiting state if it is waiting for some I/O operation to take
place. Once input is available thread may return to running state.
>When threads are in running state, yield()method can make thread to go in Runnable state.
Question 34. Difference between notify() and notifyAll() methods, can you write a code to
prove your point?
Answer. Goodness. Theoretically you must have heard or you must be aware of differences
between notify() and notifyAll().But have you created program to achieve it? If not let’s do it.
First, I will like give you a brief description of what notify() and notifyAll() methods do.
notify()- 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 random and occurs at
the discretion of the implementation. A thread waits on an object's monitor by calling one of the
wait methods.
The awakened threads will not be able to proceed until the current thread relinquishes the
lock on this object.
Public final native void notify();
notifyAll()- Wakes up all threads that are waiting on this object's monitor. A thread waits on an
object's monitor by calling one of the wait methods.
The awakened threads will not be able to proceed until the current thread relinquishes the
lock on this object.
publicfinalnativevoidnotifyAll();
Question 35. Does thread leaves object lock when sleep() method is called?
Answer. When sleep() method is called Thread does not leaves object lock and goes from
running to waiting state. Thread waits for sleep time to over and once sleep time is up it goes
from waiting to runnable state.
Question 36. Does thread leaves object lock when wait() method is called?
Answer. When wait() method is called Thread leaves the object lock and goes from running to
waiting state. Thread waits for other threads on same object to call notify() or notifyAll() and
once any of notify() or notifyAll() is called it goes from waiting to runnable state and again
acquires object lock.
When we call start() method on thread, it internally calls run() method with newly created
thread. So, if we don’t override run() method newly created thread won’t be called and
nothing will happen.
class MyThread extends Thread {
//don't override run() method
}
publicclass DontOverrideRun {
publicstaticvoid main(String[] args) {
System.out.println("main has started.");
MyThread thread1=new MyThread();
thread1.start();
System.out.println("main has ended.");
}
}
/*OUTPUT
main has started.
main has ended.
*/
As we saw in output, we didn’t override run() method that’s why on calling start() method
nothing happened.
When we call start() method on thread, it internally calls run() method with newly created
thread. So, if we override start() method, run() method will not be called until we write code
for calling run() method.
}
publicclass OverrideStartMethod {
publicstaticvoid main(String[] args) {
System.out.println("main has started.");
Question 39. Can we acquire lock on class? What are ways in which you can acquire lock
on class?
Answer. Yes, we can acquire lock on class’s class object in 2 ways to acquire lock on class.
Thread can acquire lock on class’s class object by-
• Entering synchronized block or
Let’s say there is one class MyClass. Now we can create synchronization block, and
parameter passed with synchronization tells which class has to be synchronized. In below code,
we have synchronized MyClass
synchronized (MyClass.class) {
//thread has acquired lock on MyClass’s class object.
}
As soon as thread entered Synchronization method, thread acquired lock on class’s class object.
Thread will leave lock when it exits static synchronized method.
Question 40. Difference between object lock and class lock?
Answer. It is very important question from multithreading point of view. We must understand
difference between object lock and class lock to answer interview, ocjp answers correctly.
Object lock
Class lock
Thread can acquire object lock by-
• Entering synchronized block or
• by entering synchronized methods.
Thread can acquire lock on class’s class object by-
• Entering synchronized block or
• by entering static synchronized methods.
Multiple threads may exist on same object but only one thread of that object can enter
synchronized method at a time.
Example- Let’s say there is one class MyClassand we have created it’s object and reference to
that object is myClass. Now we can create synchronization block, and parameter passed with
synchronization tells which object has to be synchronized. In below code, we have synchronized
object reference by myClass.
MyClass myClass=newMyclass();
synchronized (myClass) {
}
As soon thread entered Synchronization block, thread acquired object lock on object referenced
by myClass (by acquiring object’s monitor.)
Thread will leave lock when it exits synchronized block.
First let’s acquire lock on class’s class object by entering synchronized block.
Example- Let’s say there is one class MyClass. Now we can create synchronization block, and
parameter passed with synchronization tells which class has to be synchronized. In below code,
we have synchronized MyClass
synchronized (MyClass.class) {
}
As soon as thread entered Synchronization block, thread acquired MyClass’s class object. Thread
will leave lock when it exits synchronized block.
publicsynchronizedvoid method1() {
}
Question 41. Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-
1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?
Answer.No, here when Thread-1 is in synchronized method1() it must be holding lock on
object’s monitor and will release lock on object’s monitor only when it exits synchronized
method1(). So, Thread-2 will have to wait for Thread-1 to release lock on object’s monitor so
that it could enter synchronized method2().
Likewise, Thread-2 even cannot enter synchronized method1() which is being executed by
Thread-1. Thread-2 will have to wait for Thread-1 to release lock on object’s monitor so that it
could enter synchronized method1(). Now, let’s see a program to prove our point.
Question 42. Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-
1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at
same time?
Answer.No, here when Thread-1 is in static synchronized method1() it must be holding lock
on class class’s object and will release lock on class’s classobject only when it exits static
synchronized method1(). So, Thread-2 will have to wait for Thread-1 to release lock on class’s
classobject so that it could enter static synchronized method2().
Likewise, Thread-2 even cannot enter static synchronized method1() which is being executed
by Thread-1. Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so
that it could enter static synchronized method1(). Now, let’s see a program to prove our point.
Question 43. Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-
1 is in synchronized method1(), can Thread-2 enter static synchronized method2() at same
time?
Answer.Yes, here when Thread-1 is in synchronized method1() it must be holding lock on
object’s monitor and Thread-2 can enter static synchronized method2() by acquiring lock on
class’s class object. Now, let’s see a program to prove our point.
Question 44. Suppose you have thread and it is in synchronized method and now can thread
enter other synchronized method from that method?
Answer.Yes, here when thread is in synchronized method it must be holding lock on object’s
monitor and using that lock thread can enter other synchronized method. Now, let’s see a
program to prove our point.
Question 45. Suppose you have thread and it is in static synchronized method and now can
thread enter other static synchronized method from that method?
Answer. Yes, here when thread is in static synchronized method it must be holding lock on
class’s class object and using that lock thread can enter other static synchronized method.
Now, let’s see a program to prove our point.
Question 46. Suppose you have thread and it is in static synchronized method and now can
thread enter other non static synchronized method from that method?
Answer.Yes, here when thread is in static synchronized method it must be holding lock on
class’s class object and when it enters synchronized method it will hold lock on object’s
monitor as well.
So, now thread holds 2 locks (it’s also called nested synchronization)-
>first one on class’s class object.
>second one on object’s monitor (This lock will be released when thread exits non static
method).Now, let’s see a program to prove our point.
Question 47. Suppose you have thread and it is in synchronized method and now can thread
enter other static synchronized method from that method?
Answer.Yes, here when thread is in synchronized method it must be holding lock on object’s
monitor and when it enters static synchronized method it will hold lock on class’s class object as
well.
So, now thread holds 2 locks (it’s also called nested synchronization)-
>first one on object’s monitor.
>second one on class’s class object.(This lock will be released when thread exits static
method).Now, let’s see a program to prove our point.
Question 48. Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2).
Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same
time?
Answer.Yes, here when Thread-1 is in synchronized method1() it must be holding lock on
object1’s monitor. Thread-2 will acquire lock on object2’s monitor and enter synchronized
method2().
Likewise, Thread-2 even enter synchronized method1() as well which is being executed by
Thread-1 (because threads are created on different objects). Now, let’s see a program to prove
our point.
Question 49. Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2).
Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized
method2() at same time?
Answer.No, it might confuse you a bit that threads are created on different objects. But, not to
forgot that multiple objects may exist but there is always one class’s class object lock
available.
Here, when Thread-1 is in static synchronized method1() it must be holding lock on class
class’s object and will release lock on class’s classobject only when it exits static synchronized
method1(). So, Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so
that it could enter static synchronized method2().
Likewise, Thread-2 even cannot enter static synchronized method1() which is being executed
by Thread-1. Thread-2 will have to wait for Thread-1 to release lock on class’s classobject so
that it could enter static synchronized method1(). Now, let’s see a program to prove our point.
Question 50. Difference between wait() and wait(long timeout), What are thread states
when these method are called?
Answer.
wait()
wait(long timeout)
When wait() method is called on object, it causes causes the current thread to wait until another
thread invokes the notify() or notifyAll() method for this object.
wait(long timeout) - Causes the current thread to wait until either another thread invokes the
notify() or notifyAll() methods for this object, or a specified timeout time has elapsed.
When wait() is called on object - Thread enters from running to waiting state.
It waits for some other thread to call notify so that it could enter runnable state.
When wait(1000) is called on object - Thread enters from running to waiting state. Than even
if notify() or notifyAll() is not called after timeout time has elapsed thread will go from
waiting to runnable state.
Question 51. How can you implement your own Thread Pool in java?
Answer.
What is ThreadPool?
ThreadPool is a pool of threads which reuses a fixed number of threads to execute tasks.
At any point, at most nThreads threads will be active processing tasks. If additional tasks
are submitted when all threads are active, they will wait in the queue until a thread is
available.
ThreadPool implementation internally uses LinkedBlockingQueue for adding and removing
tasks.
In this post i will be using LinkedBlockingQueue provide by java Api, you can refer this post for
implementing ThreadPool using custom LinkedBlockingQueue.
Need/Advantage of ThreadPool?
Instead of creating new thread every time for executing tasks, we can create ThreadPool
which reuses a fixed number of threads for executing tasks.
As threads are reused, performance of our application improves drastically.
Then, threads will enter run() method of ThreadPoolsThread class and will call take() method
on taskQueue.
• If tasks are available thread will execute task by entering run() method of
task (As tasks executed always implements Runnable).
publicvoid run() {
...
while (true) {
...
Runnable runnable = taskQueue.take();
runnable.run();
...
}
...
}
Once tasks are available all waiting threads are notified that task is available.
What is ThreadLocal ?
ThreadLocal is a class which provides thread-local variables. Every thread has its own
ThreadLocal value that makes ThreadLocal value threadsafe as well.
Application of ThreadLocal?
• ThreadLocal are used by many web frameworks for maintaining some
context (may be session or request) related value.
• In any single threaded application, same thread is assigned for
every request made to same action, so ThreadLocal values will be available in
next request as well.
• In multi threaded application, different thread is assigned for
every request made to same action, so ThreadLocal values will be different for
every request.
• When threads have started at different time they might like to store time at
which they have started. So, thread’s start time can be stored in ThreadLocal.
We will create instance of ThreadLocal. ThreadLocal is a generic class, i will be using String to
demonstrate threadLocal.
All threads will see same instance of ThreadLocal, but a thread will be able to see value
which was set by it only.
Performance point of view - Busy spin is very bad from performance point of view, because one
thread keeps on looping continuously ( and consumes CPU) waiting for another thread to signal.
Solution to busy spin -
We must use sleep() or wait() and notify() method. Using wait() is better option.
Why using wait() and notify() is much better option to solve busy spin?
Because in case when we use sleep() method, thread will wake up again and again after specified
sleep time until boolean variable is true. But, in case of wait() thread will wake up only when
when notified by calling notify() or notifyAll(), hence end up consuming CPU in best possible
manner.
Question 55. Can you find whether thread holds lock on object or not?
Answer. holdsLock(object) method can be used to find out whether current thread holds the
lock on monitor of specified object.
holdsLock(object) method returns true if the current thread holds the lock on monitor of
specified object.
• Low priority threads gets less CPU (time for execution) as compared to
high priority threads. Lower priority thread may starve away waiting to get enough
CPU to perform calculations.
• In deadlock two threads waits for each other to release lock holded by
them on resources. There both Threads starves away to get CPU.
Once JVM’s shutdown has begunnew shutdown hook cannot be registered neither previously-
registered hook can be de-registered. Any attempt made to do any of these operations causes
an IllegalStateException.
For more detail with program read : Threads addShutdownHook method in java
Question 58. How you can handle uncaught runtime exception generated in run method?
Answer. We can use setDefaultUncaughtExceptionHandler method which can handle uncaught
unchecked(runtime) exception generated in run() method.
Question 59. What is ThreadGroup in java, What is default priority of newly created
threadGroup, mention some important ThreadGroup methods ?
Answer. When program starts JVM creates a ThreadGroup named main. Unless specified,
all newly created threads become members of the main thread group.
• getName()
• name of ThreadGroup.
• activeGroupCount()
• count of active groups in ThreadGroup.
• activeCount()
• count of active threads in ThreadGroup.
• list()
• list() method has prints ThreadGroups information
• getMaxPriority()
• Method returns the maximum priority of ThreadGroup.
• setMaxPriority(int pri)
• Sets the maximum priority of ThreadGroup.
Thread class provides variables of final static int type for setting thread priority.
Thread with MAX_PRIORITY is likely to get more CPU as compared to low priority threads.
But occasionally low priority thread might get more CPU. Because thread scheduler
schedules thread on discretion of implementation and thread behaviour is totally unpredictable.
Thread with MIN_PRIORITY is likely to get less CPU as compared to high priority threads.
But occasionally high priority thread might less CPU. Because thread scheduler schedules
thread on discretion of implementation and thread behaviour is totally unpredictable.
The JDK does not provide any classes which directly implements this interface, but it provides
classes which are implementations of more specific subinterfaces like Set and List in java.
COLLECTION - Top 100 important interview OUTPUT questions and answers in java,
Set-3 > Q75- Q100
Collection interview Question 2. Which interfaces and classes are most frequently used in
Collection framework in java?
Answer. This collection framework interview question will test your practical knowledge.
Freshers may get away by answering few interface and classes but experienced developers must
answer this question in detail.
It’s important to note Map interface is a member of the Java Collections Framework, but it does
not implement Collection interface in java.
Collection interview Question 4. What are differences between ArrayList and LinkedList
in java?
Answer. This is very important collection framework interview question in java.
Property
java.util.ArrayList
java.util.LinkedList
1
Structure
java.util.ArrayList is index based structure in java.
2
Resizable
ArrayList is Resizable-array in java.
New node is created for storing new element in LinkedList in java.
3
Initial capacity
java.util.ArrayList is created with initial capacity of 10 in java.
For storing every element node is created in LinkedList, so linkedList’s initial capacity is 0 in
java.
4
Ensuring Capacity/ resizing.
ArrayList is created with initial capacity of 10.
ArrayList’s size is increased by 50% i.e. after resizing it’s size become 15 in java.
For storing every element node is created, so linkedList’s initial capacity is 0, it’s size grow with
addition of each and every element in java.
5
RandomAccess interface
ArrayList implements RandomAccess(Marker interface) to indicate that they support fast
random access (i.e. index based access) in java.
LinkedList does not implement RandomAccess interface in java.
6
AbstractList and AbstractSequentialList
ArrayList extends AbstractList (abstract class) which provides implementation to List interface
to minimize the effort required to implement this interface backed by RandomAccess interface.
LinkedList extends AbstractSequentialList (abstract class), AbstractSequentialList extends
AbstractList.
In LinkedList, data is accessed sequentially, so for obtaining data at specific index, iteration is
done on nodes sequentially in java.
7
How get(index) method works?
(Though difference has been discussed briefly in above 2 points but in this in point we will figure
difference in detail.)
Get method of ArrayList directly gets element on specified index. Hence, offering O(1)
complexity in java.
Get method of LinkedList iterates on nodes sequentially to get element on specified index.
Hence, offering O(n) complexity in java.
8
When to use
Use ArrayList when get operations is more frequent than add and remove operations in
java.
Use LinkedList when add and remove operations are more frequent than get operations in
java.
For more detail like complexity comparison of method please read : ArrayList vs LinkedList in
java
Collection interview Question 5. What are differences between ArrayList and Vector in
java?
Answer. Another very important collection framework interview question to differentiate
between ArrayList and Vector in java.
Property
java.util.ArrayList
java.util.Vector
1
synchronization
java.util.ArrayList is not synchronized (because 2 threads on same ArrayList object can access
it at same time).
Enumeration is fail-safe, means any modification made to Vector during iteration using
Enumeration don’t throw any exception in java.
4
Introduced in which java version
ArrayList was introduced in second version of java i.e. JDK 2.0
Vector was introduced in first version of java i.e. JDK 1.0
But it was refactored in java 2 i.e. JDK 1.2 to implement the List interface, hence making it a
member of member of theJava Collections Framework.
5
Ensuring Capacity/ resizing.
ArrayList is created with initial capacity of 10.
When its full size is increased by 50% i.e. after resizing it’s size become 15 in java.
Vector is created with initial capacity of 10.
Vector’s size is increased by 100% i.e. after resizing it’s size become 20 in java.
6
Custom implementation
Read : ArrayList custom implementation
Read :
Vector custom implementation
For more detail like complexity comparison of method please read: ArrayList vs Vector-
Similarity and Differences in java
Collection interview Question 6. What are differences between List and Set interface in
java?
Answer. Another very very important collection framework interview question to differentiate
between List and Set in java.
Property
java.util.List
java.util.Set
1
Insertion order
java.util.List is ordered collection it maintain insertion order in java.
Most of the java.util.Set implementation does not maintain insertion order.
Get method directly gets element on specified index. Hence, offering O(1) complexity.
Set implementations does not provide any such get method to get element on specified index in
java.
5
Implementing classes
ArrayList, LinkedList, Vector, CopyOnWriteArrayList classes implements List interface in
java.
HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet,
EnumSet classes implements Set interface in java.
6
listIterator
listIterator method returns listIterator to iterate over elements in List in java.
For more detail read : List vs Set - Similarity and Differences in java
Collection interview Question 7. What are differences between Iterator and ListIterator? in
java
Answer. This collection framework interview question is tests your knowledge of iterating over
different collection framework classes in java.
java.util.ListIterator
java.util.Iterator
1
hasPrevious() method returns true if this listIterator has more elements when traversing the list
in the reverse direction.
No such method in java.util.Iterator.
2
previous() returns previous element in iteration (traversing in backward direction).
if the iteration has no previous elements than NoSuchElementException is thrown.
No such method in java.util.Iterator.
3
nextIndex() method returns the index of the element that would be returned by a subsequent call
to next() method. If listIterator is at the end of the list than method returns size of list.
No such method in java.util.Iterator.
4
previousIndex() method returns the index of the element that would be returned by a
subsequent call to previous() method. If listIterator is at the start of the list than method returns -
1.
No such method in java.util.Iterator.
5
add(E element)
Method inserts the specified element into the list.
The element is inserted immediately before the element that would be returned by next (So,
subsequent call to next would be unaffected), if any, and after the element that would be returned
by previous (So,subsequent call to previous would return the newelement), if any.
If the list does not contain any element than new element will be the sole element in the list.
No such method in java.util.Iterator.
6
set(E element)
Method replaces the last element returned by next() or previous() method with the specified
element. This call can be made only if neither remove nor add have been called after the last call
to next or previous.
If call to set() method is followed up by any call made to remove() or add() method after next()
or previous() than UnsupportedOperationException is thrown.
No such method in java.util.Iterator.
7
All the implementations of List interface like ArrayList, LinkedList, Vector,
CopyOnWriteArrayList classes returns listIterator.
All Implementation classes of Collection interface’s subinterfaces like Set and List return
iterator.
For more detail read : Iterator vs ListIterator - Similarity and Differences in java
Collection interview Question 8. What are differences between Collection and Collections
in java?
Answer. This is another very important collection framework interview question.In real projects
you must have used both Collection and Collections but what is the difference between two of
them in java?
java.util.Collections is a utility class which consists of static methods that operate on or return
Collection in java.
Additionally you must know that java.util.Collection and java.util.Collections both were
introduced in second version of java i.e. in JDK 2.0.
Collection interview Question 9. What are core classes and interfaces in java.util.List
hierarchy in java?
Answer. Freshers must know core classes in List hierarchy but experienced developers must be
able to explain this java.util.List hierarchy in detail.
Collection interview Question 10. What are core classes and interfaces in java.util.Set
hierarchy?
Answer. Freshers must know core classes in Set hierarchy but experienced developers must be
able to explain this java.util.Set hierarchy in detail.
Collection interview Question 11. What are core classes and interfaces in java.util.Map
hierarchy?
Answer. Freshers must know core classes in Map hierarchy but experienced developers must be
able to explain this java.util.Map hierarchy in detail.
java.util.Map interface extends java.util.Collection interface.
Also some abstract classes like java.util.Dictionary and java.util.AbstractMap have been
mentioned in hierarchy.
Collection interview Question 12. What are differences between Iterator and Enumeration
in java?
Answer. Experienced developers must be well versed to answer this collection framework
interview question in java.
Property
java.util.Enumeration
java.util.Iterator
1
Remove elements during iteration
java.util.Enumeration doesn’t allows to remove elements from collection during iteration in
java.
java.util.Iterator allows to remove elements from collection during iteration by using remove()
method in java.
2
Improved naming conventions in Iterator
nextElement()
Method Returns the next element of this enumeration if this enumeration object has at least one
more element to provide.
hasMoreElements()
returns true if enumeration contains more elements.
nextElement() has been changed to next() in Iterator.
And
For more detail read : Iterator vs Enumeration - Differences and similarities in java
Collection interview Question 13. How do we override equals and hashcode method in java,
write a code to use Employee as key in HashMap in java? (Important)
Answer. This is one of the most important collection framework interview question in java.
Prepare for this question properly. Freshers must know the concept how to override equals and
hashcode method but experienced developers must be able to write the java code to override
equals and hashcode neatly. We will override equals() and hashCode() like this -
By overriding equals() and hashCode() method we could use custom object as key in HashMap.
if(obj==null) //If obj is null, return without comparing obj& Employee class.
@Override
Public boolean equals(Object obj){
if(obj==null)
return false;
if(this.getClass()!=obj.getClass())
return false;
Employee emp=(Employee)obj;
return (emp.id==this.id || emp.id.equals(this.id))
&& (emp.name==this.name || emp.name.equals(this.name));
}
@Override
Public int hashCode(){
int hash=(this.id==null ? 0: this.id.hashCode() ) +
(this.name==null ? 0: this.name.hashCode() );
return hash;
}
Let’s say in an organisation there exists a employee with id=1 and name=’sam’ and some
data is stored corresponding to him, but if modifications have to be made in data, previous data
must be overridden.
Must read : Overriding equals and hashcode method - Top 18 Interview questions in java
Collection interview Question 14. What classes should i prefer to use a key in HashMap in
java? (Important)
Answer. This collection framework interview question will check your in depth knowledge of
Java’s Collection Api’s. we should prefer String, Integer, Long, Double, Float, Short and any
other wrapper class. Reason behind using them as a key is that they override equals() and
hashCode() method, we need not to write any explicit code for overriding equals() and
hashCode() method in java.
Let’s use Integer class as key in HashMap(Example) -
import java.util.HashMap;
import java.util.Map;
publicclass StringInMapExample {
publicstaticvoid main(String...a){
//HashMap's key=Integer class (Integer’s api has already overridden hashCode() and
equals() method for us )
Map<Integer, String> hm=new HashMap<Integer, String>();
hm.put(1, "data");
hm.put(1, "data OVERRIDDEN");
System.out.println(hm.get(1));
}
}
/*OUTPUT
data OVERRIDDEN
*/
If, we note above program, what we will see is we didn’t override equals() and hashCode()
method, but still we were able to store data in HashMap, override data and retrieve data using get
method.
>Let’s check in Integer’s API, how Integer class has overridden equals() and hashCode()
method :
publicinthashCode() {
returnvalue;
}
publicbooleanequals(Object obj) {
if (obj instanceof Integer) {
returnvalue == ((Integer)obj).intValue();
}
returnfalse;
}
Collection interview Question 15. What are differences between HashMap and Hashtable
in java?
Answer. Fresher and Experienced developers must answer this important collection framework
interview question in detail in java.
Differences between java.util.HashMap and java.util.Hashtable in java >
Property
java.util.HashMap
java.util.Hashtable
1
synchronization
java.util.HashMap is not synchronized (because 2 threads on same HashMap object can access
it at same time) in java.
For more detail read : HashMap and Hashtable - Similarity and Differences in java
Property
java.util.HashSet
java.util.LinkedHashSet
java.util.TreeSet
1
Insertion order
java.util.HashSet does not maintains insertion order in java.
Output >
No specific order
java.util.LinkedHashSet maintains insertion order in java.
Output >
b
c
a
java.util.TreeSet is sorted by natural order in java.
Output >
a
b
c
2
Null elements
HashSet allows to store one null in java.
LinkedHashSet allows to store one null in java.
TreeSet does not allows to store any null in java.
Collection interview Question 17. What are differences between HashMap and
ConcurrentHashMap in java?
Answer. Take my words java developers won’t be able to get away from this very important
collection framework interview question.
But how despite of being synchronized, 2 threads on same ConcurrentHashMap object can
access it at same time?
Read this post for performance comparison between HashMap and ConcurrentHashMap.
Null keys and values
HashMap allows to store one null key and many null values i.e. any key can have null value.
ConcurrentHashMap does not allow to store null key or null value.
Any attempt to store null key or value throws runtimeException (NullPointerException).
iterators
The iterators returned by the iterator() method of HashMap are fail-fast >
hashMap.keySet().iterator()
hashMap.values().iterator()
hashMap.entrySet().iterator()
concurrentHashMap.keySet().iterator()
concurrentHashMap.values().iterator()
concurrentHashMap.entrySet().iterator()
synchronized (map){
if (!map.containsKey(key))
returnmap.put(key, value);
else
returnmap.get(key);
}
Program to create method that provides functionality similar to putIfAbsent method of
ConcurrentHashMap and to be used with HashMap
If map does not contain specified key, put specified key-value pair in map and return null.
If map already contains specified key, return value corresponding to specified key.
Property
HashMap
Hashtable
LinkedHashMap
TreeMap
1
Insertion order
HashMap does not maintains insertion order in java.
Hashtable does not maintains insertion order in java.
LinkedHashMap maintains insertion order in java.
TreeMap is sorted by natural order of keys in java.
2
Performance
HashMap is not synchronized, hence its operations are faster as compared to Hashtable.
Hashtable is synchronized, hence its operations are slower as compared HashMap.
But it was refactored in java 2 i.e. JDK 1.2 to implement the Map interface, hence making it a
member of member of theJava Collections Framework.
LinkedHashMap was introduced in fourth version of java i.e. JDK 4.0
TreeMap was introduced in second version of java i.e. JDK 2.0
Property
java.util.HashMap
java.util.IdentityHashMap
1
Keys comparison object-equality vs reference-equality
HashMap when comparing keys (and values) performs object-equality not reference-equality. In
an HashMap, two keys k1 and k2 are equal if and only if (k1==null ? k2==null : k1.equals(k2))
IdentityHashMap when comparing keys (and values) performs reference-equality in place of
object-equality. In an IdentityHashMap, two keys k1 and k2 are equal if and only if (k1==k2)
2
Initial size
Constructs a new HashMap, Its initial capacity is 16 in java.
new HashMap();
As shown in Program 3.
overridden equals() and hashCode() method are not called when put, get methods are called in
IdentityHashMap.
Because IdentityHashMap implements equals() and hashCode() method by itself and checks for
reference-equality of keys.
As shown in Program 4.
6
Application - can maintain proxy object
HashMap cannot be used to maintain proxy object.
IdentityHashMap can be used to maintain proxy objects. For example, we might need to maintain
proxy object for each object debugged in the program.
For more detail read : HashMap vs IdentityHashMap - Similarity and Differences with
program in java
java.util.WeakHashMap is hash table based implementation of the Map interface, with weak
keys.
An entry in a WeakHashMap will be automatically removed by garbage collector when its key is
no longer in ordinary use. Mapping for a given key will not prevent the key from being discarded
by the garbage collector, (i.e. made finalizable, finalized, and then reclaimed). When a key has
been discarded its entry is removed from the map in java.
java.util.WeakHashMap is implementation of the java.util.Map interface in java.
Collection interview Question 25. How to implement own ArrayList in java?Or How
ArrayList works in java ?
Answer. ArrayList custom implementation / How ArrayList works in java
Collection interview Question 26. How to implement own HashSet in java? Or How
HashSet works in java ?
Answer. Set Custom implementation/ Or How HashSet works in java
Collection interview Question 27. How to implement own LinkedHashSet in java? Or How
LinkedHashSet works in java ?
Answer. LinkedHashSet Custom implementation/ How LinkedHashSet works in java
Collection interview Question 28. What do you mean by fail-fast and fast-safe? What is
ConcurrentModificationException?
Answer.
Iterator returned by few Collection framework Classesare fail-fast, means any structural
modification made to these classes during iteration will throw ConcurrentModificationException.
Some important classes whose returned iterator is fail-fast >
• ArrayList
• LinkedList
• vector
• HashSet
Iterator returned by few Collection framework Classes are fail-safe, means any structural
modification made to these classes during iteration won’t throw any Exception.
Some important classes whose returned iterator is fail-safe >
• CopyOnWriteArrayList
• CopyOnWriteArraySet
• ConcurrentSkipListSet
Collection interview Question 29. What are different ways of iterating over elements in
List?
Answer.
Creating ArrayList and add element.
List<String> arrayList=new ArrayList<String>();
arrayList.add("javaMadeSoEasy");
Collection interview Question 30. What are different ways of iterating over elements in Set?
Answer. Creating HashSet and add element.
Set<String> hashSet=new HashSet<String>();
hashSet.add("javaMadeSoEasy");
Collection interview Question 31. What are different ways of iterating over keys, values
and entry in Map?
Answer. Create and put key-value pairs in HashMap>
Map<Integer,String> hashMap=new HashMap<Integer,String>();
hashMap.put(11, "javaMadeSoEasy");
hashMap.put(21, "bmw");
hashMap.put(31, "ferrari");
Iterator<Integer> keyIterator=hashMap.keySet().iterator();
while(keyIterator.hasNext()){
System.out.println(keyIterator.next());
}
/*OUTPUT
21
11
31
*/
/*OUTPUT
javaMadeSoEasy
audi
ferrari
*/
iterator returned is fail-fast..
/*OUTPUT
21=javaMadeSoEasy
11=audi
31=ferrari
*/
iterator returned is fail-fast..
32. What is difference between Comparable and Comparator? How can you sort List?
Answer.
Property
Comparable
Comparator
1
Comparing instances of class
Comparable is used to compare instances of same class
Comparator can be used to compare instances of same or different classes.
2
sorting order
Comparable can be implemented by class which need to define a natural ordering for its
objects.
Example - String, Integer, Long , Date and all other wrapper classes implements Comparable.
Comparator is implemented when one wants a different sorting order and define custom way of
comparing two instances.
3
Changes to class
For using Comparable, original Class must implement it.
Example-
For using Comparable, Employee Class must implement it, no other class can implement it.
As used in Program 1
Class itself can implement Comparator
or
any other class can implement Comparator. Hence avoiding modification to original class.
Example-
As used in Program 4
4
Sorting on basis on one or many criteria
Provides sorting only on one criteria, because Comparable can be implemented by original class
only.
We can use Comparator to sort class on many criterias because class itself or any other class can
implement Comparator.
5
Method
compareTo method
@Override
publicint compareTo(Employee obj) {
//sort Employee on basis of name(ascending order)
returnthis.name.compareTo(obj.name);
}
As used in Program 1
compare method
@Override
publicint compare(Employee obj1, Employee obj2) {
//sort Employee on basis of name(ascending order)
return obj1.name.compareTo(obj2.name);
}
As used in Program 3
6
Package
java.lang
As used in Program 1
Let's say we wanna sort list of Employee,
Collections.sort(list,new ComparatorName());
uses Comparator interface for sorting class.
As used in Program 5
Collection interview Question 34. How can you sort given HashMap on basis of keys?
Answer.
Please Read : Sort Map by key in Ascending and descending order by implementing
Comparator interface and overriding its compare method and using TreeMap
Collection interview Question 35. How can you sort given HashMap on basis of values?
Answer.
Please Read : Sort Map by value in Ascending and descending order by implementing
Comparator interface and overriding its compare method
Collection interview Question 36. In what all possible ways you can sort a given Set?
Answer.
Please Read : Sort Set by using TreeSet and by implementing Comparator and
Comparable interface
Collection interview Question 37. How you can sort arrays? And how Comparator of
superclass can be used by subclasses?
Answer.
Please Read : Arrays.sort to sort arrays by implementing Comparator and how
Comparator of superclass can be used by subclasses
Property
java.util.ArrayList
java.util.concurrent. CopyOnWriteArrayList
1
synchronization
ArrayList is not synchronized (because 2 threads on same ArrayList object can access it at same
time).
3
Enumeration is fail-fast
Enumeration returned by ArrayList is fail-fast, means any structural modification made to
ArrayList during iteration using Enumeration will throw ConcurrentModificationException.
As shown in Program 1 below.
Enumeration returned by CopyOnWriteArrayList is fail-safe.
For more detail read :ArrayList vs CopyOnWriteArrayList - Similarity and Differences with
program
Collection interview Question 39. What are differences between HashSet vs
CopyOnWriteArraySet?
Answer.
Differences between java.util.HashSet and java.util.concurrent.CopyOnWriteArraySet in java >
Property
java.util.HashSet
java.util.concurrent. CopyOnWriteArraySet
1
synchronization
HashSet is not synchronized (because 2 threads on same HashSet object can access it at same
time) in java.
CopyOnWriteArraySet is synchronized (because 2 threads on same CopyOnWriteArraySet
object cannot access it at same time) in java.
2
Iterator
Iterator returned by HashSet is Fail-fast, means any structural modification made to HashSet
during iteration using Iterator will throw ConcurrentModificationException in java.
3
Enumeration is fail-fast
Enumeration returned by HashSet is fail-fast, means any structural modification made to
HashSet during iteration using Enumeration will throw ConcurrentModificationException.
For more detail read : HashSet vs CopyOnWriteArraySet - Similarity and Differences with
program
Property
java.util.TreeSet
java.util.concurrent. ConcurrentSkipListSet
1
synchronization
TreeSet is not synchronized (because 2 threads on same TreeSet object can access it at same
time) in java.
ConcurrentSkipListSet is synchronized (because 2 threads on same ConcurrentSkipListSet
object cannot access it at same time) in java.
2
Iterator
Iterator returned by TreeSet is Fail-fast, means any structural modification made to TreeSet
during iteration using Iterator will throw ConcurrentModificationException in java.
Property
java.util.TreeMap
java.util.concurrent. ConcurrentSkipListMap
1
synchronization
TreeMap is not synchronized (because 2 threads on same TreeMap object can access it at same
time) in java.
all three iterators are fail-fast, means any structural modification made to TreeMap during
iteration using any of 3 Iterator will throw ConcurrentModificationException.
Collection interview Question 43. Can we use null element in TreeSet? Give reason?
Answer. No, TreeSet does not allows to store any null keys.
Any attempt to add null throws runtimeException (NullPointerException).
TreeSet internally compares elements for sorting elements by natural order (comparator may be
used for sorting, if defined at creation time)and null is not comparable, Any attempt to compare
null with other object will throw NullPointerException.
Collection interview Question 44. Can we use null key in TreeMap? Give reason?
Answer. No, TreeMapnot allow to store null key.
Any attempt to store null key throws runtimeException (NullPointerException).
TreeMap internally compares keys for sorting keys by natural order (comparator may be used for
sorting, if defined at creation time) and null is not comparable, Any attempt to compare null with
other object will throw NullPointerException.
Collection interview Question 45. How ConcurrentHashMap works? Can 2 threads on
same ConcurrentHashMap object access it concurrently?
Answer. ConcurrentHashMapis divided into different segments based on concurrency level. So
different threads can access different segments concurrently.
For operations such as putAll concurrent retrievals may reflect removal of only some entries.
For operations such as clear concurrent retrievals may reflect removal of only some entries.
Collection interview Question 46. Write a program to show consequence of using ArrayList
in multithreading environment?
Answer. Program to show consequence of using ArrayList in multithreading environment in java
dri blog
Collection interview Question 47. Write a program to show advantage of using Vector in
multithreading environment?
Answer. Program to show advantage of using Vector in multithreading environment in java
Collection interview Question 48. Mention properties of most frequently used Collection
classes and Interfaces? Mention as many properties as much you can.
Answer. This question is real test for experienced developers, this will test your in depth
awareness of Collection classes and Interfaces. Answering this question in detail will really
ensure your selection.
List
Duplicate elements
insertion order
Sorted by natural order
synchronized
null elements
Iterator
ArrayList
Yes
Yes
Yes
Iterator & listIterator
are
Fail-fast
LinkedList
Yes
Yes
Yes
Iterator & listIterator
are
Fail-fast
CopyOnWriteArrayList
Yes
Yes
Yes
Yes
Iterator & listIterator
are
Fail-safe
Set
Duplicate elements
insertion order
Sorted by natural order
synchronized
null elements
Iterator
HashSet
Yes
Fail-fast
LinkedHashSet
Yes
Yes
Fail-fast
TreeSet
Yes
No
Fail-fast
ConcurrentSkipListSet
Yes
Yes
No
Fail-safe
Map
Duplicate Keys
insertion order of keys
Sorted by natural order of keys
synchronized
null keys or null values
Iterator
Yes
No
All are Fail-fast
ConcurrentHashMap
Yes
No
All are Fail-safe
TreeMap
Yes
Yes
Yes
No
All are Fail-safe
Collection interview Question 50. Which Set class must be preferred in multithreading
environment, considering performance constraint?
Answer. CopyOnWriteArraySet(allows null and elements aren't sorted in natural order) or
ConcurrentSkipListSet(doesn’t allows null and elements are sorted in natural order)
Select one depending on your requirement.
Collection interview Question 51. Which Map class must be preferred in multithreading
environment, considering performance constraint?
Answer. ConcurrentHashMap(keys aren't sorted in natural order) or
ConcurrentSkipListMap(keys are sorted in natural order)
Select one depending on your requirement.
Collection interview Question 52. Let’s say you have to build dictionary and multiple users
can add data in that dictionary? And you can use 2 Collection classes? Which Collection
classes you will prefer and WHY?
Answer. It’s very important question which test your logical reasoning and your ability to
create robust applications in multithreading environment.
Program for creating and using Java dictionary using Collection classes>
package com.ankit.dictionary;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListMap;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
publicclass MyDictionary {
publicstaticvoid main(String[] args) {
ConcurrentSkipListMap<String, TreeSet<String>> myDictionary =
new ConcurrentSkipListMap<String, TreeSet<String>>();
TreeSet<String> innocentMeaning = new TreeSet<String>();
innocentMeaning.add("not responsible for an event yet suffering its consequences");
innocentMeaning.add("not guilty of a crime");
myDictionary.put("innocent", innocentMeaning);
TreeSet<String> appealingMeaning = new TreeSet<String>();
appealingMeaning.add("attractive");
appealingMeaning.add("expressing a desire for help");
myDictionary.put("appealing", appealingMeaning);
System.out.println(myDictionary);
}
}
/* OUTPUT
{appealing=[attractive, expressing a desire for help], innocent=[not guilty of a crime, not
responsible for an event yet suffering its consequences]}
*/