techgroup-sixwares-blog
techgroup-sixwares-blog
C#, Asp.net, Java, PHP, Power BI, SharePoint Discussion Forums
16 posts
Get the best solutions & answers to problems posted in C#, Asp.net, Java, PHP, Power BI, SharePoint by different programmers. Visit Tech Group Discussion Forum. Call us at +91 - 94600 84282.
Don't wanna be here? Send us removal request.
techgroup-sixwares-blog · 6 years ago
Video
tumblr
Artificial intelligence in speech recognition
The accuracy of artificial intelligence in speech recognition technology has reached a point where it can be seriously considered.  Google’s technology for artificial intelligence in speech recognition, for example, has achieved 95% accuracy, according to venture capital firm Kleiner Perkins Caufield & Byers. Call us @ +91 - 9460084282.
0 notes
techgroup-sixwares-blog · 6 years ago
Link
0 notes
techgroup-sixwares-blog · 6 years ago
Link
0 notes
techgroup-sixwares-blog · 6 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Text
Java Interview Questions
Tumblr media
This is list of some Java interview questions & answers, which are commonly asked in a Java interview. As a senior and matured Java Programmer you must know the answers to these questions to demonstrate basic understanding of Java language and depth of knowledge. Call us @ 9460084282.
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Text
Linq Tutorial
Tumblr media
Tech Group promised to provide best Linq Tutorial. Sixwares Tech Forum also provides solutions and answers to problems posted in Linq, SharePoint by different programmers. Call us @ +91 - 9460084282.
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Text
Java Multithreading Interview Questions & Answers
Today we will go through Java Multithreading Interview Questions & Answers. We will also look into Concurrency interview questions & answers because both multithreading and concurrency go hand in hand. Thread is one of the popular topic in java interview questions. Here I am listing down most of the important java multithreading interview questions & Answers from interview perspective, but you should have good knowledge on java threads to deal with follow up questions.
1. What is the difference between Process and Thread?
A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.
2. What are the benefits of multi-threaded programming?
In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.
3. What is difference between user Thread and daemon Thread?
When we create a Thread in java program, it’s known as user thread. A daemon thread runs in background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.
4. How can we create a Thread in Java?
There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class. Read this post to learn more about creating threads in java.
5. What are different states in lifecycle of Thread?
When we create a Thread in java program, its state is New. Then we start the thread that change it’s state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked and Dead. Read this post to learn more about life cycle of thread.
6. Can we call run() method of a Thread class?
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method.
7. How can we pause the execution of a Thread for specific time?
We can use Thread class sleep() method to pause the execution of Thread for certain time. Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it’s state gets changed to runnable and based on thread scheduling, it gets executed.
8. What do you understand about Thread Priority?
Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.
9. What is Thread Scheduler and Time Slicing?
Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler. Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself.
10. What is context-switching in multi-threading?
Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment.
11. How can we make sure main() is the last thread to finish in Java Program?
We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function. Here is an article about Thread join method.
12. How does thread communicate with each other?
When threads share resources, communication between Threads is important to coordinate their efforts. Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource. Check this post to learn more about thread wait, notify and notifyAll.
13. Why thread communication methods wait(), notify() and notifyAll() are in Object class?
In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now. There is no monitor on threads in java and synchronization can be used with any Object, that’s why it’s part of Object class so that every class in java has these essential methods for inter thread communication.
14. Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?
When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object. Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object. Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.
15. How can we achieve thread safety in Java?
There are several ways to achieve thread safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at thread safety tutorial.
16. What is volatile keyword in Java
When we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it. This makes sure that the value read is the same as in the memory.
17. Which is more preferred – Synchronized method or Synchronized block?
Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.
18. How to create daemon thread in Java?
Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException.
19. What is ThreadLocal?
Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables. Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. Check this post for small example program showing ThreadLocal Example.
20. What is Thread Group? Why it’s advised not to use it?
ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread. Two of the major feature it had are to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has added setUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.
t1. t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(“exception occured:”+e.getMessage());
}
});
21. What is Java Thread Dump, How can we get Java Thread dump of a Program?
Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool etc. I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal based tool, we can create script to generate thread dump at regular intervals to analyze it later on. Read this post to know more about generating thread dump in java.
22. What is Deadlock? How to analyze and avoid deadlock situation?
Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.
To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program.
23. What is Java Timer Class? How to schedule a task to run after specific interval?
java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.
Check this post for java Timer example.
24. What is Thread Pool? How can we create Thread Pool in Java?
A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.
A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. Thread Pool Example program shows how to create and use Thread Pool in java.
Java Concurrency Interview Questions Answers 1. What is atomic operation? What are atomic classes in Java Concurrency API?
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.
int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.
To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization. Go to this article to learn more about atomic concurrent classes.
2. What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
Lock interface provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects. The advantages of a lock are
it’s possible to make them fair
it’s possible to make a thread responsive to interruption while waiting on a Lock object.
it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired
it’s possible to acquire and release locks in different scopes, and in different orders
3. What is Executors Framework?
In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.
The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.
Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.
4. What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. Check this post for producer-consumer problem implementation using BlockingQueue.
5. What is Callable and Future?
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result. Check this post for Callable Future Example.
6. What are Concurrent Collection Classes?
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.
Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates. Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.
7. What is Executors Class?
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.
Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations
8. Why synchronization is important?
A. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely affect the performance.
9. What is a ThreadLocal class?
A. 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. ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton.
10. What is a daemon thread?
A. Daemon threads are sometimes called “service” or “background” threads. These are threads that normally run at a low priority and provide a basic service to a program when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. The JVM exits whenever all non-daemon threads have completed, which means that all daemon threads are automatically stopped. To make a thread  as a daemon thread in Java
? 1myThread.setDaemon(true);
The JVM always has a main thread as default. The main thread is always non-daemon. The user threads are created from the main thread, and by default they are non-daemon. If you want to make a user created thread to be daemon (i.e. stops when the main thread stops), use the setDaemon(true) as shown above
11. How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data (via stack)?
A. The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use.Example: If you imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. In this example the concurrent threads share the same resource file. Because these threads share the common resource file they should be synchronized.  Also these two threads should communicate with each other because the consumer thread, which reads the file, should wait until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its writing operation.Let’s look at a sample code where count is a shared resource. The consumer thread will wait inside the consume( ) method on the producer thread, until the producer thread increments the count inside the produce( ) method and subsequently notifies the consumer thread. Once it has been notified, the consumer thread waiting inside the consume( ) method will give up its waiting state and completes its method by consuming the count (i.e. decrementing the count).s
12. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
A. 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.
13. What does join( ) method do?
A. t.join( ) allows the current thread to wait indefinitely until thread “t” is finished.  t.join (5000) allows the current thread to wait  for thread “t” to finish but does not wait longer than 5 seconds.
?
try { t.join(5000); //current thread waits for thread “t” to complete but does not wait more than 5 sec if(t.isAlive()){ //timeout occurred. Thread “t” has not finished } else { //thread “t” has finished } }
For example, say you need to spawn multiple threads to do the work, and continue to the next step only after all of them have completed, you will need to tell the main thread to wait. this is done with thread.join() method.
Here is the RunnableTask. The task here is nothing but sleeping for 10 seconds as if some task is being performed. It also prints the thread name and timestamp as to when this task had started
?
import java.util.Date;
public class RunnableTask implements Runnable {
@Override public void run() { Thread thread = Thread.currentThread(); System.out.println(thread.getName() + ” at ” + new Date()); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }
The taskmanager manages the tasks by spawing multiple user threads from the main thread. The main thread is always created by default. The user threads 1-3 are run sequentially, i.e. thread-2 starts only after thread-1 completes, and so on. The user threads 4-6 start and executes concurrently.
?
public class TaskManager {
public static void main(String[] args) throws InterruptedException {
RunnableTask task = new RunnableTask();
//threads 1-3 are run sequentially Thread thread1 = new Thread(task, “Thread-1”); Thread thread2 = new Thread(task, “Thread-2”); Thread thread3 = new Thread(task, “Thread-3”);
thread1.start(); //invokes run() on RunnableTask thread1.join(); // main thread blocks (for 10 seconds) thread2.start(); //invokes run() on RunnableTask thread2.join(); // main thread blocks (for 10 seconds) thread3.start(); //invokes run() on RunnableTask thread3.join(); // main thread blocks (for 10 seconds)
Thread thread4 = new Thread(task, “Thread-4”); Thread thread5 = new Thread(task, “Thread-5”); Thread thread6 = new Thread(task, “Thread-6”);
thread4.start(); //invokes run() on RunnableTask thread5.start(); //invokes run() on RunnableTask thread6.start(); //invokes run() on RunnableTask } }
Notice the times of the output. There is a 10 second difference bewteen threads 1-3. But Threads 4-6 started pretty much the same time.
?
Thread-1 at Fri Mar 02 16:59:22 EST 2012 Thread-2 at Fri Mar 02 16:59:32 EST 2012 Thread-3 at Fri Mar 02 16:59:42 EST 2012 Thread-4 at Fri Mar 02 16:59:47 EST 2012 Thread-6 at Fri Mar 02 16:59:47 EST 2012 Thread-5 at Fri Mar 02 16:59:47 EST 2012
14. If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue?
A. No. Only one thread can acquire the lock in a synchronized method of an object. Each object has a synchronization lock. No 2 synchronized methods within an object can run at the same time. One synchronized method should wait for the other synchronized method to release the lock.   This is demonstrated here with method level lock. Same concept is applicable for block level locks as well.
15. Explain threads blocking on I/O?
A. Occasionally threads have to block on conditions other than object locks. I/O is the best example of this. Threads block on I/O (i.e. enters the waiting state) so that other threads may execute while the I/O operation is performed. When threads are blocked (say due to time consuming reads or writes) on an I/O call inside an object’s synchronized method and also if the other methods of the object are also synchronized then the object is essentially frozen while the thread is blocked. Be sure to not synchronize code that makes blocking calls, or make sure that a non-synchronized method exists on an object with synchronized blocking code. Although this technique requires some care to ensure that the resulting code is still thread safe, it allows objects to be responsive to other threads when a thread holding its locks is blocked.
16. If you have a circular reference of objects, but you no longer reference it from an execution thread, will this object be a potential candidate for garbage collection?
A. Yes. Refer diagram below.
17. Which of the following is true?
a) wait( ), notify( ) ,notifyall( ) are defined as final & can be called only from within a synchronized method b) Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException c) wait( ),notify( ),notifyall( ) & sleep () are methods of object class
A. a and b. The c is wrong because the sleep method is a member of the Thread class.The other methods are members of the Object class.
18. What are some of the threads related problems and what causes those problems?
A. DeadLock, LiveLock, and Starvation. Deadlock occurs when two or more threads are blocked forever, waiting for each other. This 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:
two threads calling Thread.join() on each other.
two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.
Starvation and livelock are much less common a problem than deadlock, and it 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.
The thread livelock can occur in conditions such as:
all the threads in a program are stuck in infinite loops.
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.
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. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. The thread starvation can occur in conditions such as:
one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
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.
What happens if you call the run( ) method directly instead of via the start method? A. Calling run( ) method directly just executes the code synchronously (in the same thread), just like a normal method call. By calling the start( ) method, it starts the execution of the new thread and calls the run( ) method. The start( ) method returns immediately and the new thread normally continues until the run( ) method returns. So, don’t make the mistake of calling the run( ) method directly.Note:  These Java interview questions and answers are extracted from my book “Java/J2EE Job Interview Companion”.
1 note · View note
techgroup-sixwares-blog · 7 years ago
Text
Java Collections Interview Questions and Answers
Here are some Java Collections Interview Questions and Answers to prepare your interview.
Java Collections Framework is the fundamental aspect of java programming language. It’s one of the important topic for java interview questions. Here I am listing some important java collections interview questions and answers for helping you in interview.
Here is the list of mostly asked java collections interview questions with answers.
1. What is difference between ArrayList and vector?
1) Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
2) Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
2. How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)  and Collection.synchronizedCollection(Collection c)
3. If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
4. What is difference between HashMap and HashTable?
 Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
