Java Interview Questions - MultiThreading

This set of Java Interview Questions covers MultiThreading topics like Threads, Synchronization, DeadLock, Thread Pool and more.

You can find the previous set of Interview Questions from here:

1. What is the difference between processes and threads?
A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.
2. Explain different ways of creating a thread? Which one is preferred?
Threads can be used by either
  • Extending the Thread class.
    class Counter extends Thread {
        
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let’s see how to start the threads
        public static void main(String[] args){
           Thread t1 = new Counter();
           Thread t2 = new Counter();
           t1.start();  //start the first thread.
           t2.start(); //this starts the 2nd thread.
        }
    }
  • Implementing the Runnable interface.
    class Counter extends Base implements Runnable{
       
        //method where the thread execution will start
        public void run(){
            //logic to execute in a thread   
        }
     
        //let us see how to start the threads
        public static void main(String[] args){
             Thread t1 = new Thread(new Counter());
             Thread t2 = new Thread(new Counter());
             t1.start();  //start the first thread.
             t2.start();  //this starts the 2nd thread.
        }
    }
The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you.
3. Briefly explain high-level thread states?
A Thread can have the below states:
  1. Runnable: A thread becomes runnable when you call the start( ), but does not necessarily start running immediately. It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  2. Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
  3. Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
  4. Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  5. Blocked :Will move to runnable after chnage in I/O condition or when lock is acquired.
  6. Dead: The thread is finished working.
4. What is multithreading and what are the methods for inter-thread communication?
Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class.
  • wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state.
  • notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
5. What's the difference between the methods sleep() and wait()?
  • The code sleep(1000); puts thread aside for exactly one second whereas the code wait(1000), causes a wait of up to one second.
  • A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
  • The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
6. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object. Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.
7. What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:
public synchronized void Method1 () {
    // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
    // Synchronized code here.
  }
}
8. What are the disadvantages of synchronization?
The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
9. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
10. When you will synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
11. What is a ThreadLocal class?
ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads.
Below are some key points about ThreadLocal variables :
  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
12. What is deadlock?
When two threads are waiting each other and can’t precede the program is said to be deadlock. Deadlock may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated.
The thread deadlock can occur in conditions such as:
  1. two threads calling Thread.join() on each other.
  2. two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.
13. What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
14. What is immutable object? How does it help in writing concurrent application?
An object is considered immutable if its state cannot change after it is constructed. Immutable objects are particularly useful in concurrent applications, since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your multi threaded program, since they are
  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
15. What is Starvation? and What is a Livelock?
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
  • LiveLock : Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
    1. When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
    2. When all the threads in a program are stuck in infinite loops.
  • Starvation : Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
16. What is thread pool? Why should we use thread pools?
A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment.
One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.
Below are key reasons to use a Thread Pool :
  1. Using thread pools minimizes the JVM overhead due to thread creation.
  2. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).

Java Interview Questions - Exception

Here is a set of Java Interview Questions which focuses on Exceptions and the Exception Handling framework. You can find the previous set of Interview Questions from here:

1. What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
2. How does exception handling work in Java?
  1. It separates the working/functional code from the error-handling code by way of try-catch clauses.
  2. It allows a clean path for error propagation. If the called method encounters a situation it can’t manage, it can throw an exception and let the calling method deal with it.
  3. By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding.
3. What are the different ways to generate an Exception?
There are two different ways to generate an Exception:
  1. Exceptions can be generated by the Java run-time system. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
  2. Exceptions can be manually generated by your code.Manually generated exceptions are typically used to report some error condition to the caller of a method.
4. What are the two types of Exception in Java?
Exceptions are of two types: Compiler-enforced exceptions, or checked exceptions and Runtime exceptions, or unchecked exceptions.
  • Compiler-enforced (checked) exceptions are instances of the Exception class or one of its subclasses — excluding the RuntimeException branch. The compiler expects all checked exceptions to be appropriately handled. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exception represent unexpected exceptional conditions which can be handled but not necessarily recovered from. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
5. Explain the User-defined or Custom Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purpose. An user defined exception can be created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
       // The class simply has to exist to be an exception
}
6. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
7. What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
8. What is the difference between exception and error?
The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file which does not exist, when the network connection is disrupted, or when operands being manipulated are out of prescribed ranges.
The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
9. What is the super class of java.lang.Exception
java.lang.Throwable, the parent class of all exception related classes.
10. Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.
Eg:
try {
   // try block for code for which we want to catch exceptions.
} catch (Exception e) {
   // catch block to handle the exception.
}
11. What is the use of finally block?
The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.
If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes.
12. What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.
13. Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
14. What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.
public void someMethod(g) throws someException {
      // Method body
}
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
throw new someException("Catch this one !!");

Core Java Interview Questions - Part 3

