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