Hashmap is not synchronized in nature but hshtable is.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. Fail-safe– “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationExceptionâ€?
3. HashMap permits null values and only 1 null key, while Hashtable doesn’t allow key or value as null.
5. What are the classes implementing List interface?
There are three classes that implement List interface: 1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
6. Which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet – It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet – It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
7. What is difference between List and a Set?
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements. 2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
8. What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
int [] intArray= new int[6];
intArray[7]   // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList(); list.add(1);  list.add(3); list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1];   // 3 dimensional array
To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
9. When to use ArrayList or LinkedList ?
Ans)  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using “get” is fast, but for LinkedList, it’s slow. It’s slow because there’s no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you’re doing random access on the list, and a LinkedList works better if you’re doing a lot of editing in the middle of the list.
10. Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
11. Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
12. Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
Example of Iteration design pattern – Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.
13. Is it better to have a HashMap with large number of records or n number of small hashMaps?
Ans) It depends on the different scenario one is working on: 1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map. 2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
14. Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
The most important one – If a function is declared such that it takes list. E.g void showDetails(List list); When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
15. What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the ‘n’ location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the ‘n’th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.  ArrayList is index access and LinkedList is iterator access.
16. How to sort list in reverse order?
Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList(); Comparator comp = Collections.reverseOrder();   Collections.sort(list, comp)
17. Can a null element added to a Treeset or HashSet?
Ans) A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element.
18. How to sort list of strings ,case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
19. How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.
20. What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
21. Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
22. Which data structure HashSet implements?
Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.
23. Arrange in the order of speed – HashMap,HashTable, Collections.synchronizedMap, concurrentHashmap ?
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
24. What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
25. What is WeakHashMap?
Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes
techgroup-sixwares-blog · 7 years ago
Text
AngularJS Interview Questions & Answers
AngularJS Interview Questions & Answers
1. What is AngularJS?
AngularJS is a javascript framework used for creating single web page applications.  It allows you to use HTML as your template language and enables you to extend HTML’s syntax to express your application’s components clearly.
2. Explain what are the key features of AngularJS?
The key features of AngularJS are
Scope Controller View Model Services Data Binding Directives Testable Filters 3. What is scope in AngularJS?
Scopes are objects that refer to the model. They act as glue between controller and view.
4. What are the controllers in AngularJS?
Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data.
5. What are the services in AngularJS?
AngularJS come with several built-in services. For example $https: service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app.
6.What Are Filters? Explain Different Filters Provided By AngularJS?
An AngularJS Filter changes or transforms the data before passing it to the view. These Filters work in combination with AngularJS expressions or directives. AngularJS uses pipe character (“|”) to add filters to the expressions or directives. For example:
<p> {{ bid | currency }} </p> The above example is an expression enclosed in the curly braces. The filter used in this expression is currency. Also important to note that filters are case-sensitive.
AngularJS provides following filters to transform data.
currency – It is used to format a number to a currency format. date – It is required to format a date to a specified format. filter – It chooses a subset of items from an array. json – It formats an object to a JSON string. limitTo – Its purpose is to create an array or string containing a specified number of elements/characters. The elements are selected, either from the beginning or the end of the source array or string. This depends on the value and sign (positive or negative) of the limit. lowercase – This filter converts a string to lower case. number – It formats a number as text. orderBy – It enables to sort an array. By default, sorting of strings happens alphabetically. And sorting of numbers is done numerically. It also supports a comparator function where we can define what will be counted as a match or not. uppercase – This filter converts a string to upper case. 7.Explain What Directives Are? Mention Some Of The Most Commonly Used Directives In AngularJS Application?
AngularJS extends the behavior of HTML and DOM elements with new attributes called Directives. It directs the AngularJS’s HTML compiler ($compile) to attach a unique action to that DOM element. This AngularJS component starts with the prefix “ng.”
Following is the list of AngularJS built-in directives.
ng-bind – The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If there is any change in the value of the given variable or expression, then the content of the specified HTML element will also be updated accordingly. It supports one-way binding only. ng-model – This directive is used to bind the value of HTML controls (input, select, text area) to application data. It is responsible for linking the view into the model. Directives such as ‘input’, ‘text area’, and ‘select’ require it. It supports two-way data binding. ng-class – This directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. ng-app – Just like the “Main()” function of Java language, this directive marks the beginning of the application to AngularJS’s HTML compiler ($compile). If we do not use this directive first, an error gets generated. ng-init – This is used to initialize the application data so that we can use it in the block where it is declared. If an application requires local data like a single value or an array of values, this can be achieved using the ng-init directive. ng-repeat – This repeats a set of HTML statements for the defined number of times. The set of HTML statements will be repeated once per item in a collection. This collection must be an array or an object. We can even create custom directives and use them in our AngularJS Application.
8. Why AngularJS?
AngularJS lets us extend HTML vocabulary for our application resulting in an expressive, readable, and quick to develop environment . Some of the advantages are:
   MVC implementation is done right.    It extends HTML using directives, expression and data binding techniques to define a powerful HTML template.    Two way data-binding, form validations, routing supports, inbuilt services.    REST friendly.    Dependency injection support.    It helps you to structure and test your JavaScript code. 9. Is AngularJS compatible with all browsers?
