Important FAQ
What is fail-safe property?
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 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.
Encrypt, Decrypt password in Mysql
Inserting password encrypted to database using the following sql.
INSERT INTO PASSWORD(pass) VALUES(DES_ENCRYPT('user password'));
This SQL will encrypt the user inserted password to a encrypted text. In table level, password is unreadable.
Instead of DES_ENCRYPT() method you can come up with your own function.
Selecting password from database to a string.
SELECT DES_DECRYPT(pass) FROM PASSWORD ;
This SQL will return user password as user inserted
weblogic.xml to use on memory session replication
<?xml version="1.0" encoding="UTF-8" ?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-descriptor>
<timeout-secs>300</timeout-secs>
<invalidation-interval-secs>60</invalidation-interval-secs>
<persistent-store-type>jdbc</persistent-store-type>
<persistent-store-pool>SessionDS</persistent-store-pool>
<persistent-store-table>WL_SERVLET_SESSIONS</persistent-store-table>
</session-descriptor>
</weblogic-web-app>
Use the above code for weblogic.xml. Your weblogic cluster MUST be configured to use jdbc persistence store to capture web-browsers and nodes sessions. WL_SERVLET_SESSIONS is the table for session store.
Add this weblogic.xml file to your WEB-INF directory and deploy your application to the weblogic cluster. When a cluster node down, it will replicate all the JSP sessions associates with the clients.
What are the common browser issues you will keep in mind while creating a web application?
1) User pressing back/refresh button
2) Browser crashing
3) Session issues
4) Compatibility across web browsers
What do you generally do after you have resolved a problem?
Perform the Root Cause Analysis and make sure the changes done have not effected any other module.
The Server and Database are working fine at your end but not on customer machine. What will you do?
1) Check if the customer has not done any customizations
2) Provide a test build same as running at my end (ask customer to take a backup of their app)
3) Check out how the customer is using the application
A web application is running but pages are loading slow. How will you figure out what the problem is?
Look for threading, database, caching issues.
What are the reasons for a page not found error and how will you sort it out?1) The URL being sent is wrong2) The web.xml mapping is wrong
3) The web server is down
4) The application has not been deployed
How to check if a thread holds lock on a particular object in JavaThink about a scenario where you would have to find at run time that whether a thread has lock on a particular object e.g. find out whether thread NewsReader has lock on NewsPaper object or not ?
If this questions came in any interview then I would automatically assume that there could be at least two answer one is hard earned raw answer which programmer would like to figure out based on fundamentals and other could be some rarely used API calls which is available in java , by the way this is actually asked to me in an interview of one of the biggest global bank.
Here I am giving my answer and what I had discovered after interview
1)I thought about IllegalMonitorStateException which wait() and notify() methods throw when they get called from non-synchronized context so I said I would call newspaper.wait() and if this call throws exception it means thread is not holding lock, otherwise thread holds lock.
2)Later I discovered that thread is a static method called holdsLock(Object obj) which returns true or false based on whether threads holds lock on object passed.
How to write equals method in JAVA
When I started JAVA i heard that JAVA is truly object oriented language and everything in JAVA is object, later I found that though its not completely true but yes most of things are in Java is represented via OOPS concept. One of them is Introduction of java.lang.Object class and every class in Java extends this class by default. So when I started my blog and writing about my JAVA experience as Core JAVA Tutorials I thouhgt lets write something which helps beginners in JAVA.
Object class holds some very interesting method which is applicable at object level and one of them is equals () which we are going to discuss in this article. equals () method is used to compare the equality of two object. default implementation of equals() class provided by Object class compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object. JAVA recommends to override equals method if equality is going to be define by logical way or via some business logic and some classes in Java standard library does override it e.g. String class whose implementation of equals() method return true if content of two strings are exactly same.
Since HashMap of JAVA relies on equals () and hashcode () method for comparing keys and values, java has provided a contract to follow while overriding equals () method which state that
1) if two objects are equal by equals method then there hashcode must be same.
2) if two objects are unequal by equals method then there hashcode could be same or different.
So this was the basic theory about equals () method in JAVA now we are going to discuss the approach on how to override equals () method, yes I know you all know this stuff :) but I have seen some of equals () code which can really be improved by following correct. For illustration purpose we will see an example of Person class and discuss How to write equals () method for that class.
Here is my approach for writing equals() method
1) Do this check -- if yes then return true.
2) Do null check -- if yes then return false.
3) Do the instanceof check if instanceof return false than return false
4) Type cast the object; note the sequence instanceof check must be prior to casting object.
5) Compare individual attribute start with numeric attribute because comparing numeric attribute is fast and using short circuit operator so if first field does not match , don't try to match rest of attribute and return false.
Let’s see a code example:
class Person{
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean equals(Object obj){
if(obj == this){ //this is the fasted check
return true;
}
//this will handle both null and instanceof check
if (!(obj instanceof Person)){
return false; }
//casting only after instanceof check passed so no ClassCastException
Person guest = (Person) obj;
//using short circuit operator and comparing numeric first
return this.id == guest.id && this.firstName.equals(guest.getFirstName())
&& this.lastName.equals(guest.getLastName());
}
Tip: most of the IDE provides support to generate equals() and hashcode() method
In Eclipse do the right click-> source -> generate hashCode() and equals().Tip: if your domain class has any unique business key then just comparing that field in equals method would be enough instead of comparing all the fields e.g. in case of our example if "id" is unique for every person then by just comparing id we will be able to identify whether two persons are equal or not.
What is deadlock in Java ? How to fix it ?
This is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep.
"What is deadlock ?"
when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multithreading.
How do you detect deadlock ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.
other way is to find it when you actually get locked while running the application , try to take thread dump , in linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.
once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock becuase if thead 1 aquires lock on Sting object while executing method1() and thread 2 aquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.
now interviewer comes to final part , one of the most important in my view , How to fix deadlock ?
if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thead A aquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.
What is the use of class “java.lang.Class” ? why do we need Class.forName() and Class.newInstance() method if we can create object using new()?
java.lang.Class is one of the most important class in java but oftenly overlooked by java developers.
Every time JVM creates an object, it also creates a java.lang.Class object that describes the type of the object.
All instances of the same class share the same Class object and you can obtain the Class object by calling the getClass() method of the object. This method is inherited from java.lang.Object
Suppose you create two instances of class called Person e.g.
Person A = new Person();
Person B = new Person();
if(A.getClass() == B.getClass()){
System.out.println("A and B are instances of same class");
}else{
System.out.println("A and B are instances of different class");
}
In this case it will print "A and B are instances of same class" because they are both instance of clas Person.
We need forName() and newInstance() because many times it happens that we don’t know the name of the class to instantiate while writing code , we may get it from config files ,database , network or from any upstream.
this we called reflective way of creating object which is one of the most powerful feature of java and which makes way for many frameworks e.g. Spring ,Struts which uses java reflection.
How do you find length of a Singly Linked list
Here is one of the classical questions asked to me on an interview with multinational Investment bank after that this question asked to me on several times in other interviews also . what makes this question interesting is that java developers are not that great with datastructure relative to C++ developer which is obvious because of fundamental difference between this two language.C++ is more of system programming language while java is more on application programming , also rich set of java API allows programmer to skip this kind of basic programming techniques.
anyway lets come back to the question , everybody knows that Linked lists is last element will point to "null" element , so first answer would most of the times would be "I will use a counter and increment till we reach the end of the element" e.g.
Iterative Solutions
public int length(){
int count=0;
Node current = this.head;
while(current != null){
count++;
current=current.next()
}
return count;
}
If you answer this question without any difficulty most interviewer will ask you to write a "recursive" solution for this just to check how you deal with recursion if your first answer would have been recursive they will ask you to write an "iterative solution" as shown above.
Recursive Solution:
public int length(Node current){
if(current == null) //base case
return 0;
return 1+length(current.next());
}
Why wait (), notify () and notifyAll () must be called from synchronized block or method in JavaMost of Java developer knows that wait() ,notify() and notifyAll() method of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why ? Recently this questions was asked to in Java interview to one of my friend, he pondered for a moment and replied that if we don't call wait () or notify () method from synchronized context we will receive IllegalMonitorStateException in java. He was right in terms of behavior of language but as per him interviewer was not completely satisfied with the answer and wanted to explain more about it. After the interview he discussed the same questions with me and I thought he might have told about race condition between wait () and notify () in Java that could exists if we don't call them inside synchronized method or block. Let’s see how it could happen:
We use wait () and notify () or notifyAll () method mostly for inter-thread communication. One thread is waiting after checking a condition e.g. In Producer Consumer example Producer Thread is waiting if buffer is full and Consumer thread notify Producer thread after he creates a space in buffer by consuming an element. calling notify() or notifyAll() issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block , all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Let’s divide this whole operation in steps to see a possibility of race condition between wait () and notify () method in Java, we will use Produce Consumer thread example to understand the scenario better:
1. The Producer thread tests the condition (buffer is full or not) and confirms that it must wait (after finding buffer is full).
2. The Consumer thread sets the condition after consuming an element from buffer.
3. The Consumer thread calls the notify () method; this goes unheard since the Producer thread is not yet waiting.
4. The Producer thread calls the wait () method and goes into waiting state.So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang.
So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang.
Now let's think how does this potential race condition get resolved? This race condition is resolved by using synchronized keyword and locking provided by java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method. Since the wait () method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait () method, we must use this lock to ensure that checking the condition (buffer is full or not) and setting the condition (taking element from buffer) is atomic which can be achieved by using synchronized method or block in Java.
Just to summarize we call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.2) Any potential race condition between wait and notify method in Java.
-----------------------------------------------------------------------------------------------------------------------------------------------
I want to know, How many number of users logged in to website? can any one answer?
The Number of threads can run simmultaneously by the server is equal to the number of persons can log into a web site.
Number of users loged on website is depends on Pool Size of there connection string. By Default MaxPoolSize=100 and MinPolSize=0.if Max pool size in 100 so only 100 user can loged in.If 101 ser will try to simultaneously you will get TimeOut error because your connectionstring wait to free one of connection onject out of 100.
Create a static variable and increment it every time the page/sit gets loaded.
Use listeners. Since you want to to know how many users have logged in, so the login info would be stored in a session.You can create a filter by extending HttpSessionListener, and update a static variable when the session is created. The value of this variable will store the number of users currently logged on.
1. If the website is static pages no data base interaction then using static variable we can find out how many users loged into the system.2.If the webpage is data base centric and for accessing any page we are retriving data then we can find the max. no of connections .
HttpSessionListener is Listener whenever session is created.
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}
public static int getActiveSessions() {
return activeSessions;
}
}
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 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.
Encrypt, Decrypt password in Mysql
Inserting password encrypted to database using the following sql.
INSERT INTO PASSWORD(pass) VALUES(DES_ENCRYPT('user password'));
This SQL will encrypt the user inserted password to a encrypted text. In table level, password is unreadable.
Instead of DES_ENCRYPT() method you can come up with your own function.
Selecting password from database to a string.
SELECT DES_DECRYPT(pass) FROM PASSWORD ;
This SQL will return user password as user inserted
weblogic.xml to use on memory session replication
<?xml version="1.0" encoding="UTF-8" ?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-descriptor>
<timeout-secs>300</timeout-secs>
<invalidation-interval-secs>60</invalidation-interval-secs>
<persistent-store-type>jdbc</persistent-store-type>
<persistent-store-pool>SessionDS</persistent-store-pool>
<persistent-store-table>WL_SERVLET_SESSIONS</persistent-store-table>
</session-descriptor>
</weblogic-web-app>
Use the above code for weblogic.xml. Your weblogic cluster MUST be configured to use jdbc persistence store to capture web-browsers and nodes sessions. WL_SERVLET_SESSIONS is the table for session store.
Add this weblogic.xml file to your WEB-INF directory and deploy your application to the weblogic cluster. When a cluster node down, it will replicate all the JSP sessions associates with the clients.
What are the common browser issues you will keep in mind while creating a web application?
1) User pressing back/refresh button
2) Browser crashing
3) Session issues
4) Compatibility across web browsers
What do you generally do after you have resolved a problem?
Perform the Root Cause Analysis and make sure the changes done have not effected any other module.
The Server and Database are working fine at your end but not on customer machine. What will you do?
1) Check if the customer has not done any customizations
2) Provide a test build same as running at my end (ask customer to take a backup of their app)
3) Check out how the customer is using the application
A web application is running but pages are loading slow. How will you figure out what the problem is?
Look for threading, database, caching issues.
What are the reasons for a page not found error and how will you sort it out?1) The URL being sent is wrong2) The web.xml mapping is wrong
3) The web server is down
4) The application has not been deployed
How to check if a thread holds lock on a particular object in JavaThink about a scenario where you would have to find at run time that whether a thread has lock on a particular object e.g. find out whether thread NewsReader has lock on NewsPaper object or not ?
If this questions came in any interview then I would automatically assume that there could be at least two answer one is hard earned raw answer which programmer would like to figure out based on fundamentals and other could be some rarely used API calls which is available in java , by the way this is actually asked to me in an interview of one of the biggest global bank.
Here I am giving my answer and what I had discovered after interview
1)I thought about IllegalMonitorStateException which wait() and notify() methods throw when they get called from non-synchronized context so I said I would call newspaper.wait() and if this call throws exception it means thread is not holding lock, otherwise thread holds lock.
2)Later I discovered that thread is a static method called holdsLock(Object obj) which returns true or false based on whether threads holds lock on object passed.
How to write equals method in JAVA
When I started JAVA i heard that JAVA is truly object oriented language and everything in JAVA is object, later I found that though its not completely true but yes most of things are in Java is represented via OOPS concept. One of them is Introduction of java.lang.Object class and every class in Java extends this class by default. So when I started my blog and writing about my JAVA experience as Core JAVA Tutorials I thouhgt lets write something which helps beginners in JAVA.
Object class holds some very interesting method which is applicable at object level and one of them is equals () which we are going to discuss in this article. equals () method is used to compare the equality of two object. default implementation of equals() class provided by Object class compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object. JAVA recommends to override equals method if equality is going to be define by logical way or via some business logic and some classes in Java standard library does override it e.g. String class whose implementation of equals() method return true if content of two strings are exactly same.
Since HashMap of JAVA relies on equals () and hashcode () method for comparing keys and values, java has provided a contract to follow while overriding equals () method which state that
1) if two objects are equal by equals method then there hashcode must be same.
2) if two objects are unequal by equals method then there hashcode could be same or different.
So this was the basic theory about equals () method in JAVA now we are going to discuss the approach on how to override equals () method, yes I know you all know this stuff :) but I have seen some of equals () code which can really be improved by following correct. For illustration purpose we will see an example of Person class and discuss How to write equals () method for that class.
Here is my approach for writing equals() method
1) Do this check -- if yes then return true.
2) Do null check -- if yes then return false.
3) Do the instanceof check if instanceof return false than return false
4) Type cast the object; note the sequence instanceof check must be prior to casting object.
5) Compare individual attribute start with numeric attribute because comparing numeric attribute is fast and using short circuit operator so if first field does not match , don't try to match rest of attribute and return false.
Let’s see a code example:
class Person{
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean equals(Object obj){
if(obj == this){ //this is the fasted check
return true;
}
//this will handle both null and instanceof check
if (!(obj instanceof Person)){
return false; }
//casting only after instanceof check passed so no ClassCastException
Person guest = (Person) obj;
//using short circuit operator and comparing numeric first
return this.id == guest.id && this.firstName.equals(guest.getFirstName())
&& this.lastName.equals(guest.getLastName());
}
Tip: most of the IDE provides support to generate equals() and hashcode() method
In Eclipse do the right click-> source -> generate hashCode() and equals().Tip: if your domain class has any unique business key then just comparing that field in equals method would be enough instead of comparing all the fields e.g. in case of our example if "id" is unique for every person then by just comparing id we will be able to identify whether two persons are equal or not.
- There are utilities available to write efficient and time saving equals method. One can use ToEqualsBuilder in Apache commons-lang package. It is very easy to implement and does lot of calculation automatically.
- most of the IDE provides support to generate equals() and hashcode() method in Eclipse do the right click-> source -> generate hashCode() and equals().
- Since firstName and lastName are String objects, == operator might not always return true, you should use equals() method to compare them.
What is deadlock in Java ? How to fix it ?
This is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep.
"What is deadlock ?"
when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multithreading.
How do you detect deadlock ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.
other way is to find it when you actually get locked while running the application , try to take thread dump , in linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.
once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock becuase if thead 1 aquires lock on Sting object while executing method1() and thread 2 aquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.
now interviewer comes to final part , one of the most important in my view , How to fix deadlock ?
if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thead A aquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.
What is the use of class “java.lang.Class” ? why do we need Class.forName() and Class.newInstance() method if we can create object using new()?
java.lang.Class is one of the most important class in java but oftenly overlooked by java developers.
Every time JVM creates an object, it also creates a java.lang.Class object that describes the type of the object.
All instances of the same class share the same Class object and you can obtain the Class object by calling the getClass() method of the object. This method is inherited from java.lang.Object
Suppose you create two instances of class called Person e.g.
Person A = new Person();
Person B = new Person();
if(A.getClass() == B.getClass()){
System.out.println("A and B are instances of same class");
}else{
System.out.println("A and B are instances of different class");
}
In this case it will print "A and B are instances of same class" because they are both instance of clas Person.
We need forName() and newInstance() because many times it happens that we don’t know the name of the class to instantiate while writing code , we may get it from config files ,database , network or from any upstream.
this we called reflective way of creating object which is one of the most powerful feature of java and which makes way for many frameworks e.g. Spring ,Struts which uses java reflection.
How do you find length of a Singly Linked list
Here is one of the classical questions asked to me on an interview with multinational Investment bank after that this question asked to me on several times in other interviews also . what makes this question interesting is that java developers are not that great with datastructure relative to C++ developer which is obvious because of fundamental difference between this two language.C++ is more of system programming language while java is more on application programming , also rich set of java API allows programmer to skip this kind of basic programming techniques.
anyway lets come back to the question , everybody knows that Linked lists is last element will point to "null" element , so first answer would most of the times would be "I will use a counter and increment till we reach the end of the element" e.g.
Iterative Solutions
public int length(){
int count=0;
Node current = this.head;
while(current != null){
count++;
current=current.next()
}
return count;
}
If you answer this question without any difficulty most interviewer will ask you to write a "recursive" solution for this just to check how you deal with recursion if your first answer would have been recursive they will ask you to write an "iterative solution" as shown above.
Recursive Solution:
public int length(Node current){
if(current == null) //base case
return 0;
return 1+length(current.next());
}
Why wait (), notify () and notifyAll () must be called from synchronized block or method in JavaMost of Java developer knows that wait() ,notify() and notifyAll() method of object class must have to be called inside synchronized method or synchronized block in Java but how many times we thought why ? Recently this questions was asked to in Java interview to one of my friend, he pondered for a moment and replied that if we don't call wait () or notify () method from synchronized context we will receive IllegalMonitorStateException in java. He was right in terms of behavior of language but as per him interviewer was not completely satisfied with the answer and wanted to explain more about it. After the interview he discussed the same questions with me and I thought he might have told about race condition between wait () and notify () in Java that could exists if we don't call them inside synchronized method or block. Let’s see how it could happen:
We use wait () and notify () or notifyAll () method mostly for inter-thread communication. One thread is waiting after checking a condition e.g. In Producer Consumer example Producer Thread is waiting if buffer is full and Consumer thread notify Producer thread after he creates a space in buffer by consuming an element. calling notify() or notifyAll() issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block , all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Let’s divide this whole operation in steps to see a possibility of race condition between wait () and notify () method in Java, we will use Produce Consumer thread example to understand the scenario better:
1. The Producer thread tests the condition (buffer is full or not) and confirms that it must wait (after finding buffer is full).
2. The Consumer thread sets the condition after consuming an element from buffer.
3. The Consumer thread calls the notify () method; this goes unheard since the Producer thread is not yet waiting.
4. The Producer thread calls the wait () method and goes into waiting state.So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang.
So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang.
Now let's think how does this potential race condition get resolved? This race condition is resolved by using synchronized keyword and locking provided by java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method. Since the wait () method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait () method, we must use this lock to ensure that checking the condition (buffer is full or not) and setting the condition (taking element from buffer) is atomic which can be achieved by using synchronized method or block in Java.
Just to summarize we call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.2) Any potential race condition between wait and notify method in Java.
-----------------------------------------------------------------------------------------------------------------------------------------------
I want to know, How many number of users logged in to website? can any one answer?
The Number of threads can run simmultaneously by the server is equal to the number of persons can log into a web site.
Number of users loged on website is depends on Pool Size of there connection string. By Default MaxPoolSize=100 and MinPolSize=0.if Max pool size in 100 so only 100 user can loged in.If 101 ser will try to simultaneously you will get TimeOut error because your connectionstring wait to free one of connection onject out of 100.
Create a static variable and increment it every time the page/sit gets loaded.
Use listeners. Since you want to to know how many users have logged in, so the login info would be stored in a session.You can create a filter by extending HttpSessionListener, and update a static variable when the session is created. The value of this variable will store the number of users currently logged on.
1. If the website is static pages no data base interaction then using static variable we can find out how many users loged into the system.2.If the webpage is data base centric and for accessing any page we are retriving data then we can find the max. no of connections .
HttpSessionListener is Listener whenever session is created.
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}
public static int getActiveSessions() {
return activeSessions;
}
}