1. What is the difference between hashmap and hashtable?
hashtable is synchronized.
hashmap is not synchronized.
hashtable doesnot allow null keys or null values.
hashmap allows 1 null key and multiple null value.
2.What is fail fast and fail safe in java?
Fail fast : if we use iterator to iterate through the collection, in a multithreaded environment, if one thread is iterating the collection and other thread modifies the collection, then it throws concurrent modification Exception.So it fails fast.
Fail-safe: If we use the concurrent collections , like CopyOnWriteArrayList , BlockingQueue , ConcurrentHashMap it will not throw ConcurrentModificationException even though if we try to modify the collection when it is getting iterated.
Fail-safe Collections works with a copy of collection i.e clone of a collection so even if try to modify the collection i.e concurrent hashmap,then it will not throw concurrentmodification exception.
3.What is serialization in java?
Serialization is the process of storing the state of an object into an external System,to do that we need to convert the object into byte array.Serializable is a marker interface. which flags the jvm the objects of the serializable class to save the state of the object into a external system.
4.What is externalizable and serializable?
java.io.externalizable and java.io.serializable both are used to serialize an object and to save the state of the object into a database or a file.In earlier versions of jvm, the reflection was very slow and to handle the situation, java was provided with the java.io.externalizable interface.
This provides 2 methods : readExternal() and writeExternal() which we need to implement. we need to implement the marshalling and unmarshalling logic in these methods.This gives a workarround to performance to reflection problem.but modern jvms gives lot of performance when compared to previous JVMs.so no need to use externalizable interface.also , JBOSS provides third party serialization which is very quick when compared to default serialization.
One drawback of externalization is u need to maintain the logic of serialization. once a new field is added to the class , the object of which is getting serialized, then you need to add those fields in your readExternal() and writeExternal() interface.
The following code lines illustrate how to write MyObject (or any serializable object) to a file or disk.
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyObject.ser"));
out.writeObject(object);
out.close();
// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
//read it from the disc
try{
FileInputStream door = new FileInputStream("name_of_file.sav");
ObjectInputStream reader = new ObjectInputStream(door);
MyObject x = new MyObject();
x = (MyObject) reader.nextObject();
}catch (IOException e){
e.printStackTrace();
}
5.What is a Threadpool?
Its a pool of threads, which can be reused instead of creating large number of threads in an application we can reuse the threads by maintaining a finite number of threads in a pool of threads.
6.if you want to create an application with number of users want to access at the same time what will u do?
Create a pool of threads.and assign it to each users.
7.what is executor in Java?
Executor is an interface in java.In large scale applications it makes sense to separate thread management from the thread creation.So we use executor Interface.Executor interface has only one method execute(r). execute(Runnable r) method takes only one object.
If e is an executor object then we can call e.execute(r) which does the same thing as [ {new Thread(r)} . start();] this is asynchronous so executes the given command(runnable object) sometimes in future.
8.What is the difference b/w Concurrent collections and Synchonized collections?
We use Collections.SynchronizedMap() to synchronize the collections. These are synchronized collections. but java 5 provides some of the concurrent collections like ConcurrentHashMap, BlockingQueue and CopyOnwriteArrayList.
It synchronizes a portion of arraylist or map , based on the concurrency level,so its performance is higher.however the hashtable provides better thread safety on a cost of performance.
9.What happens to java generics at runtime?
The main advantage of generics is for type casting, type safety, type checks, the information of generics is lost at runtime. The impossibility to inspect generic-types at runtime, because they had to be implemented with Type Erasure. One way to handle this is to store the Type information in seperate class, like we have java.lang.reflect.Type; using this we can create a separate class and store the Type info.
10.what is the life cycle of a servlet?
Container loads the sevlet into the jvm, It creates the Class object of the Servlet and calls the getInstance() method on the class object which calls the private constructor of the class there by creating an instance, and using that it instantiates the servlet by calling init() method , Every Servlet has to call this init() method, you can implement init() method, to initialize a resource like getting the database Connection,open a file(All one time task can be performed using init()), or you dont have to implement init(ServletConfig) method in your servlet class .init(ServletConfig) takes one parameter , i.e Servlet Config, which is used to pass the initial parameters to the servlet ,from web.xml Then it calls the Service(ServletRequest,ServletResponse) of Generic Servlet, which then calls the overriden Service(ServletReq, ServletRes) from HTTPServlet class , which then calls the protected Service(Httpreq,Httpres) this has a req.getMethod() which returns the method is post/get .
protected Service(Httpreq,Httpres){
req.getMethod();
}
using this info either doget() or doPost() method is called, so once this is finishes the execution, the
destroy() method is called which releases the resources acquired in init() method.
11.How does hashmap works in java?
Hashmap works on hashing mechanism.Hashing mechanism is a way of assigning a unique code to an object by applying some formula to the members of that object.Hashmap has a inner class Entry which impements Map.Entry.which has a final key, a value, next and hash.The instance of this Entry class is stored in an array.Now 2 unequal objects may have same hashcode. then how it(put(key,value)) will determine the location to store the object?
That's why we have next pointer. It is stored in a linkedlist(linked list is inside the arrayindex, which is nothing but a hash bucket) inside the Array. it traverses through the linked list and gets the null position of the linked list.Because there may be already some objects which r having same hashcode might have been saved in the same bucket i.e same array index.So Linked list is traversed and the new unequal object with same hashcode is placed in the null position.
When you give key to retrieve the object get(key) hashmap uses keys hashcode to retrieve the value.
if 2 object has same hashcode they have 2 objects in the same bucket. thats when we use equals() to compare the contents of the objects and return the correct object.
12.What happens On HashMap in Java if the size of the HashMap exceeds a given treshhold defined by load factor ?
Resizing happens and race condition occurs when one thread is trying to resize and refill more new buckets as in arraylist it does, putting all the old values in the new buckets, the other thread also tries to resize it by putting the old contents into new buckets.This process is called rehashing. while rehashing it may leads to race condition.
13.Why String, Integer and other wrapper classes are considered good keys ?
They are immutable, they are final and returns the same hashcode always .They have implemented equals() and hashcode(). They are threadsafe.
hashtable is synchronized.
hashmap is not synchronized.
hashtable doesnot allow null keys or null values.
hashmap allows 1 null key and multiple null value.
2.What is fail fast and fail safe in java?
Fail fast : if we use iterator to iterate through the collection, in a multithreaded environment, if one thread is iterating the collection and other thread modifies the collection, then it throws concurrent modification Exception.So it fails fast.
Fail-safe: If we use the concurrent collections , like CopyOnWriteArrayList , BlockingQueue , ConcurrentHashMap it will not throw ConcurrentModificationException even though if we try to modify the collection when it is getting iterated.
Fail-safe Collections works with a copy of collection i.e clone of a collection so even if try to modify the collection i.e concurrent hashmap,then it will not throw concurrentmodification exception.
3.What is serialization in java?
Serialization is the process of storing the state of an object into an external System,to do that we need to convert the object into byte array.Serializable is a marker interface. which flags the jvm the objects of the serializable class to save the state of the object into a external system.
4.What is externalizable and serializable?
java.io.externalizable and java.io.serializable both are used to serialize an object and to save the state of the object into a database or a file.In earlier versions of jvm, the reflection was very slow and to handle the situation, java was provided with the java.io.externalizable interface.
This provides 2 methods : readExternal() and writeExternal() which we need to implement. we need to implement the marshalling and unmarshalling logic in these methods.This gives a workarround to performance to reflection problem.but modern jvms gives lot of performance when compared to previous JVMs.so no need to use externalizable interface.also , JBOSS provides third party serialization which is very quick when compared to default serialization.
One drawback of externalization is u need to maintain the logic of serialization. once a new field is added to the class , the object of which is getting serialized, then you need to add those fields in your readExternal() and writeExternal() interface.
The following code lines illustrate how to write MyObject (or any serializable object) to a file or disk.
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyObject.ser"));
out.writeObject(object);
out.close();
// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
//read it from the disc
try{
FileInputStream door = new FileInputStream("name_of_file.sav");
ObjectInputStream reader = new ObjectInputStream(door);
MyObject x = new MyObject();
x = (MyObject) reader.nextObject();
}catch (IOException e){
e.printStackTrace();
}
5.What is a Threadpool?
Its a pool of threads, which can be reused instead of creating large number of threads in an application we can reuse the threads by maintaining a finite number of threads in a pool of threads.
6.if you want to create an application with number of users want to access at the same time what will u do?
Create a pool of threads.and assign it to each users.
7.what is executor in Java?
Executor is an interface in java.In large scale applications it makes sense to separate thread management from the thread creation.So we use executor Interface.Executor interface has only one method execute(r). execute(Runnable r) method takes only one object.
If e is an executor object then we can call e.execute(r) which does the same thing as [ {new Thread(r)} . start();] this is asynchronous so executes the given command(runnable object) sometimes in future.
8.What is the difference b/w Concurrent collections and Synchonized collections?
We use Collections.SynchronizedMap() to synchronize the collections. These are synchronized collections. but java 5 provides some of the concurrent collections like ConcurrentHashMap, BlockingQueue and CopyOnwriteArrayList.
It synchronizes a portion of arraylist or map , based on the concurrency level,so its performance is higher.however the hashtable provides better thread safety on a cost of performance.
9.What happens to java generics at runtime?
The main advantage of generics is for type casting, type safety, type checks, the information of generics is lost at runtime. The impossibility to inspect generic-types at runtime, because they had to be implemented with Type Erasure. One way to handle this is to store the Type information in seperate class, like we have java.lang.reflect.Type; using this we can create a separate class and store the Type info.
10.what is the life cycle of a servlet?
Container loads the sevlet into the jvm, It creates the Class object of the Servlet and calls the getInstance() method on the class object which calls the private constructor of the class there by creating an instance, and using that it instantiates the servlet by calling init() method , Every Servlet has to call this init() method, you can implement init() method, to initialize a resource like getting the database Connection,open a file(All one time task can be performed using init()), or you dont have to implement init(ServletConfig) method in your servlet class .init(ServletConfig) takes one parameter , i.e Servlet Config, which is used to pass the initial parameters to the servlet ,from web.xml Then it calls the Service(ServletRequest,ServletResponse) of Generic Servlet, which then calls the overriden Service(ServletReq, ServletRes) from HTTPServlet class , which then calls the protected Service(Httpreq,Httpres) this has a req.getMethod() which returns the method is post/get .
protected Service(Httpreq,Httpres){
req.getMethod();
}
using this info either doget() or doPost() method is called, so once this is finishes the execution, the
destroy() method is called which releases the resources acquired in init() method.
11.How does hashmap works in java?
Hashmap works on hashing mechanism.Hashing mechanism is a way of assigning a unique code to an object by applying some formula to the members of that object.Hashmap has a inner class Entry which impements Map.Entry.which has a final key, a value, next and hash.The instance of this Entry class is stored in an array.Now 2 unequal objects may have same hashcode. then how it(put(key,value)) will determine the location to store the object?
That's why we have next pointer. It is stored in a linkedlist(linked list is inside the arrayindex, which is nothing but a hash bucket) inside the Array. it traverses through the linked list and gets the null position of the linked list.Because there may be already some objects which r having same hashcode might have been saved in the same bucket i.e same array index.So Linked list is traversed and the new unequal object with same hashcode is placed in the null position.
When you give key to retrieve the object get(key) hashmap uses keys hashcode to retrieve the value.
if 2 object has same hashcode they have 2 objects in the same bucket. thats when we use equals() to compare the contents of the objects and return the correct object.
12.What happens On HashMap in Java if the size of the HashMap exceeds a given treshhold defined by load factor ?
Resizing happens and race condition occurs when one thread is trying to resize and refill more new buckets as in arraylist it does, putting all the old values in the new buckets, the other thread also tries to resize it by putting the old contents into new buckets.This process is called rehashing. while rehashing it may leads to race condition.
13.Why String, Integer and other wrapper classes are considered good keys ?
They are immutable, they are final and returns the same hashcode always .They have implemented equals() and hashcode(). They are threadsafe.
Very helpful information. Thanks for sharing.
ReplyDelete