Yes AngularJS is compatible with the following browsers: Safari, Chrome, Firefox, Opera 15, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).
10. How to implement routing in AngularJS?
It is a five-step process:
Step 1: – Add the “Angular-route.js” file to your view. Step 2: – Inject “ngroute” functionality while creating Angular app object. Step 3: – Configure the route provider. Step 4: – Define hyperlinks. Step 5: – Define sections where to load the view. 11. List Down The Popular AngularJS IDE Plugins/Extensions For Web Development?
Here is a list of IDE Plugins and Extensions which can enhance the way you code with AngularJS:
Sublime Text WebStorm Eclipse Netbeans Visual Studio 2012/2013 Express or higher TextMate Brackets ATOM 12. Mention what are the advantages of using AngularJS ?
AngularJS has several advantages in web development.
AngularJS supports MVC pattern Can do two ways data binding using AngularJS It has per-defined form validations It supports both client server communication It supports animations 13. Who created Angular JS ?
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is being developed by Google.
14. What Is The Difference Between One-Way Binding And Two-Way Binding?
The main difference between one-way binding and two-way binding is as follows.
In one-way binding, the scope variable in the HTML gets initialized with the first value its model specifies. In two-way binding, the scope variable will change its value whenever the model gets a different value.
0 notes
techgroup-sixwares-blog · 7 years ago
Text
Java Interview Questions & Answers And Java Tutorials
This is list of some Java interview questions & answers, which are commonly asked in a Java interview.
As a senior and matured Java Programmer you must know the answers to these questions to demonstrate basic understanding of Java language and depth of knowledge.
1. What is immutable object in Java? Can you change values of a immutable object?
A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. 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. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics:
Immutable objects are simple to use test and construct. Immutable objects are automatically thread-safe. Immutable objects do not require a copy constructor. Immutable objects do not require an implementation of clone. Immutable objects allow hashCode to use lazy initialization, and to cache its return value. Immutable objects do not need to be copied defensively when used as a field. Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). Immutable objects have their class invariant established once upon construction, and it never needs to be checked again. Immutable objects always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state. 2. How to create a immutable object in Java? Does all property of immutable object needs to be final?
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. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
3. What is difference between String, StringBuffer and StringBuilder? When to use them?
The main difference between the three most commonly used String classes as follows.
StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable. StringBuffer class implementation is synchronized while StringBuilder class is not synchronized. Concatenation operator “+” is internally implemented by Java using either StringBuffer or StringBuilder. Criteria to choose among String, StringBuffer and StringBuilder
If the Object value will not change in a scenario use String Class because a String object is immutable. If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster). If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized). 4. Why String class is final or immutable?
It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java
Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict. Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered You can share duplicates by pointing them to a single instance. You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret that makes Java substring implementation very fast. Immutable objects are good fit for becoming Hashtable keys. If you change the value of any object that is used as a hash table key without removing it and re-adding it you will lose the object mapping. Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth. If String were not final, you could create a subclass and have two strings that look alike when “seen as Strings”, but that are actually different. 5. Is Java Pass by Reference or Pass by Value?
The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. The difficult thing can be to understand that Java passes “objects as references” passed by value. This can certainly get confusing and I would recommend reading this article from an expert: http://javadude.com/articles/passbyvalue.htm Also read this interesting thread with example on StackOverflow : Java Pass By Ref or Value
6. What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?
This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered
lang.OutOfMemoryError: Java heap space The quick solution is to add these flags to JVM command line when Java runtime is started:
-Xms1024m -Xmx1024m
lang.OutOfMemoryError: PermGen space The solution is to add these flags to JVM command line when Java runtime is started:
-XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled
Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.
7. What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call. if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed. 8. Why there are two Date classes; one in java.util package and another in java.sql?
From the JavaDoc of java.sql.Date:
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE, the millisecond values wrapped inside a java.sql.Date instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero.
Explanation: A java.util.Date represents date and time of day, a java.sql.Date only represents a date (the complement of java.sql.Date is java.sql.Time, which only represents a time of day, but also extends java.util.Date).
9. What is Marker interface? How is it used in Java?
The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are
java.io.Serializable – Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. java.rmi.Remote – The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a “remote interface”, an interface that extends java.rmi.Remote are available remotely. java.lang.Cloneable – A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object’s clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown. javax.servlet.SingleThreadModel – Ensures that servlets handle only one request at a time. This interface has no methods. java.util.EvenListener – A tagging interface that all event listener interfaces must extend. The “instanceof” keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.
10. Why main() in java is declared as public static void main? What if the main method is declared as private?
Public – main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application static – When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class. void – Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system. If main method is declared as private then – Program will compile properly but at run-time it will give “Main method not public.” error.
11. What are available drivers in JDBC?
JDBC technology drivers fit into one of four categories:
A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress. 12. What are the types of statements in JDBC?
JDBC API has 3 Interfaces, (1. Statement, 2. PreparedStatement, 3. CallableStatement ). The key features of these are as follows:
Statement
This interface is used for executing a static SQL statement and returning the results it produces. The object of Statement class can be created using Connection.createStatement() method. PreparedStatement
A SQL statement is pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface. CallableStatement
This interface is used to execute SQL stored procedures. This extends PreparedStatement interface. The object of CallableStatement class can be created using Connection.prepareCall() method. 13. What is a stored procedure? How to call stored procedure using JDBC API?
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. Stored procedures can be called using CallableStatement class in JDBC API. Below code snippet shows how this can be achieved.
CallableStatement cs = con.prepareCall(“{call MY_STORED_PROC_NAME}”);
ResultSet rs = cs.executeQuery();
14. What is Connection pooling? What are the advantages of using a connection pool?
Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database.
Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool.
Apart from performance this also saves you resources as there may be limited database connections available for your application.
15. How to do database connection using JDBC thin driver ?
This is one of the most commonly asked questions from JDBC fundamentals, and knowing all the steps of JDBC connection is important.
import java.sql.*;
class JDBCTest {
public static void main (String args []) throws Exception
{
//Load driver class
Class.forName (“oracle.jdbc.driver.OracleDriver”);
//Create connection
Connection conn = DriverManager.getConnection
(“jdbc:oracle:thin:@hostname:1526:testdb”, “scott”, “tiger”);
// @machineName:port:SID,   userid,  password
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(“select ‘Hi’ from dual”);
while (rs.next())
System.out.println (rs.getString(1));   // Print col 1 => Hi
stmt.close();
}
}
16. What does Class.forName() method do?
Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName(‘MyClass’) is going to do following
– Load the class MyClass. – Execute any static block code of MyClass. – Return an instance of MyClass.
JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this
Class.forName(“org.mysql.Driver”);
All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException(“Can’t register driver!”);
}
}
Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.
17. Which one will you use Statement or PreparedStatement? Or Which one to use when (Statement/PreparedStatement)? Compare PreparedStatement vs Statement.
By Java API definitions: Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. There are few advantages of using PreparedStatements over Statements
Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. (What does pre-compiled statement means? The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.) In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way. SQL injection attacks on a system are virtually impossible when using PreparedStatements. 18. What does setAutoCommit(false) do?
A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode using below command
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method. A Simple transaction with use of autocommit flag is demonstrated below.
con.setAutoCommit(false);
PreparedStatement updateStmt =
con.prepareStatement( “UPDATE EMPLOYEE SET SALARY = ? WHERE EMP_NAME LIKE ?”);
updateStmt.setInt(1, 5000); updateSales.setString(2, “Jack”);
updateStmt.executeUpdate();
updateStmt.setInt(1, 6000); updateSales.setString(2, “Tom”);
updateStmt.executeUpdate();
con.commit();
con.setAutoCommit(true);
19. What are database warnings and How can I handle database warnings in JDBC?
Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects. Handling SQLWarning from connection object
//Retrieving warning from connection object
SQLWarning warning = conn.getWarnings();
//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();
//Clear all warnings reported for this Connection object.
conn.clearWarnings();
Handling SQLWarning from Statement object
//Retrieving warning from statement object
stmt.getWarnings();
//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();
//Clear all warnings reported for this Statement object.
stmt.clearWarnings();
Handling SQLWarning from ResultSet object
//Retrieving warning from resultset object
rs.getWarnings();
//Retrieving next warning from warning object itself
SQLWarning nextWarning = warning.getNextWarning();
//Clear all warnings reported for this resultset object.
rs.clearWarnings();
The call to getWarnings() method in any of above way retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. Trying to call getWarning() on a connection after it has been closed will cause an SQLException to be thrown. Similarly, trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an SQLException to be thrown. Note that closing a statement also closes a result set that it might have produced.
20. What is Metadata and why should I use it?
JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology (“JDBC driver”) that is used with it. Below is a sample code which demonstrates how we can use the DatabaseMetaData
DatabaseMetaData md = conn.getMetaData();
System.out.println(“Database Name: ” + md.getDatabaseProductName());
System.out.println(“Database Version: ” + md.getDatabaseProductVersion());
System.out.println(“Driver Name: ” + md.getDriverName());
System.out.println(“Driver Version: ” + md.getDriverVersion());
The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. Below a sample code which demonstrates how we can use the ResultSetMetaData
ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM TABLE2”);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);
21. What is RowSet? or What is the difference between RowSet and ResultSet? or Why do we need RowSet? or What are the advantages of using RowSet over ResultSet?
RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset’s command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet. There are two clear advantages of using RowSet over ResultSet
RowSet makes it possible to use the ResultSet object as a JavaBeans component. As a consequence, a result set can, for example, be a component in a Swing application. RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object. 22. What is a connected RowSet? or What is the difference between connected RowSet and disconnected RowSet? or Connected vs Disconnected RowSet, which one should I use and when?
Connected RowSet –  A RowSet object may make a connection with a data source and maintain that connection throughout its life cycle, in which case it is called a connected rowset. A rowset may also make a connection with a data source, get data from it, and then close the connection. Such a rowset is called a disconnected rowset. A disconnected rowset may make changes to its data while it is disconnected and then send the changes back to the original source of the data, but it must reestablish a connection to do so. Example of Connected RowSet: A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver.
Disconnected RowSet – A disconnected rowset may have a reader (a RowSetReader object) and a writer (a RowSetWriter object) associated with it. The reader may be implemented in many different ways to populate a rowset with data, including getting data from a non-relational data source. The writer can also be implemented in many different ways to propagate changes made to the rowset’s data back to the underlying data source. Example of Disconnected RowSet: A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).
23. What is the benefit of having JdbcRowSet implementation? Why do we need a JdbcRowSet like wrapper around ResultSet?
The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet
This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object. 24. What is Java Collections API?
Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level
Reduces programming efforts. – Increases program speed and quality. Allows interoperability among unrelated APIs. Reduces effort to learn and to use new APIs. Reduces effort to design new APIs. Encourages & Fosters software reuse. To be specific, There are six collection java interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections.
25. What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
26. What is the difference between java.util.Iterator and java.util.ListIterator?
Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.
27. What is HashMap and Map?
Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.
28. Difference between HashMap and HashTable? Compare Hashtable vs HashMap?
Both Hashtable & HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls). HashMap does not guarantee that the order of the map will remain constant over time. But one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable. HashMap is non synchronized whereas Hashtable is synchronized. Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn’t. So this could be a design consideration. 29. What does synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
30. What is fail-fast property?
At high level – Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: “failing immediately and visibly” sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.
31. Why doesn’t Collection extend Cloneable and Serializable?
From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that’s backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn’t know the actual type of a Collection, it’s much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms
Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. Fail-fast is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown. 32. How can we make Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
33. Where will you use Hashtable and where will you use HashMap?
There are multiple aspects to this decision: 1. The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one. 2. If there is a possibility in future that – there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.
34. Difference between Vector and ArrayList? What is the Vector class?
Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences
Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2 Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector. ArrayList has no default size while vector has a default size of 10. The Enumerations returned by Vector’s elements method are not fail-fast. Whereas ArraayList does not have any method returning Enumerations. 35. What is the Difference between Enumeration and Iterator interface?
Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove(). Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator. 36. Why Java Vector class is considered obsolete or unofficially deprecated? or Why should I always use ArrayList over Vector?
You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That’s almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don’t need to. It’s a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList – the fact that Vector combines both the “resized array” collection implementation with the “synchronize every operation” bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don’t check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization – with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won’t be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class. (Read details Deprecate Hashtable and Vector)
37. What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
38. What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.
39. Where will you use Vector and where will you use ArrayList?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
40. What is the importance of hashCode() and equals() methods? How they are used in Java?
The java.lang.Object has two methods defined in it. They are – public boolean equals(Object obj) public int hashCode(). These two methods are used heavily when objects are stored in collections. There is a contract between these two methods which should be kept in mind while overriding any of these methods. The Java API documentation describes it in detail. The hashCode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.HashMap. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is “equal to” this one. The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn’t necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().
41. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.
42. What is java.util.concurrent BlockingQueue? How it can be used?
Java has implementation of BlockingQueue available since Java 1.5. Blocking Queue interface extends collection interface, which provides you power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic “bounded buffer” (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.
43. Set & List interface extend Collection, so Why doesn’t Map interface extend Collection?
Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun’s FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is “Key-value pairs”, but this provides a very limited (and not particularly useful) Map abstraction. You can’t ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There’s no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three “Collection view operations” on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That’s why we don’t have a map view operation on Lists.
44. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
Vector b. ArrayList c. LinkedList ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions. 45. What is the difference between ArrayList and LinkedList? (ArrayList vs LinkedList.)
java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:
ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier. ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there’s no fast way to access the Nth element of the list. Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node. Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. ArrayList may also have a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues. 46. Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList / LinkedList).
Below is a snippet from SUN’s site. The Java SDK contains 2 implementations of the List interface – ArrayList and LinkedList. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.
47. What is performance of various Java collection implementations/algorithms? What is Big ‘O’ notation for each of them ?
Each java collection implementation class have different performance for different methods, which makes them suitable for different programming needs.
Performance of Map interface implementations
Hashtable – An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.
HashMap –This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
TreeMap-The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.
LinkedHashMap-A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.
Performance of Set interface implementations
HashSet- The HashSet class offers constant-time [ Big O Notation is O(1) ] performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
TreeSet-The TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
LinkedHashSet-A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.
Performance of List interface implementations
LinkedList– Performance of get and remove methods is linear time [ Big O Notation is O(n) ] – Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]
ArrayList– The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. [ Big O Notation is O(1) ] – The add operation runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case (since the array must be resized and copied) adding n elements requires linear time [ Big O Notation is O(n) ] – Performance of remove method is linear time [ Big O Notation is O(n) ] – All of the other operations run in linear time [ Big O Notation is O(n) ]. The constant factor is low compared to that for the LinkedList implementation.
48. What is synchronization in respect to multi-threading in Java?
With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.
50. Explain different way of using thread?
A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
51. What is the difference between Thread.start() & Thread.run() method?
Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.
52. Why do we need run() & start() method both. Can we achieve it with only run method?
We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
53. What is ThreadLocal class? How can it be used?
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) 54. When InvalidMonitorStateException is thrown? Why?
This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
55. What is the difference between sleep(), suspend() and wait() ?
Thread.sleep() takes the current thread to a “Not Runnable” state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a “Not Runnable” state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.
Here is the sequence of operations you can think
A thread T1 is already running a synchronized block with a lock on object – lets say “lockObject” Another thread T2 comes to execute the synchronized block and find that its already acquired. Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread. T1 thread finishes all its synchronized block work. T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock. Since T2 thread is first in the queue of waiting it acquires the lock and starts processing. 56. What happens when I make a static method as synchronized?
Synchronized static methods have a lock on the class “Class”, so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access “same synchronized instance methods” at same time for different instances.
57. Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads,
public class Common {
public synchronized void synchronizedMethod1() {
System.out.println(“synchronizedMethod1 called”);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(“synchronizedMethod1 done”);
}
public void method1() {
System.out.println(“Method 1 called”);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(“Method 1 done”);
}
}
public class MyThread extends Thread {
private int id = 0; private Common common;
public MyThread(String name, int no, Common object) {
super(name);
common = object;
id = no;
}
public void run() {
System.out.println(“Running Thread” + this.getName());
try {
if (id == 0) {
common.synchronizedMethod1();
} else {  common.method1();  }
} catch (Exception e) { e.printStackTrace();  }
}
public static void main(String[] args) {
Common c = new Common();
MyThread t1 = new MyThread(“MyThread-1”, 0, c);
MyThread t2 = new MyThread(“MyThread-2”, 1, c);
t1.start();
t2.start();
}
}
Here is the output of the program
Running ThreadMyThread-1
synchronizedMethod1 called
Running ThreadMyThread-2
Method 1 called
synchronizedMethod1 done
Method 1 done
This shows that method1() – is called even though the synchronizedMethod1() was in execution.
58. Can two threads call two different synchronized instance methods of an Object?
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods
public class Common {
public synchronized void synchronizedMethod1() {
System.out.println(“synchronizedMethod1 called”);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“synchronizedMethod1 done”);
}
public synchronized void synchronizedMethod2() {
System.out.println(“synchronizedMethod2 called”);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“synchronizedMethod2 done”);
}
}
public class MyThread extends Thread {
private int id = 0;
private Common common;
public MyThread(String name, int no, Common object) {
super(name);
common = object;
id = no;
}
public void run() {
System.out.println(“Running Thread” + this.getName());
try {
if (id == 0) {
common.synchronizedMethod1();
} else {
common.synchronizedMethod2();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Common c = new Common();
MyThread t1 = new MyThread(“MyThread-1”, 0, c);
MyThread t2 = new MyThread(“MyThread-2”, 1, c);
t1.start();
t2.start();
}
}
59. What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other’s resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
When two threads call Thread.join() on each other. When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.
60. 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:
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. 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. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. 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.
61. How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?
Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
findMonitorDeadlockedThreads() – This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor. findDeadlockedThreads() – It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.
62. 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. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. 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.
63. How will you take thread dump in Java? How will you analyze Thread dump?
A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java process
Step 1On UNIX, Linux and Mac OSX Environment run below command:ps -el | grep javaOn Windows:Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process Step 2:Use jstack command to print the Java stack traces for a given Java process PIDjstack [PID]More details of jstack command can be found here : JSTACK Command Manual 64. What is a thread leak? What does it mean in Java?
Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.
66. How can I trace whether the application has a thread leak?
If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways
Give unique and descriptive names to the threads created in application. – Add log entry in all thread at various entry and exit points in threads. Change debugging config levels (debug, info, error etc) and analyze log messages. When you find the class that is leaking out threads check how new threads are instantiated and how they’re closed. Make sure the thread is Guaranteed to close properly by doing following – Handling all Exceptions properly. Make sure the thread is Guaranteed to close properly by doing following Handling all Exceptions properly. releasing all resources (e.g. connections, files etc) before it closes. 67. 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
Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead. You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool). Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.
68. Can we synchronize the run method? If yes then what will be the behavior?
Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object
69. Can we synchronize the constructor of a Java Class?
As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish
Serialization is a mechanism by which you can save or transfer the state of an object by converting it to a byte stream. This can be done in java by implementing Serialiazable interface. Serializable is defined as a marker interface which needs to be implemented for transferring an object over a network or persistence of its state to a file. Since its a marker interface, it does not contain any methods. Implementation of this interface enables the conversion of object into byte stream and thus can be transferred. The object conversion is done by the JVM using its default serialization mechanism.
70. Why is Serialization required? What is the need to Serialize?
Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object’s state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.
71. What is the Difference between Externalizable and Serializable Interfaces?
This is one of top serialization questions that is asked in many big companies to test your in-depth understanding of serialization. Serializable is a marker interface therefore you are not forced to implement any methods, however Externalizable contains two methods readExternal() and writeExternal() which must be implemented. Serializable interface provides a inbuilt serialization mechanism to you which can be in-efficient at times. However Externilizable interface is designed to give you greater control over the serialization mechanism. The two methods provide you immense opportunity to enhance the performance of specific object serialization based on application needs. Serializable interface provides a default serialization mechanism, on the other hand, Externalizable interface instead of relying on default Java Serialization provides flexibility to control this mechanism. One can drastically improve the application performance by implementing the Externalizable interface correctly. However there is also a chance that you may not write the best implementation, so if you are not really sure about the best way to serialize, I would suggest your stick to the default implementation using Serializable interface.
72. When will you use Serializable or Externalizable interface? and why?
Most of the times when you want to do a selective attribute serialization you can use Serializable interface with transient modifier for variables not to be serialized. However, use of Externalizable interface can be really effective in cases when you have to serialize only some dynamically selected attributes of a large object. Lets take an example, Some times when you have a big Java object with hundreds of attributes and you want to serialize only a dozen dynamically selected attributes to keep the state of the object you should use Externalizable interface writeExternal method to selectively serialize the chosen attributes. In case you have small objects and you know that most or all attributes are required to be serialized then you should be fine with using Serializable interface and use of transient variable as appropriate.
73. What are the ways to speed up Object Serialization? How to improve Serialization performance?
The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.
Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself. Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process. Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute. Use Externalizable interface and implement the readExternal and writeExternal methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes. 74. What is a Serial Version UID (serialVersionUID) and why should I use it? How to generate one?
The serialVersionUID represents your class version, and you should change it if the current version of your class is not backwards compatible with its earlier versions. This is extract from Java API Documentation
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
Most of the times, we probably do not use serialization directly. In such cases, I would suggest to generate a default serializable uid by clicking the quick fix option in eclipse.
75. What would happen if the SerialVersionUID of an object is not defined?
If you don’t define serialVersionUID in your serilizable class, Java compiler will make one by creating a hash code using most of your class attributes and features. When an object gets serialized, this hash code is stamped on the object which is known as the SerialVersionUID of that object. This ID is required for the version control of an object. SerialVersionUID can be specified in the class file also. In case, this ID is not specified by you, then Java compiler will regenerate a SerialVersionUID based on updated class and it will not be possible for the already serialized class to recover when a class field is added or modified. Its recommended that you always declare a serialVersionUID in your Serializable classes.
76. Does setting the serialVersionUID class field improve Java serialization performance?
Declaring an explicit serialVersionUID field in your classes saves some CPU time only the first time the JVM process serializes a given Class. However the gain is not significant, In case when you have not declared the serialVersionUID its value is computed by JVM once and subsequently kept in a soft cache for future use.
77. What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:
Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database. Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations. JSON Data Transfer – is recently popular data transfer format. A lot of web services are being developed in JSON due to its small footprint and inherent integration with web browser due to JavaScript format. 78. What are transient variables? What role do they play in Serialization process?
The transient keyword in Java is used to indicate that a field should not be serialized. Once the process of de-serialization is carried out, the transient variables do not undergo a change and retain their default value. Marking unwanted fields as transient can help you boost the serialization performance. Below is a simple example where you can see the use of transient keyword.
class MyVideo implements Serializable
{
private Video video;
private transient Image thumbnailVideo;
private void generateThumbnail()
{
// Generate thumbnail.
}
private void readObject(ObjectInputStream inputStream)
throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
generateThumbnail();
}
}
79. Why does serialization NOT save the value of static class attributes? Why static variables are not serialized?
The Java variables declared as static are not considered part of the state of an object since they are shared by all instances of that class. Saving static variables with each serialized object would have following problems
It will make redundant copy of same variable in multiple objects which makes it in-efficient. The static variable can be modified by any object and a serialized copy would be stale or not in sync with current value. 80. How to Serialize a collection in java? How to serialize a ArrayList, Hashmap or Hashset object in Java?
All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. All the commonly used collection classes like java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not really need to write anything specific to serialize collection objects. However you should keep following things in mind before you serialize a collection object – Make sure all the objects added in collection are Serializable. – Serializing the collection can be costly therefore make sure you serialize only required data isntead of serializing the whole collection. – In case you are using a custom implementation of Collection interface then you may need to implement serialization for it.
81. Is it possible to customize the serialization process? How can we customize the Serialization process?
Yes, the serialization process can be customized. When an object is serialized, objectOutputStream.writeObject (to save this object) is invoked and when an object is read, ObjectInputStream.readObject () is invoked. What most people do not know is that Java Virtual Machine provides you with an option to define these methods as per your needs. Once this is done, these two methods will be invoked by the JVM instead of the application of the default serialization process. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
82. How can a sub-class of Serializable super class avoid serialization? If serializable interface is implemented by the super class of a class, how can the serialization of the class be avoided?
In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it
class MySubClass extends SomeSerializableSuperClass {
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObjectNoData()
throws ObjectStreamException; {
throw new NotSerializableException(“Can not serialize this class”);
}
}
83. What changes are compatible and incompatible to the mechanism of java Serialization?
This is one of a difficult and tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:
Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled. The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream. Changing a transient field to a non-transient field is compatible change since it is similar to adding a field. Changing a static field to a non-static field is compatible change since it is also similar to adding a field. Some Simple Examples of incompatible changes are:
Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream. Deleting a existing Serializable fields will cause a problem. Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field. Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field. Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field. Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream. The classpath is the location where the Java Virtual Machine search for user-defined classes, packages and resources in any Java program. Below is a list of some java interview questions on CLASSPATH that may give you an edge over others in your next Java interview.
84. Why Java uses Classpath parameter or environment variables?
In a Java class import statements are used to access other classes. You also do a wild card import like org.fromdev.* on your java file. In such cases, It will become very impractical/slow for the Java Virtual Machine to search for classes in every file/folder on a machine, therefore you can provide the Java Virtual Machine with a list of places to look. This is done by putting folder and jar files on your classpath.
Environment variables in general are a set of dynamic name value pair that can be used by processes to decide the behavior based on a system. These are supported by all modern operating systems.
The CLASSPATH variable is a Java way to tell the possible locations of user classes or jar files for a Java application. Since each user/computer may choose to have classes in different location its best to have custom locations configured in Classpath variable.
In case you have not set the classpath environment variable, the default value is used as the “.” (current directory). That means, the current directory is searched.
85. When does Java read values of Classpath environment variable?
Java uses the CLASSPATH environment variable to read the classes and libraries from file system. This variable is used by all JDK Tools and Extension including Java Compiler (javac) and JRE(java) use this variable to locate the dependent user classes and jar files to perform specific tasks.
Java Compiler uses it to locate the dependent user classes and jar files to compile Java source files.
Java Run-time Environment (JRE) uses the classpath variable to identify the location of files to be loaded for the run-time dependencies (e.g. classes and jar files) of java program.
86. How to set Java Classpath on Windows, Unix, Linux and Mac?
Setting CLASSPATH on Windows XP
Follow below steps on Windows XP to set Java CLASSPATH
Right-click My Computer, and then click Properties. Click the Advanced tab.  Click Environment variables. Click one the following options, for either a user or a system variable Click New to add a new variable name and value. Enter Variable name as CLASSPATH enter all directories and jar files separated by semicolon. (e.g. c:\dir1;c:\dir2;c:\dir3\abc.jar) Setting CLASSPATH on Windows 7
Click Start Then right-click on Computer, select Properties  click Select Advanced System Settings tab. click the Environment Variables button. Setting CLASSPATH on Unix, Linux and Mac Use export command to set the CLASSPATH environment variable in your system. export CLASSPATH=/path/to/dir1:/path/to/dir2:path/to/abc.jar
87. How do I check the CLASSPATH variable is set in my machine?
Checking CLASSPATH on Windows
To check CLASSPATH variable is set on Microsoft Windows, run following command on command prompt
C:> echo %CLASSPATH%
If CLASSPATH variable is not set you will see %CLASSPATH% on windows system.
Checking CLASSPATH on Unix, Linux or Mac
To check CLASSPATH variable is set on Unix/Linux/Mac run following command on shell
$ echo $CLASSPATH
If CLASSPATH variable is not set you will see CLASSPATH: Undefined variable error on Unix/Linux/Mac systems.
88. How to set Multiple Jar Files in Java Classpath
Java versions Older then Java 6 does not support wildcard characters. Setting Multiple jars using wildcard in Java classpath are allowed in Java 6 and later versions.
For example, to specify all jar files in a directory “lib” the classpath entry should look like this  –>  lib/*
The wildcard entry (*) in classpath value will match only jar files NOT class files. To match both class files and JAR files in a same directory lib, you need to specify both values as shown below
Setting Multiple Jars in Classpath on Windows
Windows environment variable values are separated by semicolon, therefore you classpath entry would look like this
lib/*;lib
Setting Multiple Jars in Classpath on Unix, Linux or Mac
Unix environment variable values are separated by colon, therefore you classpath entry would look like this
lib/*:lib
Older version of Java
In older version of Java(older than Java 6), each jar file needs to be specified in the classpath. It can be a tedious and erroneous task if you are using many third party libraries.
89. What is the difference between NoClassDefFoundError and ClassNotFoundException? When NoClassDefFoundError and ClassNotFoundException are thrown?
NoClassDefFoundError and ClassNotFoundException are very closely related and often confused with each other by many developers. Below is the description of each from the Java API Specifications
ClassNotFoundException
Thrown when an application tries to load in a class through its string name using:
The forName method in class Class. The findSystemClass method in class ClassLoader. The loadClass method in class ClassLoader. but the definition of the class with the specified name could not be found due to following reasons
The specified name class does not exist. The specified name class is not in the classpath The specified name class is not visible to the classloader.
NoClassDefFoundError
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
Key Differences
The NoClassDefFoundError is thrown when the source was successfully compiled, but during runtime, the required class files were not found. This may be a case when some dependency jar files were not included or not in classpath.A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader or not visible to the Classloader. Another important distinction between these two is, NoClassDefFoundError is a sub class of java.lang.Error and the ClassNotFoundException is a subclass of java.lang.Exception. NoClassDefFoundError is a critical error for JVM since its having problems finding a class it expected to find.On the other hand, the ClassNotFoundException is an Exception. Use of reflection api can be error-prone and there is no compile-time check to validate reflection call is loading right classes, so there can be situations when some classes may not be found. Some scenario when ClassNotFoundException may occur
Scenario 1 (Use of reflection) – You will see ClassNotFoundException when you are using reflection to load classes at runtime, and the class you are trying to load does not exist or not in classpath.
Scenario 2 (Multiple Classloaders being used) – You will see ClassNotFoundException when a class is being loaded from another class which was already loaded in a parent classloader and the class from the child classloader is not visible.
90. How can we include Jar within a Jar in java classpath?
There is no easy way to do this in current java versions. There are 2 alternatives to deal with this problem using third party libraries
Use Jar class loader library
The JarClassLoader library provides you the feature of loading resources from a top JAR and from JARs inside the top JAR.
Explode and combine into one jar
Instead of trying to bundle jar file inside jar you can explode all required jars and re-bundle them as one jar using following two libraries
The first is One-Jar, which uses a special classloader to allow the nesting of jars. The second is UberJar, (or Maven Shade Plugin), which explodes the included libraries and puts all the classes in the top-level jar. 91. How to read a file from CLASSPATH in java?
This can be done in two simple ways
Using ClassLoader.getResourceAsStream –  This method can be used to load any file from CLASSPATH
InputStream in =this.getClass().getClassLoader().getResourceAsStream(“MyFile.txt”);
Using Class.getResourceAsStream –  This method can be used to load files using relative path to the package of the class
InputStream in =this.getClass().getResourceAsStream(“SomeTextFile.txt”);
This method can also be used to load any files from CLASSPATH by prefixing a “/”
92. How to find which jar file is being used by Java run-time?
On Windows –You need use below windows program Process Explorer that lets you see which files are open for a particular process or program
On Unix, Linux or Mac –It can be done using lsof command. lsof is one of my favorite and useful java debugging commands on Unix. Below is the syntax for using this command –  lsof -p [pid]
93. How to find the load location of a Java class file at run-time?
There are two ways to find it
Using Classloader
Below code snippet can be used to find the location of java class com.fromdev.MyClass this.getClass().getClassLoader().getResource(“com/fromdev/MyClass.class”)
Using Protection Domain
We can use this to find the exact location a jar file containing the class JVM is using
clazz.getProtectionDomain().getCodeSource().getLocation()
94. How Java handles Two classes with same name in classpath
If I have two classes with same name say MyClass.java in two different jar in my classpath which one will be picked up by JVM , is there anyway I can suggest JVM to pick a specific one ? Java interpreter loads classes based on the order they are specified in the CLASSPATH variable. For example, lets say this is your classpath variable value
C:\Project\Dir1;C:\Project\Dir2
The Java interpreter will first look for MyClass class in the directory C:\Project\Dir1. Only if it doesn’t find it in that directory it will look in the C:\Project\Dir2 directory.
95. How to Add A Jar File To Java Load Path At Run Time
This can done by use of URLClassloader. A sample implementation of this code is shown below
import java.net.URL;
import java.net.URLClassLoader;
public class SimpleJarLoader {
public static void main(String args[]) {
if (args.length < 2) {
System.out.println(“Usage: [Class name] [Jar Path]”);
return;
}
try {
System.out.println(“Trying to load the class…”);
Class.forName(args[0]);
} catch (Exception ex) {
System.out.println(“Not able to load class…” + args[0]);
}
try {
String url = “jar:file:/” + args[1] + “!/”;
URL urls[] = { new URL(url) };
URLClassLoader cl = new URLClassLoader(urls,
SimpleJarLoader.class.getClassLoader());
System.out.println(“Looking into jar… ” + url);
cl.loadClass(args[0]);
System.out.println(“Woohoo….I found it”);
} catch (Exception ex) {
System.out.println(“Oops…Still cant find the jar”);
ex.printStackTrace();
}
}
}
You can run this code by below command. (Make sure to use forward slash “/” as directory separator.)
java SimpleJarLoader org.springframework.core.SpringVersion C:/spring.jar
The output is like this
Trying to load the class…
Not able to load class…org.springframework.core.SpringVersion
Looking into jar… jar:file:/C:/spring.jar!/
Woohoo….I found it
96. Why calling System.setProperty() does not affect the classpath at run-time?
You can easily set any system properties in java using System.setPropoerty method, However it may not have any effect in case of CLASSPATH property. This is mainly because the Java system class loader is initialized very early in the JVM startup sequence. The class loader copies the classpath into its own data structures, and the classpath property is not read again. Therefore changing it after its already copied does not affect anything. There are mainly two reasons for this – First most important reason is security. You do not want a malicious code change the classpath at runtime and load some unwanted classes. Second reason is performance, since reading the classpath every-time its needed may not be efficient.
97. How to Add A Jar File To Java System Classpath At Run-time?
This can be done by using a simple reflection API hack as demonstrated in below sample code. This example assumes you have a file “c:/Sample.txt” that is not already in class path and at run-time c:/ is added the System classpath and then Sample.txt is made available.
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class HackJavaClasspath {
public static void addURL(URL url) throws Exception {
URLClassLoader cl = (URLClassLoader) ClassLoader
.getSystemClassLoader();
Class clazz = URLClassLoader.class;
Method method = clazz.getDeclaredMethod(“addURL”,
new Class[] { URL.class });
method.setAccessible(true);
method.invoke(cl, new Object[] { url });
}
public static void main(String[] args) throws Exception {
//Add c: to the classpath
addURL(new File(“c:/”).toURI().toURL());
//Now load the file from new location
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(“Sample.txt”);
System.out.println(in.available()); }
}
Running this java class prints the number of bytes available. This indicates the file is available for further processing.
98. How to get a list of resources from a directory in Java classpath?
You can use Reflections library for doing this. Reflections is a open source Java library. It scans Java classpath and indexes it with metadata. This library allows you to query the classpath at runtime and can be very handy for many run-time reflection code needs.
99. Web Application Scalability Questions and Answers for IT Architect
Web applications scalability is a common problem most of the web architect face. Any internet facing web application may require to be highly scalable due to heavy load of traffic. Now a days, developing a smart web application is much more than creating dynamic Web pages.
As the web is growing, our need of building larger and more scalable applications is also becoming more important. In this decade, lot of distributed web applications are being developed that can utilize the resources from multiple machines, by separating the application functionality into manageable group of tasks that can be deployed in a distribute systems. There are numerous benefits to dividing applications this way, some of the most important are reusability, scalability, and manageability.
100. What Do You Mean By High Availability?
Having better service capacity with high availability and low latency is mission critical for almost all businesses.
Availability means the ability of the application user to access the system, If a user cannot access the application, it is assumed unavailable. High Availability means the application will be available, without interruption.
Achieving high availability for a application is not always a easy task. Using redundant server nodes with clustering is a common way to achieve higher level of availability in web applications.  Availability is commonly expressed as a percentage of uptime in a given year.
101. What Is Scalability?
Scalability is the ability of a system, network, or process to handle a growing amount of load by adding more resources. The adding of resource can be done in two ways
Scaling Up-This involves adding more resources to the existing nodes. For example, adding more RAM, Storage or processing power.
Scaling Out-This involves adding more nodes to support more users.
Any of the approaches can be used for scaling up/out a application, however the cost of adding resources (per user) may change as the volume increases. If we add resources to the system It should increase the ability of application to take more load in a proportional manner of added resources.
An ideal application should be able to serve high level of load in less resources. However, in practical, linearly scalable system may be the best option achievable. Poorly designed applications may have really high cost on scaling up/out since it will require more resources/user as the load increases.
102. What Is A Cluster?
A cluster is group of computer machines that can individually run a software. Clusters are typically utilized to achieve high availability for a server software. Clustering is used in many types of servers for high availability.
App Server Cluster-An app server cluster is group of machines that can run a application server that can be reliably utilized with a minimum of down-time. Database Server Cluster-An database server cluster is group of machines that can run a database server that can be reliably utilized with a minimum of down-time. 103. Why Do You Need Clustering?
Clustering is needed for achieving high availability for a server software. The main purpose of clustering is to achieve 100% availability or a zero down time in service.
A typical server software can be running on one computer machine and it can serve as long as there is no hardware failure or some other failure.
By creating a cluster of more than one machine, we can reduce the chances of our service going un-available in case one of the machine fails.
Doing clustering does not always guarantee that service will be 100% available since there can still be a chance that all the machine in a cluster fail at the same time. However it in not very likely in case you have many machines and they are located at different location or supported by their own resources.
104. What Is Middle Tier Clustering?
Middle tier clustering is just a cluster that is used for service the middle tier in a application. This is popular since many clients may be using middle tier and a lot of heavy load may also be served by middle tier that requires it be to highly available.
Failure of middle tier can cause multiple clients and systems to fail, therefore its one of the approaches to do clustering at the middle tier of a application.
In java world, it is really common to have EJB server clusters that are used by many clients. In general any application that has a business logic that can be shared across multiple client can use a middle tier cluster for high availability.
105. What Is Load Balancing?
Load balancing is simple technique for distributing workloads across multiple machines or clusters. The most common and simple load balancing algorithm is Round Robin. In this type of load balancing the request is divided in circular order ensuring all machines get equal number of requests and no single machine is overloaded or underloaded.
The Purpose of load balancing is to
Optimize resource usage (Avoid overload and under-load of any machines.) Achieve Maximum Throughput Minimize response time Most common load balancing techniques in web based applications are
Round robin Session affinity or sticky session IP Address affinity What Is Sticky Session (session Affinity) Load Balancing? What Do You Mean By ‘session Affinity’?
Sticky session or a session affinity technique another popular load balancing technique that requires a user session to be always served by a allocated machine.
Why Sticky Session?
In a load balanced server application where user information is stored in session it will be required to keep the session data available to all machines. This can be avoided by always serving a particular user session request from one machine.
How It Is Done?
The machine is associated with a session as soon as the session is created. All the requests in a particular session are always redirected to the associated machine. This ensures the user data is only at one machine and load is also shared.In Java world, this is typically done by using jsessionid cookie. The cookie is sent to the client for the first request and every subsequent request by client must be containing that same cookie to identify the session.
What Are The Issues With Sticky Session?
There are few issues that you may face with this approach
The client browser may not support cookies, and your load balancer will not be able to identify if a request belongs to a session. This may cause strange behavior for the users who use no cookie based browsers. In case one of the machine fails or goes down, the user information (served by that machine) will be lost and there will be no way to recover user session.
What Is IP Address Affinity Technique For Load Balancing?
IP address affinity is another popular way to do load balancing. In this approach, the client IP address is associated with a server node. All requests from a client IP address are served by one server node.
This approach can be really easy to implement since IP address is always available in a HTTP request header and no additional settings need to be performed.
This type of load balancing can be useful if you clients are likely to have disabled cookies.
However there is a down side of this approach. If many of your users are behind a NATed IP address then all of them will end up using the same server node. This may cause uneven load on your server nodes.
NATed IP address is really common, in fact anytime you are browsing from a office network its likely that you and all your coworkers are using same NATed IP address.
106. What Is Fail Over?
Fail over means switching to another machine when one of the machine fails.
Fail over is a important technique in achieving high availability. Typically a load balancer is configured to fail over to another machine when the main machie fails.
To achieve least down time, most load balancer support a feature of heart beat check. This ensures that target machine is responding. As soon as a hear beat signal fails, load balancer stops sending request to that machine and redirects to other machines or cluster.
107. What Is Session Replication?
Session replication is used in application server clusters to achieve session failover. A user session is replicated to other machines of a cluster, every time the session data changes. If a machine fails, the load balancer can simply send incoming requests to another server in the cluster. The user can be sent to any server in the cluster since all machines in a cluster have copy of the session.
Session replication may allow your application to have session failover but it may require you to have extra cost in terms of memory and network bandwidth.
108. What Does Distributable Tag Means In Web.xml ?
In Java world, JEE applications use the concept of distributable web applications to provide session-failover and enable load balancing.
You can set a JEE application to support session replication by adding distributable tag in web.xml file.
<distributable />
109. What Are The Requirements For Making A Java EE Application Session Replication Enabled?
Setting distributable tag in web.xml just enables the application to support session replication, however it does not guarantee that your application will work fine in a session replicated environment.
JEE Application developer needs to make sure following things are taken care during web application development.
All attributes/objects that are saved in HTTP Session are serializable. This means all your custom objects and child objects of that should be serializable. Making changes to any session attribute should be done using session.setAttribute() method. If you have reference to a java object that was previously set in session, you must call session.setAttribute() method every time you make any change to the object. 110. What Are Different Mechanism Of Session Replication?
Session replication between multiple cluster nodes can be done in many ways. The best approach may depend on the type of application. However there are few common methods used by application server vendors.
Using session persistence, and saving the session to a shared file system (PersistenceManager + FileStore) . This will allow all machines in a cluster to be able to access the persisted session from the shared file system. Using session persistence, and saving the session to a shared database (PersistenceManager + JDBCStore) – This will allow all machines in a cluster to be able to access the persisted session from the shared database system. Using in-memory-replication, This will create a in memory copy of session in all the cluster nodes. 111. What Is CAP Theorem?
The CAP Theorem for distributed computing was published by Eric Brewer, This states that it is not possible for a distributed computer system to simultaneously provide all three of the following guarantees:
Consistency (all nodes see the same data even at the same time with concurrent updates ) Availability (a guarantee that every request receives a response about whether it was successful or failed) Partition tolerance (the system continues to operate despite arbitrary message loss or failure of part of the system) The CAP acronym corresponds to these 3 guarantees. This theorem has created the base for modern distributed computing approaches.   Worlds most high volume traffic companies (e.g. Amazon, Google, Facebook) use this as basis for deciding their application architecture.  Its important to understand that only two of these three conditions can be guaranteed to be met by a system.
112. What Is Sharding?
Sharding is a architectural approach that distributes a single logical database system into a cluster of machines.
Sharding is Horizontal partitioning design scheme. In this database design rows of a database table are stored separately, instead of splitting into columns (like in normalization and vertical partitioning). Each partition is called as a shard, which can be independently located on a separate database server or physical location.
Sharding makes a database system highly scalable. The total number of rows in each table in each database is reduced since the tables are divided and distributed into multiple servers. This reduces the index size, which generally means improved search performance.
The most common approach for creating shards is by the use of consistent hashing of a unique id in application (e.g. user id).
The downsides of sharding are,
It requires application to be aware of the data location. Any addition or deletion of nodes from system will require some rebalance to be done in the system. If you require lot of cross node join queries then your performance will be really bad. Therefore, knowing how the data will be used for querying becomes really important. A wrong sharding logic may result in worse performance. Therefore make sure you shard based on the application need. 113. What Is ACID Property Of A System?
ACID is a acronym which is commonly used to define the properties of a relational database system, it stand for following terms
Atomicity – This property guarantees that if one part of the transaction fails, the entire transaction will fail, and the database state will be left unchanged. Consistency – This property ensures that any transaction will bring the database from one valid state to another. Isolation – This property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially. Durable – means that once a transaction has been committed, it will remain so, even in the event of power loss. 114. What Is BASE Property Of A System?
BASE properties are the common properties of recently evolved NOSQL databases. According to CAP theorem, a BASE system does not guarantee consistency. This is a contrived acronym that is mapped to following property of a system in terms of the CAP theorem
Basically available indicates that the system is guaranteed to be available Soft stateindicates that the state of the system may change over time, even without input. This is mainly due to the eventually consistent model. Eventual consistency indicates that the system will become consistent over time, given that the system doesn’t receive input during that time. 115. What Do You Mean By Eventual Consistency? What Does Eventually Consistent Mean?
Unlike relational database property of Strict consistency, eventual consistency property of a system ensures that any transaction will eventually (not immediately) bring the database from one valid state to another.
This means there can be intermediate states that are not consistent between multiple nodes.
Eventually consistent systems are useful at scenarios where absolute consistency is not critical. For example in case of Twitter status update, if some users of the system do not see the latest status from a particular user its may not be very devastating for system.
Eventually consistent systems can not be used for use cases where absolute/strict consistency is required. For example a banking transactions system can not be using eventual consistency since it must consistently have the state of a transaction at any point of time. Your account balance should not show different amount if accessed from different ATM machines.
116. What Is Shared Nothing Architecture? How Does It Scale?
A shared nothing architecture (SN) is a distributed computing approach in which each node is independent and self-sufficient, and there is no single point of contention required across the system.
This means no resources are shared between nodes (No shared memory, No shared file storage) The nodes are able to work independently without depending on each other for any work. Failure on one node affects only the users of that node, however other nodes continue to work without any disruption. This approach is highly scalable since it avoid the existence of single bottleneck in the system. Shared nothing is recently become popular for web development due to its linear scalability. Google has been using it for long time.
In theory, A shared nothing system can scale almost infinitely simply by adding nodes in the form of inexpensive machines.
117. How Do You Update A Live Heavy Traffic Site With Minimum Or Zero Down Time?
Deploying a newer version of a live website can be a challenging task specially when a website has high traffic. Any downtime is going to affect the users. There are a few best practices that we can follow
Before deploying on Production
Thoroughly test the new changes and ensure it working in a test environment which is almost identical to production system. If possible do automation of test cases as much as possible. We use selenium for a lot of functional testing. Create a automated sanity testing script (also called as smoke test) that can be run on production (without affecting real data). These are typically readonly type of test cases. However depending on your application needs you can add more cases to this. Make sure it can be run quickly by keeping it short. Create scripts for all manual tasks(if possible), avoiding any hand typing mistakes during day of deployment. Test the script to make sure they work on a non-production environment. Keep the build artifacts ready. e.g application deployment files, database scripts, config files etc. Create a checklist of things to do on day of deployment. Rehearse. Deploy in a non-prod environment is almost identical to production. Try this with production data volumes(if possible). Make a note of time required for your tasks so you can plan accordingly.When doing deploying on a production environment. Keep backup of current site/data to be able to rollback. Use sanity test cases before doing a lot of in depth testing.
0 notes
techgroup-sixwares-blog · 7 years ago
Link
0 notes