Here is the Third set of Core Java Interview Questions. You can find the previous set of interview questions from below :
1. Where and how can you use a private constructor.
Private constructor can be used if you do not want any other class to instanstiate the object , the instantiation is done from a static public method. This method is used when dealing with the factory method pattern when the designer wants only one controller (fatory method ) to create the object.
2. Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
3. Differentiate between continue and break.
In break, control comes out of the loop whereas in continue control stops at “continue” statement. The remaining statements aren’t executed as control enters following loop.
4. What restrictions are placed on method overriding in Java Programming?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
5. Why equals should be overridden?
Two objects are considered equal if referring to the same object as the equals method uses only the operator == to compare. Hence while using the object as keys, equals() method needs to be overridden. Similarly while using hashmaps or hashtables the method hashcode needs to be overridden as the object is placed in the hash using hashcode value.
6. Can we override a static method?
The static methods cannot be overridden. If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass.
7. What are Transient and Volatile Modifiers?
Transient: Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
8. What is Garbage Collection?
When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection.
Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
9. How you can force the garbage collection?
Garbage collection automatic process and can't be forced. You could request it by calling System.gc() or Runtime.gc(). JVM does not guarantee that GC will be started immediately and when all the objects will garbage collected.
Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use.
10. What are immutable objects in Java? Can we change the value of an immutable object?
An object is considered to be immutable if its value cannot change after it is created. Immutable objects are particularly very useful in multi-threaded applications. Since they cannot change state, they won’t get corrupted by thread interference or observed in an inconsistent state. Objects of java.lang.Integer and java.lang.String classes are the examples of immutable objects. To create an immutable object You need to make the class final and all its members private or final, so that once objects gets created no one can modify its state.
11. What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
12. What is an applet?
Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser. Applet needs no explicit installation on local machine and runs itself automatically in a java-enabled browser.
13. What is the lifecycle of an applet?
  1. init() method - Can be called when an applet is first loaded
  2. start() method - Can be called each time an applet is started.
  3. paint() method - Can be called when the applet is minimized or maximized.
  4. stop() method - Can be used when the browser moves off the applet’s page.
  5. destroy() method - Can be called when the browser is finished with the applet.
14. What is JVM (Java Virtual Machine)?
JVM stands for Java Virtual Machine. JVM is a software implementation which stands on the top of the real hardware platform and operating system. It provides abstraction between the compiled java program and the hardware and operating system. So the compiled program does not have to worry about what hardware and operating system he has to run in, it’s all handled by the JVM and thus attaining portability. All Java programs are compiled in to bytecodes. JVM can only understand and execute Java bytecodes.
15. Explain the advantages and disadvantages of JAVA.
JAVA offers a number of advantages to developers.
  1. Java is simple: Java was designed to be easy to use and learn than other programming languages. Java is much simpler than C++ as it uses automatic memory allocation and garbage collection where else C++ requires the programmer to allocate memory and to collect garbage.
  2. Java is object-oriented: Programming in Java is centered on creating objects, manipulating objects, and making objects work together. This allows you to create modular programs and reusable code.
  3. Java is platform-independent: Java programs are compiled into Java Virtual Machine code called bytecode. The bytecode is machine independent and is able to run on any machine that has a Java interpreter. With Java, the program need only be compiled once, and the bytecode generated by the Java compiler can run on any platform.
  4. Java is distributed: Distributed computing involves several computers on a network working together. Java is designed to make distributed computing easy with the networking capability that is inherently integrated into it.
  5. Java is secure: Java is one of the first programming languages to consider security as part of its design. The Java language, compiler, interpreter, and runtime environment were each developed with security in mind.
  6. Java is robust: Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to detect many problems that would first show up during execution time in other languages.
  7. Java is multithreaded: Multithreaded is the capability for a program to perform several tasks simultaneously within a program. In Java, multithreaded programming has been smoothly integrated into it.
Disadvantages of JAVA :
  1. Performance: Java can be perceived as significantly slower and more memory-consuming than natively compiled languages such as C or C++.
  2. Single-paradigm language: Java is predominantly a single-paradigm language. However, with the addition of static imports in Java 5.0 the procedural paradigm is better accommodated than in earlier versions of Java.

Please do comment if you find any discrepancies or want to suggest new questions.

Core Java Interview Questions - Part 2

Here is the Second set of Core Java Interview Questions. You can find the previous set of interview questions from below :
1. What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
2. What does the "static" keyword mean in front of a variable? A method? A class? Curly braces {}?
  • static variable: means a class level variable
  • static method: Can be invoked even before a single instance of a class is created. It is not allowed to access the not static members of the class.
  • static class: no such thing.
  • static free floating block: is executed at the time the class is loaded. There can be multiple such blocks. This may be useful to load native libraries when using native methods.
3. What does the "final" keyword mean in front of a variable? A method? A class?
FINAL for a variable : value is constant
FINAL for a method : final method cannot be overridden or hidden by new access specifications.
FINAL for a class : cannot be derived, The best example of a final class is the String class.
4. What is difference between final, finalize() and finally?
final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.
finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.
finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
5. What is casting?
Casting is used to convert the value of one type to another. There are two types of casting in Java, these are Implicit casting and explicit casting. Casting operation is used to convert between types and the instanceof operator is used to check for type information at run time.
6. What are the types of casting?
There are two types of casting in Java, these are Implicit casting and explicit casting.
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not workout for all application scenarios.
Example:
int i = 4000;
long h = i; //Implicit casting
Explicit casting in the process in which the compiler are specifically informed to about transforming the object.
Example:
long ln = 700.20;
t = (int) ln; //Explicit casting
7. What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy.
8. What modifiers may be used with top-level class?
public, abstract and final can be used for top-level class.
9. What are inner class and anonymous class?
Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.
Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
10. Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
eg: boolean  - java.lang.Boolean
int - java.lang.Integer
void - java.lang.Void
11. What is the difference between StringBuffer and String class?
A StringBuffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
The String class represents character strings. All string literals in Java programs are immutable and their values cannot be changed after they are created.
12. What is the difference between the boolean '&' operator and the '&&' operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated.
Whereas when an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
13. Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  1. The global variables breaks the referential transparency
  2. Global variables creates collisions in namespace.
14. Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers.
15. How is it possible for two String objects with identical values not to be equal under the == operator?
The '==' operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

Please do provide your valuable comments and suggestions. Thanks in Advance.

Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates