Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday, 13 July 2013

Java Interview Question chapterwise

KEY JAVA INTERVIEW QUESTION

 1. What is immutable object? Can you write immutable object?
You need to make 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.

2. Does all property of immutable object needs to be final?
Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new () and literal?
When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.


String s = new String("Test");
will put the object in String pool , it it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" it put the String in pool.


4. How does substring () inside String works?
Another good question, I think answer is not sufficient but here it is “Substring creates new object out of string by taking a portion of original string”.


suggested by Anand and Anonymous


The substring() method is used to return a part (or substring) of the String used to invoke the method. The first argument represents the starting location (zero-based) of the substring. If the call has only one argument, the substring returned will include the characters to the end of the original String. If the call has two arguments, the substring returned will end with the character located in the nth position of the original String where n is the second argument. Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last character in the returned String will be in the original String’s 7 position, which is index 6. Let’s look at an example:
String x = "0123456789";

System.out.println( x.substring(5) ); // output is "56789"
System.out.println( x.substring(5, 8)); // output is "567"

The first example should be easy: start at index 5 and return the rest of the String. The second example should be read as follows: start at index 5 and return the characters up to and including the 8th position (index 7).



and @Anonymous pointed out some interesting fact:
omething important about String.substring() method, its implementation calls the following String(...) constructor :

// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}

That means the new String() object returned by substring(...) shares the same backing array (this.value) as the original string object.

Thus if your original string object is 1GB long, the substring object will always be 1GB long too!

You will probably want to trim the new array size to the substring range, this should do the job:

String veryLongString = readFromFile(file);
String tinyString = new String(veryLongString.substring(1,10));

The String(String) constructor is implemented that way:

public String(String original) {
...
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
}
...
}



5. Which two method you need to implement for key in hashMap ?
(equals and hashcode) read How HashMap works in Java for detailed explanation.

6. Where does these  two method comes in picture during get operation?
See here  How HashMap works in Java for detailed explanation.

7. How do you handle error condition while writing stored procedure or accessing stored procedure from java?
Open for all, my friend didn't know the answer so he didn't mind telling me.

8. What is difference between Executor.submit() and Executer.execute() method ?
(Former returns an object of Future which can be used to find result from worker thread)


@vinit Saini suggesed a very good point related to this core java interview question


There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.

9. What is the difference between factory and abstract factory pattern?
Open for all, he explains about factory pattern and how factory pattern saves maintenance time by encapsulating logic of object creation but didn't know exact answer


@Raj suggested
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.


10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
see my article 10 Interview questions on Singleton Pattern in Java

11. Can you write Critical section code for singleton?
check here  10 Interview questions on Singleton Pattern in Java

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.

13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java

14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here  How HashMap works in Java for detailed explanation.

15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.


19. Give a simplest way to find out the time a method takes for execution without using any profiling tool?
this questions is suggested by @Mohit
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code…

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println (“Time taken for execution is ” + (end – start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing


=========================================================================
1. can static methods be overloaded?

2. can ther be 2 main methods ... i.e one with argument String[] srgs and other with int[] args...is this possible?

3. static class tim
{
int a;
static
{
int a=20;
}
public static void main(String args[])
{
tim t=new tim();
t.a=10;
S.O.P(""+a);
}
}

what is the output why?
-----------------------------------------------------------------------------------------------------------------------------
1.How can two threads access a synchronized block simultaneuously i.e. one thread should give the chance for other thread to execute synchronized block even before this thread finishes the execution of the same synchronized block?
ans: If first thread that is executing synchronized block calls wait(), than it releases lock, so second thread will get chance to execute that synchronized block.
Remember: If first thread will call sleep(), it does not release lock so second thread will not enter in that block for sleep() case.

2.What are the diffferent ways in which you can create a thread?
ans:
1)-extending Thread class
2)-implementing Runnable Interface

3.If you need to restrict creation of objects of a class to one, how do you do ensure this happens? What are the different ways?
ans: Singleton design pattern is used. Constructor in made private, clone() is overriden. Private Instance is created early and a static method is provided to return this instance always.
class Singleton{
private Singleton INSTANCE=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}

protected Object clone(){}
}

4. Can a class have private or protected modifer? Give supporting answer where you can have and where you cant.
ans:
Yes a class can have private and protected modifier provided that class should be inner class.
class Outer{
private class Inner{}
}

5. One source file can have only one public class declared in it? True/False? Give the reason.
ans: true.
Reason: To make java efficient, it is a design issue.
The compiler would have to make an additional pass through all the compilation units (.java files) to figure out what classes were where, and that would make the compilation even slower.

6. Explain how is Java secure? Where all the security is handled?

7.Is applet secure? Give supporting answer.

8. Why is Java called "purely" object oriente language. Give gun shot answer.
ans: As for performing any thing we have to make class and think in term of object.

9. What is maximum size of an identifier in java?
ans: 8 bytes or 64 bits, long and double.
10. Does java work on "Pass by reference" or "Pass by value"?
ans: pass by value

11.Is it compulsory that the source file should have the same name as the class which contains main() method? Give explanation of when you are forced to have the same name?
ans:No it is not necessary.

12.Java's semantics is similar to SmallTalk language or C++?
ans: c++

13. What is the difference between Compile time polymorphism and dynamic polymorphism? Give explanation.
ans: Compile time polymorphism is applied to overloading and solved by compiler, compiler decides which method should be called based on the signature of the method.
Dynamic polymorphism means overriding and solved by jvm, jvm decided which object's method to call at runtime based on the actual object type.

14. Java removed multiple inheritance concept. What are the problems with it?
ans: In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. Mainly to avoid Diamond Problem they did not support this concept.

15. How is responsbile for loading classes in Java? Can you load classes available in network resources?

16.For each main() method a new stack is created. True/False?
ans: true. new stack is created for every method.

17. Are eight primitive types (int, byte, short, char, float, double, long, boolean) objects?
ans: no

18. What is the different b/w creation of a String variable and String object? Where is the memory alloacted for each one of them?
String str=new String("100,200");
String str1={"100",200"};
ans:
String str=new String("100,200");
this created two String objects in memory.
first: first string object is created in memory when .java file is compiled into .class file. and reference of this Object is stored in String constant pool.
second: second object is created in memory when the code is run.

String str1={"100",200"}; only one object is created here at compile time and object reference in stored in String constant pool.

18. What kind of class is 'Integer' ?
ans: final class and wrapper class.

19. What method does Garbage collector invoke to remove the objects that has no references.
ans: finalize() method.

20. What is name spoofing? How do we eliminate?
--------------------------------------------------------------------------------------------------------------
How HashMap  works in Java
How HashMap works in Java or sometime how get method work in HashMap is common questions on Java interviews now days. Almost everybody who worked in Java knows about HashMap, where to use HashMap or difference between Hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth it offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement 


"Have you used HashMap before" or  "What is HashMap? Why do we use it “
Almost everybody answers this with yes and then interviewee keep talking about common facts about HashMap like HashMap accept null while Hashtable doesn't, HashMap is not synchronized, HashMap is fast and so on along with basics like its stores key and value pairs etc. This shows that person has used HashMap  and quite familiar with the functionality HashMap  offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in HashMap . Interview here you and come back with questions like

"Do you Know how HashMap works in Java” or "How does get () method of HashMap works in Java"
And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put() and get() method for storing and retrieving data from HashMap. When we pass an object to put() method to store it on HashMap, HashMap implementation calls hashcode() method HashMap  key object and by applying that hashcode on its own hashing function it identifies a bucket location for storing value object , important part here is HashMap  stores both key and value object in bucket which is essential to understand the retrieving logic. If people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap  . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap  works in Java. But this is just start of story and confusion increases when you put interviewee on scenarios every Java developers faced day by day basis. Next question could be about collision detection and collision resolution in Java HashMap  e.g. 

"What will happen if two different objects have same hashcode?”
Now from here confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap  will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList. Great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap  does follow this. But story does not end here and interview asks

"How will you retrieve if two different objects have same hashcode?”
how HashMap works internally in JavaInterviewee will say we will call get() method and then HashMap  uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't  have value object to compare ,So until they know that HashMap  stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap . Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashCode () and equals () and keys and values object in HashMap  which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap . Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap  keys and improve performance of Java HashMap  by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer provided by Java Collection API are very good HashMap  keys.

Now if you clear this entire java HashMap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the HashMap  exceeds a given threshold defined by load factor ?". Until you know how HashMap  works exactly you won't be able to answer this question. If the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java HashMap  does that by creating another new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location. 

If you manage to answer this question on HashMap  in java you will be greeted by "do you see any problem with resizing of HashMap  in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java HashMap  and potentially looking for race condition on HashMap  in Java

So the answer is Yes there is potential race condition exists while resizing HashMap  in Java, if two thread at the same time found that now Java HashMap  needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java HashMap  doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap  in multi-threaded environment to interviewer :)

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap  questions has verified
Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () and there importance in HashMap?
Benefit of immutable object?
Race condition on HashMap  in Java
Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions

How HashMap  works in Java
HashMap  works on principle of hashing, we have put () and get () method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.
Also HashMap  stores both key+value tuple in every node of linked list.

What will happen if two different HashMap  key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap .

In terms of usage HashMap  is very versatile and I have mostly used HashMap  as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap  comes as very handy there. You can also check following articles form Javarevisited to learn more about HashMap and Hashtable in Java :

Why Java Object Oriented?
To be truly considered "object oriented", a programming language should support at a minimum four characteristics:

* [b]Encapsulation[/b]--implements information hiding and modularity (abstraction)

* Polymorphism--the same message sent to different objects results in behavior that's dependent on the nature of the object receiving the message

* Inheritance--you define new classes and behavior based on existing classes to obtain code re-use and code organization

* Dynamic binding--objects could come from anywhere, possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. Dynamic binding provides maximum flexibility while a program is executing

What is the difference between Synchronized Collection classes and Concurrent Collection Classes ? When to use what ?

Collections classes are heart of java API though I feel using them judiuously is an art.its my personal experience where I have improved performance by using ArrayList where legacy codes are unnecesarily used Vector etc.

JDK 1.5 introduce some good concurrent collections which is highly efficient for high volume , low latency system.

The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List.
However, several factors make them unsuitable for use in highly concurrent applications -- their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationExceptions.

The ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.

So what is the difference between hashtable and ConcurrentHashMap , both can be used in multithreaded environment but once the size of hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap indroduced concept of segmentation , how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.

Read more: http://javarevisited.blogspot.com/2010/10/what-is-difference-between-synchronized.html#ixzz20VsDmjKu
 

10 Example of Hashtable in Java – Java Hashtable Tutorial

These Java hashtable Examples contains some of the frequently used operations on hastable in Java. when I discussed throw of How HashMap or Hashtable works in Java I touched based on inner working of hastable, while in this java hashtable tutorial we will see some examples of hashtable in Java like checking a key exits in hashmap or not or getting all keys and values from HashMap , Iterating on hashtable keys and values using Enumeration etc.

Hashtable Examples in Java

Java hashtable examples and sample codeBefore using Hashtable is worth remembering that it’s an obsolete collection and there are better alternatives available in form of HashMap and ConcurrentHashMap. You can also see Difference between Hashtable and HashMap for comparing each other. Examples of hashtable is not very different than hashmap or ConcurrentHashMap and put() and get() almost work same except some synchronization difference e.g. on ConcurrentHashMap get() and put() can overlap but on hashtable they can’t because whole map gets locked on either operation. On the other hand since hashmap is not synchronized at all using it on concurrent java application is not advised.


10 Java Hashtable Examples:

Now let’s move on Hashtable examples in Java following is a list of all examples of hashtable operation we will see in this article:

1. How to put object into Hashtable?
2. How to retrieve object from Hashtable in Java?
3. How to reuse Hashtable by using clear()?
4. How to check if Hastable contains a particular value?
5. How to check if Hashtable contains a particular key?
6. How to traverse Hashtable in Java?
7. How to check if Hashtable is empty in Java?
8. How to Copy content of Hashtable into HashMap?
9. How to find size of Hashtable in Java?
10. How to get all values form hashtable in Java?
11. How to get all keys from hashtable in Java?


Here is complete code example of all above hashtable example or exercises:

import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;

public class HashtableDemo {

public static void main(String args[]) {

// Creating Hashtable for example
Hashtable companies = new Hashtable();


// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");


// Java Hashtable example to get Object from Hashtable
// get(key) method is used to retrieve Objects from Hashtable
companies.get("Google");


// Hashtable containsKey Example
// Use containsKey(Object) method to check if an Object exits as key in
// hashtable
System.out.println("Does hashtable contains Google as key: "
+ companies.containsKey("Google"));


// Hashtable containsValue Example
// just like containsKey(), containsValue returns true if hashtable
// contains specified object as value
System.out.println("Does hashtable contains Japan as value: "
+ companies.containsValue("Japan"));


// Hashtable enumeration Example
// hashtabl.elements() return enumeration of all hashtable values
Enumeration enumeration = companies.elements();

while (enumeration.hasMoreElements()) {
System.out
.println("hashtable values: " + enumeration.nextElement());
}


// How to check if Hashtable is empty in Java
// use isEmpty method of hashtable to check emptiness of hashtable in
// Java
System.out.println("Is companies hashtable empty: "
+ companies.isEmpty());


// How to find size of Hashtable in Java
// use hashtable.size() method to find size of hashtable in Java
System.out.println("Size of hashtable in Java: " + companies.size());


// How to get all values form hashtable in Java
// you can use keySet() method to get a Set of all the keys of hashtable
// in Java
Set hashtableKeys = companies.keySet();


// you can also get enumeration of all keys by using method keys()
Enumeration hashtableKeysEnum = companies.keys();


// How to get all keys from hashtable in Java
// There are two ways to get all values form hashtalbe first by using
// Enumeration and second getting values ad Collection

Enumeration hashtableValuesEnum = companies.elements();


Collection hashtableValues = companies.values();


// Hashtable clear example
// by using clear() we can reuse an existing hashtable, it clears all
// mappings.
companies.clear();
}
}


Output:
Does hashtable contains Google as key: true
Does hashtable contains Japan as value: true
hashtable values: Finland
hashtable values: United States
hashtable values: Japan
Is companies hashtable empty: false
Size of hashtable in Java: 3

That’s all on Hashtable Example in Java. We have seen almost all frequently used hashtable operations in java. As I said earlier don’t use Hashtable as its pretty old and there are better alternatives available like ConcurrentHashMap until it’s absolutely necessary for you.


Read more: http://javarevisited.blogspot.com/2012/01/java-hashtable-example-tutorial-code.html#ixzz20VsOOpBY

I looked at the System class and this is what it says about the method gc():

Runtime.exit(int)

gc

public static void gc()

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()


See Also:
Runtime.gc()
I have read documents which say
1.garbage collection cannot be forced..
2.System.gc initiates garbage collection...

Are'nt these contradictory..which one of these is correct?

Answer
1.
Both of your arguments are right.
Garbage collection cannot be forced.
Because in java whenever any object has no reference in memory,then the space that object occupies is reclaimed automatically by System .gc i.e you do not have to call system.gc explicitely, it is called implicitely by java

2.
Garbage collection cannot be forced. This indicates that Garbage Collector is an independent thread and is on a priority which is decided by the Java Virtual Machine, so you may not enforce Garbage Collection.
What Calling the System.gc method suggests is that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Does that mean one cannot explicitly call System.gc in his program?

Will it be invoked by JVm periodically?


You can always call System.gc() as a normal method call. But, This does not guarantee that the Garbage Collection thread will clean up memory chunks which are no longer required. The execution of the Garbage Collector Thread for collecting the discarded objects is with the JVM, and JVM periodically infact on a as and when required basis cleans up the same.



There are lots of points to be cleared on thisi topic so please read this carefully & try to understand teh exact use of system.gc::::

Some points to keep in mind are::

1.]calling System.gc() doesn't guarantee you that the GC will get performed. So if your program is dependent on a GC happening, then you're right -- and your program probably isn't coded so well.

But say your program is prety computationally intensive. But there's a few points when it slows down a bit (and kind of takes a breath if you know what I mean). It might be a really good idea to call System.gc() at those points where the system is less busy and kind of suggest to the garbage collector "Hey -- if you do your thing now, you'll be able to get it done!" Whereas if you don't put those System.gc() calls at the slower points in your code... the system may decide to do a GC at some really inopportune times and really slow down your program when its just not convenient.
 

How Garbage Collection works in Java



I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article or you call tutorial about How Garbage Collection works in Java or what is Garbage collection in Java in simple word which would be easy to understand and have sufficient information to understand how garbage collection works in Java.

Garbage collection in Java TutorialThis article is  in continuation of my previous articles How Classpath works in Java and How to write Equals method in java and  before moving ahead let's recall few important points about garbage collection in java:

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.


When an Object becomes Eligible for Garbage Collection

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.

Heap Generations for Garbage Collection in Java

Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java

Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

JVM Parameters for garbage collection in Java

Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding of garbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html

Full GC and Concurrent Garbage Collection in Java

Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java.

Read more: http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz20VsxfmGx 
 

Difference between HashMap and HashTable? Can we make hashmap synchronized?


Difference between HashMap and Hashtable



This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is  fail-fast  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove()  method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms
1)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.

2)Fail-safe 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 wjavascript:void(0)ill 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.

3)Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Hope this will be useful.

Read more: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html#ixzz20Vt7DBrQ
 



 

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...