JDK (Java Development Kit)
Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…
Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.
JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file
JRE (Java Runtime Environment)
Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system
The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.
If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.
JVM (Java Virtual Machine)
As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file. '.class' file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.
The JVM is called "virtual" because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.
There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.
Thursday, February 24, 2011
How To Manage Memory With Java
Java provides automatic garbage collection,sometimes you will want to know how large the object heap is and how much of it is left. You can use this result to know about the efficiency of your application or program, that is you may come to know how many more objects you can instantiate. To obtain these values use totalMemory() and freeMemory() methods.
Since Java Garbage Collector runs periodically to check the dangling object references and empty Strings and to recycle these unused objects. However on the other hand we can let the garbage collector run whenever we want. Garbage collector runs on random times, you never know when will be the next appointment of Garbage Collector. So, f you think you are running out of memory you can enforce Garbage Collector to Sweep unused memory. You can run the Garbage Collector on demand by calling gc() method. gc() is called as "System. gc()". A good practice is to first call gc() method then call freeMemory() to get the base memory usage. Next execute your code and now see how much memory code is occupying by again calling freeMemory() method.
NOTE:-The methods gc(), totalMemory(), freeMemory() are part of Runtime class(For more on Runtime refer its Runtime API). The gc() method is also available in System class and is marked static in it.
Lets understand by example:-
public class Memoryusage{
public static void main(String a[]){
Runtime rt = Runtime. getRuntime();
long mem1,mem2;
String toomuch[] = new String[20000];
System. out. println("Total memory is : "+rt. totalMemory());
mem1=rt. freeMemory();
System. out. println("Initial Free Memory : "+mem1);
rt. gc();
mem1=rt. freeMemory();
System. out. println("Memory after Garbage Collection :"+mem1);
for(int i=0;i<20000;i++)
toomuch[i] = new String("String Array");
mem2=rt. freeMemory();
System. out. println("Memory after allocation :"+mem2);
System. out. println("Memory used by alocation : "+(mem1-mem2));
for(int i=0;i<1000;i++)
toomuch[i] = null;
rt. gc();
mem2=rt. freeMemory();
System. out. println("Memory after deacllocating memory : "+mem2);
}
}
Output:-
Total memory is : 5177344
Initial Free Memory : 4898608
Memory after Garbage Collection :4986512
Memory after allocation :4505976
Memory used by allocation : 480536
Memory after deacllocation memory : 4530512
Output is Machine specific and may vary on your machine.
Now you can see that how these methods work gc(),freeMemory() and totalMemory(). Runtime class is an abstract class thus it cannot be used to create instances but despite we can all methods to do the same. Like here we have called method getRuntime().
Since Java Garbage Collector runs periodically to check the dangling object references and empty Strings and to recycle these unused objects. However on the other hand we can let the garbage collector run whenever we want. Garbage collector runs on random times, you never know when will be the next appointment of Garbage Collector. So, f you think you are running out of memory you can enforce Garbage Collector to Sweep unused memory. You can run the Garbage Collector on demand by calling gc() method. gc() is called as "System. gc()". A good practice is to first call gc() method then call freeMemory() to get the base memory usage. Next execute your code and now see how much memory code is occupying by again calling freeMemory() method.
NOTE:-The methods gc(), totalMemory(), freeMemory() are part of Runtime class(For more on Runtime refer its Runtime API). The gc() method is also available in System class and is marked static in it.
Lets understand by example:-
public class Memoryusage{
public static void main(String a[]){
Runtime rt = Runtime. getRuntime();
long mem1,mem2;
String toomuch[] = new String[20000];
System. out. println("Total memory is : "+rt. totalMemory());
mem1=rt. freeMemory();
System. out. println("Initial Free Memory : "+mem1);
rt. gc();
mem1=rt. freeMemory();
System. out. println("Memory after Garbage Collection :"+mem1);
for(int i=0;i<20000;i++)
toomuch[i] = new String("String Array");
mem2=rt. freeMemory();
System. out. println("Memory after allocation :"+mem2);
System. out. println("Memory used by alocation : "+(mem1-mem2));
for(int i=0;i<1000;i++)
toomuch[i] = null;
rt. gc();
mem2=rt. freeMemory();
System. out. println("Memory after deacllocating memory : "+mem2);
}
}
Output:-
Total memory is : 5177344
Initial Free Memory : 4898608
Memory after Garbage Collection :4986512
Memory after allocation :4505976
Memory used by allocation : 480536
Memory after deacllocation memory : 4530512
Output is Machine specific and may vary on your machine.
Now you can see that how these methods work gc(),freeMemory() and totalMemory(). Runtime class is an abstract class thus it cannot be used to create instances but despite we can all methods to do the same. Like here we have called method getRuntime().
Wednesday, February 23, 2011
http://www.javadev.org/files/Hibernate%20Performance%20Tuning.pdf
Hibernate Performance Tuning
Fetching strategies
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over‐ridden by a particular HQL or Criteria query.
Hibernate3 defines the following fetching strategies:
• Join fetching ‐ Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
• Select fetching ‐ a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
• Subselect fetching ‐ a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
• Batch fetching ‐ an optimization strategy for select fetching ‐ Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
• Immediate fetching ‐ an association, collection or attribute is fetched immediately, when the owner is
loaded.
• Lazy collection fetching ‐ a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
• "Extra‐lazy" collection fetching ‐ individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
• Proxy fetching ‐ a single‐valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
• "No‐proxy" fetching ‐ a single‐valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
• Lazy attribute fetching ‐ an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
Solving the n+1 selects problem
The biggest performance killer in applications that persist objects to SQL databases is the n+1 selects problem. When you tune the performance of a Hibernate application, this problem is the first thing you’ll usually need to address. Its normal (and recommended) to map almost all associations for lazy initialization.
This means you generally set all collections to lazy="true" and even change some of the one‐to‐one and many‐to‐one associations to not use outer joins by default. This is the only way to avoid retrieving all objects in the database in every transaction. Unfortunately, this decision exposes you to the n+1 selects problem.
It’s easy to understand this problem by considering a simple query that retrieves all Items for a particular user:
Iterator items = session.createCriteria(Item.class)
.add( Expression.eq("item.seller", user) )
.list()
.iterator();
This query returns a list of items, where each collection of bids is an uninitialized collection wrapper. Suppose that we now wish to find the maximum bid for each item. The following code would be one way to do this:
List maxAmounts = new ArrayList();
while (items.hasNext()) {
Item item = (Item) items.next();
BigDecimal maxAmount = new BigDecimal("0");
for ( Iterator b = item.getBids().iterator(); b.hasNext(); ) {
Bid bid = (Bid) b.next();
if ( bid.getAmount().compareTo(maxAmount) == 1 )
maxAmount = bid.getAmount();
}
maxAmounts.add( new MaxAmount( item.getId(), maxAmount ) );
}
But there is a huge problem with this solution (aside from the fact that this would be much better executed in the database using aggregation functions): Each time we access the collection of bids, Hibernate must fetch this lazy collection from the database for each item. If the initial query returns 20 items, the entire transaction requires 1 initial select that retrieves the items plus 20 additional selects to load the bids collections of each item. This might easily result in unacceptable latency in a system that accesses the database across a network. Usually you don't explicitly create such operations, because you should quickly see doing so is suboptimal.
However, the n+1 selects problem is often hidden in more complex application logic, and you may not recognize it by looking at a single routine.
Batch fetching
The first attempt to solve this problem might be to enable batch fetching. We change our mapping for the bids collection to look like this:
With batch fetching enabled, Hibernate pre‐fetches the next 10 collections when the first collection is accessed. This reduces the problem from n+1 selects to n/10 + 1 selects. For many applications, this may be sufficient to achieve acceptable latency. On the other hand, it also means that in some other transactions, collections are fetched unnecessarily. It isn’t the best we can do in terms of reducing the number of round trips to the database.
HQL aggregation A much, much better solution is to take advantage of HQL aggregation and perform the work of calculating the maximum bid on the database. Thus we avoid the problem:
String query = "select MaxAmount( item.id, max(bid.amount) )" + " from Item item join item.bids bid" + " where item.seller = :user group by item.id"; List maxAmounts = session.createQuery(query).setEntity("user", user).list();
Unfortunately, this isn’t a complete solution to the generic issue. In general, we may need to do more complex processing on the bids than merely calculating the maximum amount. We’d prefer to do this processing in the Java application.
Eager fetching
We can try enabling eager fetching at the level of the mapping document:
The outer‐join attribute is available for collections and other associations. It forces Hibernate to load the association eagerly, using an SQL outer join. Note that, as previously mentioned, HQL queries ignore the outer‐join attribute; but we might be using a criteria query. This mapping avoids the problem as far as this transaction is concerned; we’re now able to load all bids in the initial select. Unfortunately, any other transaction that retrieves items using get(), load(), or a criteria query will also retrieve all the bids at once. Retrieving unnecessary data imposes extra load on both the database server and the application server and may also reduce the concurrency of the system, creating too many unnecessary read locks at the database level. Hence we consider eager fetching at the level of the mapping file to be almost always a bad approach. The outer‐join attribute of collection mappings is arguably a misfeature of Hibernate (fortunately, it’s disabled by default). Occasionally it makes sense to enable outer‐join for a or association (the default is auto), but we’d never do this in the case of a collection.
Runtime (codelevel) declarations
The recommended solution for this problem is to take advantage of Hibernate’s support for runtime (code‐level) declarations of association fetching strategies. The example can be implemented like this:
List results = session.createCriteria(Item.class)
.add( Expression.eq("item.seller", user) )
.setFetchMode("bids", FetchMode.EAGER)
.list();
// Make results distinct
Iterator items = new HashSet(results).iterator();
List maxAmounts = new ArrayList();
for ( ; items.hasNext(); ) {
Item item = (Item) items.next();
BigDecimal maxAmount = new BigDecimal("0");
for ( Iterator b = item.getBids().iterator(); b.hasNext(); ) {
Bid bid = (Bid) b.next();
if ( bid.getAmount().compareTo(maxAmount) == 1 )
maxAmount = bid.getAmount();
}
maxAmounts.add( new MaxAmount( item.getId(), maxAmount ) );
}
We disabled batch fetching and eager fetching at the mapping level; the collection is lazy by default. Instead, we enable eager fetching for this query alone by calling setFetchMode(). As discussed earlier in this chapter, this is equivalent to a fetch join in the from clause of an HQL query. The previous code example has one extra complication: The result list returned by the Hibernate criteria query isn’t guaranteed to be distinct. In the case of a query that fetches a collection by outer join, it will contain duplicate items. It’s the application’s responsibility to make the results distinct if that is required. We implement this by adding the results to a HashSet and then iterating the set.
So, we have established a general solution to the n+1 selects problem. Rather than retrieving just the top‐level objects in the initial query and then fetching needed associations as the application navigates the object graph, we follow a two step process:
1 Fetch all needed data in the initial query by specifying exactly which associations will be accessed in the following unit of work.
2 Navigate the object graph, which will consist entirely of objects that have already been fetched from the database.
This is the only true solution to the mismatch between the object‐oriented world, where data is accessed by navigation, and the relational world, where data is accessed by joining.
Lazy fetching
By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single‐valued associations. These defaults make sense for almost all associations in almost all applications. However, lazy fetching poses one problem that you must be aware of. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. Since the lazy collection was not initialized when the Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects. The fix is to move the code that reads from the collection to just before the transaction is committed. Alternatively, we
could use a non‐lazy collection or association, by specifying lazy="false" for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non‐lazy associations in your object model, Hibernate will end up needing to fetch the entire database into memory in every transaction!
Initializing collections and proxies
A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, ie. when the entity owning the collection or having the reference to the proxy is in the detached state.
Sometimes we need to ensure that a proxy or collection is initialized before closing the Session. Of course, we can always force initialization by calling item.getBids() or item.getBids().size(), for example. But that is confusing to readers of the code and is not convenient for generic code. The static methods Hibernate.initialize() and Hibernate.isInitialized() provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(item) will force the initialization of a proxy, item, as long as its Session is still open. Hibernate.initialize(item.getBids() ) has a similar effect for the collection of bids. Another option is to keep the Session open until all needed collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:
•
In a web‐based application, a servlet filter can be used to close the Session only at the very end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the Session is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view.
•
In an application with a separate business tier, the business logic must "prepare" all collections that will be needed by the web tier before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.
•
You may also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections (or other proxies). No, Hibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
The Second Level Cache
A Hibernate Session is a transaction‐level cache of persistent data. It is possible to configure a cluster or JVMlevel (SessionFactory‐level) cache on a class‐by‐class and collection‐by‐collection basis. You may even plugin a clustered cache. Be careful. Caches are never aware of changes made to the persistent store by another application (though they may be configured to regularly expire cached data).
You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate comes bundled with a number of built‐in integrations with open‐source cache providers (listed below); additionally, you could implement your own and plug it in as outlined above.
Cache Providers
Cache
Provider class
Type
Cluster Safe
Query Cache
Supported
Hashtable
(not intended
for production
use)
org.hibernate.cache.HashtableCacheProv
ider
memory
yes
EHCache
org.hibernate.cache.EhCacheProvider
memory, disk
yes
OSCache
org.hibernate.cache.OSCacheProvider
memory, disk
yes
SwarmCache
org.hibernate.cache.SwarmCacheProvider
clustered (ip
multicast)
yes (clustered
invalidation)
JBoss
TreeCache
org.hibernate.cache.TreeCacheProvider
clustered (ip
multicast),
transactional
yes
(replication)
yes (clock
sync req.)
Cache mappings
The element of a class or collection mapping has the following form:
usage="transactional|read‐write|nonstrict‐read‐write|read‐only" (1)
region="RegionName" (2)
include="all|non‐lazy" (3)
/>
(1) usage (required) specifies the caching strategy: transactional, read‐write, nonstrict‐read‐write or read‐only (2) region (optional, defaults to the class or collection role name) specifies the name of the second level cache region
(3) include (optional, defaults to all) non‐lazy specifies that properties of the entity mapped with lazy="true" may not be cached when attribute‐level lazy fetching is enabled
Alternatively (preferably?), you may specify and elements in hibernate.cfg.xml.
Strategy: read only
If your application needs to read but never modify instances of a persistent class, a read‐only cache may be used. This is the simplest and best performing strategy. It's even perfectly safe for use in a cluster.
Strategy: read/write
If the application needs to update data, a read‐write cache might be appropriate. This cache strategy should never be used if serializable transaction isolation level is required. If the cache is used in a JTA environment, you must specify the property hibernate.transaction.manager_lookup_class, naming a strategy for obtaining the JTA TransactionManager. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called. If you wish to use this strategy in a cluster, you should ensure that the underlying cache implementation supports locking. The built‐in cache providers do not.
Strategy: nonstrict read/write
If the application only occasionally needs to update data (ie. if it is extremely unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a nonstrictread‐write cache might be appropriate. If the cache is used in a JTA environment, you must specify hibernate.transaction.manager_lookup_class. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called.
Strategy: transactional
The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.
Cache Concurrency Strategy Support
Cache
read‐only
read‐only nonstrictread‐
write
read‐write
transactional
Hashtable (not intended
for production
use)
yes
yes
yes
EHCache
yes
yes
yes
OSCache
yes
yes
yes
SwarmCache
yes
yes
JBoss TreeCache
yes
yes
Managing the caches
Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. When flush() is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur or if you are processing a huge number of objects and need to manage memory efficiently, the evict() method may be used to remove the object and its collections from the firstlevelcache.
ScrollableResult items = sess.createQuery("from Item as item").scroll(); //a huge result set
while ( items.next() ) {
Item item = (Item) items.get(0);
doSomethingWithAItem(item);
sess.evict(item);
}
The Session also provides a contains() method to determine if an instance belongs to the session cache. To completely evict all objects from the session cache, call Session.clear() For the second‐level cache, there are methods defined on SessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role.
sessionFactory.evict(Item.class, itemId); //evict a particular Item
sessionFactory.evict(Item.class); //evict all Items sessionFactory.evictCollection("Item.bids", itemId); //evict a particular collection of bids
sessionFactory.evictCollection("Item.bids"); //evict all bid collections
The CacheMode controls how a particular session interacts with the second‐level cache.
• CacheMode.NORMAL ‐ read items from and write items to the second‐level cache • CacheMode.GET ‐ read items from the second‐level cache, but don't write to the second‐level cache except when updating data • CacheMode.PUT ‐ write items to the second‐level cache, but don't read from the second‐level cache • CacheMode.REFRESH ‐ write items to the second‐level cache, but don't read from the second‐level cache, bypass the effect of hibernate.cache.use_minimal_puts, forcing a refresh of the second‐level cache for all items read from the database
To browse the contents of a second‐level or query cache region, use the Statistics API:
Map cacheEntries = sessionFactory.getStatistics()
.getSecondLevelCacheStatistics(regionName)
.getEntries();
You'll need to enable statistics, and, optionally, force Hibernate to keep the cache entries in a more human understandable format:
hibernate.generate_statistics true
hibernate.cache.use_structured_entries true
The Query Cache
Query result sets may also be cached. This is only useful for queries that are run frequently with the same parameters. To use the query cache you must first enable it:
hibernate.cache.use_query_cache true
This setting causes the creation of two new cache regions ‐ one holding cached query result sets
(org.hibernate.cache.StandardQueryCache), the other holding timestamps of the most recent updates to queryable tables (org.hibernate.cache.UpdateTimestampsCache). Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. So the query cache should always be used in conjunction with the second‐level cache.
Most queries do not benefit from caching, so by default queries are not cached. To enable caching, call
Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed.
By Nima Goudarzi ‐ July, 2007
References:
‐ Hibernate3 reference
‐ Hibernate in Action (Manning 2005)
Fetching strategies
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over‐ridden by a particular HQL or Criteria query.
Hibernate3 defines the following fetching strategies:
• Join fetching ‐ Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
• Select fetching ‐ a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
• Subselect fetching ‐ a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
• Batch fetching ‐ an optimization strategy for select fetching ‐ Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
• Immediate fetching ‐ an association, collection or attribute is fetched immediately, when the owner is
loaded.
• Lazy collection fetching ‐ a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
• "Extra‐lazy" collection fetching ‐ individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
• Proxy fetching ‐ a single‐valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
• "No‐proxy" fetching ‐ a single‐valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
• Lazy attribute fetching ‐ an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
Solving the n+1 selects problem
The biggest performance killer in applications that persist objects to SQL databases is the n+1 selects problem. When you tune the performance of a Hibernate application, this problem is the first thing you’ll usually need to address. Its normal (and recommended) to map almost all associations for lazy initialization.
This means you generally set all collections to lazy="true" and even change some of the one‐to‐one and many‐to‐one associations to not use outer joins by default. This is the only way to avoid retrieving all objects in the database in every transaction. Unfortunately, this decision exposes you to the n+1 selects problem.
It’s easy to understand this problem by considering a simple query that retrieves all Items for a particular user:
Iterator items = session.createCriteria(Item.class)
.add( Expression.eq("item.seller", user) )
.list()
.iterator();
This query returns a list of items, where each collection of bids is an uninitialized collection wrapper. Suppose that we now wish to find the maximum bid for each item. The following code would be one way to do this:
List maxAmounts = new ArrayList();
while (items.hasNext()) {
Item item = (Item) items.next();
BigDecimal maxAmount = new BigDecimal("0");
for ( Iterator b = item.getBids().iterator(); b.hasNext(); ) {
Bid bid = (Bid) b.next();
if ( bid.getAmount().compareTo(maxAmount) == 1 )
maxAmount = bid.getAmount();
}
maxAmounts.add( new MaxAmount( item.getId(), maxAmount ) );
}
But there is a huge problem with this solution (aside from the fact that this would be much better executed in the database using aggregation functions): Each time we access the collection of bids, Hibernate must fetch this lazy collection from the database for each item. If the initial query returns 20 items, the entire transaction requires 1 initial select that retrieves the items plus 20 additional selects to load the bids collections of each item. This might easily result in unacceptable latency in a system that accesses the database across a network. Usually you don't explicitly create such operations, because you should quickly see doing so is suboptimal.
However, the n+1 selects problem is often hidden in more complex application logic, and you may not recognize it by looking at a single routine.
Batch fetching
The first attempt to solve this problem might be to enable batch fetching. We change our mapping for the bids collection to look like this:
With batch fetching enabled, Hibernate pre‐fetches the next 10 collections when the first collection is accessed. This reduces the problem from n+1 selects to n/10 + 1 selects. For many applications, this may be sufficient to achieve acceptable latency. On the other hand, it also means that in some other transactions, collections are fetched unnecessarily. It isn’t the best we can do in terms of reducing the number of round trips to the database.
HQL aggregation A much, much better solution is to take advantage of HQL aggregation and perform the work of calculating the maximum bid on the database. Thus we avoid the problem:
String query = "select MaxAmount( item.id, max(bid.amount) )" + " from Item item join item.bids bid" + " where item.seller = :user group by item.id"; List maxAmounts = session.createQuery(query).setEntity("user", user).list();
Unfortunately, this isn’t a complete solution to the generic issue. In general, we may need to do more complex processing on the bids than merely calculating the maximum amount. We’d prefer to do this processing in the Java application.
Eager fetching
We can try enabling eager fetching at the level of the mapping document:
The outer‐join attribute is available for collections and other associations. It forces Hibernate to load the association eagerly, using an SQL outer join. Note that, as previously mentioned, HQL queries ignore the outer‐join attribute; but we might be using a criteria query. This mapping avoids the problem as far as this transaction is concerned; we’re now able to load all bids in the initial select. Unfortunately, any other transaction that retrieves items using get(), load(), or a criteria query will also retrieve all the bids at once. Retrieving unnecessary data imposes extra load on both the database server and the application server and may also reduce the concurrency of the system, creating too many unnecessary read locks at the database level. Hence we consider eager fetching at the level of the mapping file to be almost always a bad approach. The outer‐join attribute of collection mappings is arguably a misfeature of Hibernate (fortunately, it’s disabled by default). Occasionally it makes sense to enable outer‐join for a
Runtime (codelevel) declarations
The recommended solution for this problem is to take advantage of Hibernate’s support for runtime (code‐level) declarations of association fetching strategies. The example can be implemented like this:
List results = session.createCriteria(Item.class)
.add( Expression.eq("item.seller", user) )
.setFetchMode("bids", FetchMode.EAGER)
.list();
// Make results distinct
Iterator items = new HashSet(results).iterator();
List maxAmounts = new ArrayList();
for ( ; items.hasNext(); ) {
Item item = (Item) items.next();
BigDecimal maxAmount = new BigDecimal("0");
for ( Iterator b = item.getBids().iterator(); b.hasNext(); ) {
Bid bid = (Bid) b.next();
if ( bid.getAmount().compareTo(maxAmount) == 1 )
maxAmount = bid.getAmount();
}
maxAmounts.add( new MaxAmount( item.getId(), maxAmount ) );
}
We disabled batch fetching and eager fetching at the mapping level; the collection is lazy by default. Instead, we enable eager fetching for this query alone by calling setFetchMode(). As discussed earlier in this chapter, this is equivalent to a fetch join in the from clause of an HQL query. The previous code example has one extra complication: The result list returned by the Hibernate criteria query isn’t guaranteed to be distinct. In the case of a query that fetches a collection by outer join, it will contain duplicate items. It’s the application’s responsibility to make the results distinct if that is required. We implement this by adding the results to a HashSet and then iterating the set.
So, we have established a general solution to the n+1 selects problem. Rather than retrieving just the top‐level objects in the initial query and then fetching needed associations as the application navigates the object graph, we follow a two step process:
1 Fetch all needed data in the initial query by specifying exactly which associations will be accessed in the following unit of work.
2 Navigate the object graph, which will consist entirely of objects that have already been fetched from the database.
This is the only true solution to the mismatch between the object‐oriented world, where data is accessed by navigation, and the relational world, where data is accessed by joining.
Lazy fetching
By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single‐valued associations. These defaults make sense for almost all associations in almost all applications. However, lazy fetching poses one problem that you must be aware of. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. Since the lazy collection was not initialized when the Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects. The fix is to move the code that reads from the collection to just before the transaction is committed. Alternatively, we
could use a non‐lazy collection or association, by specifying lazy="false" for the association mapping. However, it is intended that lazy initialization be used for almost all collections and associations. If you define too many non‐lazy associations in your object model, Hibernate will end up needing to fetch the entire database into memory in every transaction!
Initializing collections and proxies
A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, ie. when the entity owning the collection or having the reference to the proxy is in the detached state.
Sometimes we need to ensure that a proxy or collection is initialized before closing the Session. Of course, we can always force initialization by calling item.getBids() or item.getBids().size(), for example. But that is confusing to readers of the code and is not convenient for generic code. The static methods Hibernate.initialize() and Hibernate.isInitialized() provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(item) will force the initialization of a proxy, item, as long as its Session is still open. Hibernate.initialize(item.getBids() ) has a similar effect for the collection of bids. Another option is to keep the Session open until all needed collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:
•
In a web‐based application, a servlet filter can be used to close the Session only at the very end of a user request, once the rendering of the view is complete (the Open Session in View pattern). Of course, this places heavy demands on the correctness of the exception handling of your application infrastructure. It is vitally important that the Session is closed and the transaction ended before returning to the user, even when an exception occurs during rendering of the view.
•
In an application with a separate business tier, the business logic must "prepare" all collections that will be needed by the web tier before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.
•
You may also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections (or other proxies). No, Hibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
The Second Level Cache
A Hibernate Session is a transaction‐level cache of persistent data. It is possible to configure a cluster or JVMlevel (SessionFactory‐level) cache on a class‐by‐class and collection‐by‐collection basis. You may even plugin a clustered cache. Be careful. Caches are never aware of changes made to the persistent store by another application (though they may be configured to regularly expire cached data).
You have the option to tell Hibernate which caching implementation to use by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. Hibernate comes bundled with a number of built‐in integrations with open‐source cache providers (listed below); additionally, you could implement your own and plug it in as outlined above.
Cache Providers
Cache
Provider class
Type
Cluster Safe
Query Cache
Supported
Hashtable
(not intended
for production
use)
org.hibernate.cache.HashtableCacheProv
ider
memory
yes
EHCache
org.hibernate.cache.EhCacheProvider
memory, disk
yes
OSCache
org.hibernate.cache.OSCacheProvider
memory, disk
yes
SwarmCache
org.hibernate.cache.SwarmCacheProvider
clustered (ip
multicast)
yes (clustered
invalidation)
JBoss
TreeCache
org.hibernate.cache.TreeCacheProvider
clustered (ip
multicast),
transactional
yes
(replication)
yes (clock
sync req.)
Cache mappings
The
region="RegionName" (2)
include="all|non‐lazy" (3)
/>
(1) usage (required) specifies the caching strategy: transactional, read‐write, nonstrict‐read‐write or read‐only (2) region (optional, defaults to the class or collection role name) specifies the name of the second level cache region
(3) include (optional, defaults to all) non‐lazy specifies that properties of the entity mapped with lazy="true" may not be cached when attribute‐level lazy fetching is enabled
Alternatively (preferably?), you may specify
Strategy: read only
If your application needs to read but never modify instances of a persistent class, a read‐only cache may be used. This is the simplest and best performing strategy. It's even perfectly safe for use in a cluster.
Strategy: read/write
If the application needs to update data, a read‐write cache might be appropriate. This cache strategy should never be used if serializable transaction isolation level is required. If the cache is used in a JTA environment, you must specify the property hibernate.transaction.manager_lookup_class, naming a strategy for obtaining the JTA TransactionManager. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called. If you wish to use this strategy in a cluster, you should ensure that the underlying cache implementation supports locking. The built‐in cache providers do not.
Strategy: nonstrict read/write
If the application only occasionally needs to update data (ie. if it is extremely unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a nonstrictread‐write cache might be appropriate. If the cache is used in a JTA environment, you must specify hibernate.transaction.manager_lookup_class. In other environments, you should ensure that the transaction is completed when Session.close() or Session.disconnect() is called.
Strategy: transactional
The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.
Cache Concurrency Strategy Support
Cache
read‐only
read‐only nonstrictread‐
write
read‐write
transactional
Hashtable (not intended
for production
use)
yes
yes
yes
EHCache
yes
yes
yes
OSCache
yes
yes
yes
SwarmCache
yes
yes
JBoss TreeCache
yes
yes
Managing the caches
Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. When flush() is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur or if you are processing a huge number of objects and need to manage memory efficiently, the evict() method may be used to remove the object and its collections from the firstlevelcache.
ScrollableResult items = sess.createQuery("from Item as item").scroll(); //a huge result set
while ( items.next() ) {
Item item = (Item) items.get(0);
doSomethingWithAItem(item);
sess.evict(item);
}
The Session also provides a contains() method to determine if an instance belongs to the session cache. To completely evict all objects from the session cache, call Session.clear() For the second‐level cache, there are methods defined on SessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role.
sessionFactory.evict(Item.class, itemId); //evict a particular Item
sessionFactory.evict(Item.class); //evict all Items sessionFactory.evictCollection("Item.bids", itemId); //evict a particular collection of bids
sessionFactory.evictCollection("Item.bids"); //evict all bid collections
The CacheMode controls how a particular session interacts with the second‐level cache.
• CacheMode.NORMAL ‐ read items from and write items to the second‐level cache • CacheMode.GET ‐ read items from the second‐level cache, but don't write to the second‐level cache except when updating data • CacheMode.PUT ‐ write items to the second‐level cache, but don't read from the second‐level cache • CacheMode.REFRESH ‐ write items to the second‐level cache, but don't read from the second‐level cache, bypass the effect of hibernate.cache.use_minimal_puts, forcing a refresh of the second‐level cache for all items read from the database
To browse the contents of a second‐level or query cache region, use the Statistics API:
Map cacheEntries = sessionFactory.getStatistics()
.getSecondLevelCacheStatistics(regionName)
.getEntries();
You'll need to enable statistics, and, optionally, force Hibernate to keep the cache entries in a more human understandable format:
hibernate.generate_statistics true
hibernate.cache.use_structured_entries true
The Query Cache
Query result sets may also be cached. This is only useful for queries that are run frequently with the same parameters. To use the query cache you must first enable it:
hibernate.cache.use_query_cache true
This setting causes the creation of two new cache regions ‐ one holding cached query result sets
(org.hibernate.cache.StandardQueryCache), the other holding timestamps of the most recent updates to queryable tables (org.hibernate.cache.UpdateTimestampsCache). Note that the query cache does not cache the state of the actual entities in the result set; it caches only identifier values and results of value type. So the query cache should always be used in conjunction with the second‐level cache.
Most queries do not benefit from caching, so by default queries are not cached. To enable caching, call
Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed.
By Nima Goudarzi ‐ July, 2007
References:
‐ Hibernate3 reference
‐ Hibernate in Action (Manning 2005)
Monday, November 29, 2010
OOPS and CORE JAVA
· What is JVM (Java Virtual Machine)?
· What is JIT (Just- in-Time) Compilation?
· What is Object Oriented Programming?
· What’s a Class?
· What’s an Object?
· What’s the relation between Classes and Objects?
· What are different properties provided by Object-oriented systems?
· How do you implement inheritance in Java?
· How can we implement polymorphism in Java?
· What is an Abstract class?
· What are Abstract methods?
· What’s the difference between “Abstract” classes and “Interfaces”?
· What’s difference between Static and Non-Static fields of a class?
· What are inner classes and what’s the practical implementation of inner classes?
· What are packages?
· What is a constructor in class?
· Can constructors be parameterized?
· What is the use if “instance of” keyword?
· What are Native methods in Java?
· How do refer to a current instance of object?
· Explain in depth Garbage collector?
· How does the garbage collector determine that the object has to be marked for
deletion?
· Can you explain “finalize ()” method?
· How can we force the garbage collector to run?
· What’s the main difference between “Switch” and “If” comparison?
· What’s the use of JAVAP tool?
· What are applets?
· In which package is, the applet class located?
· What are native interfaces in Java?
· What are Class loaders?
· What is Bootstrap, Extension and System Class loader?
· Can you explain the flow between bootstrap, extension and system class loader?
· Can you explain how can you practically do dynamic loading?
· What is Reflection API in Java?
· What’s the difference between static and dynamic class loading?
· How can you copy one array in to a different array?
· Can you explain the core collection interfaces?
· Can you explain in brief the collection classes which implement the collection
interfaces?
· What’s the difference between standard JAVA array and Array List class?
· What’s the use of “ensure Capacity” in Array List class?
· How can we obtain an array from an Array List class?
· What is “Linked List” class for?
· Can you explain Hash Set class in collections?
· What is Linked Hash Set class?
· What is a Tree Set class?
· What’s the use of Comparator Interface?
· How can we access elements of a collection?
· What is Map and SortedMap Interface?
· Have you used any collection algorithm?
· Why do we use collections when we had traditional ways for collection?
· Can you name the legacy classes and interface for collections?
· What is Enumeration Interface?
· What’s the main difference between Array List / Hash Map and Vector / Hash
table?
· Are String object Immutable, Can you explain the concept?
· What is a String Buffer class and how does it differs from String class?
· What is the difference between String Builder and String Buffer class?
· What is Pass by Value and Pass by reference? How does JAVA handle the same?
· What are access modifiers?
· What is Assertion?
· Can you explain the fundamentals of deep and shallow Cloning?
· How do we implement shallow cloning?
· How do we implement deep cloning?
· What’s the impact of private constructor?
· What are the situations you will need a constructor to be private?
· Can you explain final modifier?
· What are static Initializes?
· If we have multiple static initialize blocks how are the sequence handled?
· Define casting? What are the different types of Casting?
· Can you explain Widening conversion and Narrowing conversion?
· Can we assign parent object to child objects?
· Define exceptions?
· Can you explain in short how JAVA exception handling works?
· Can you explain different exception types?
· Can you explain checked and unchecked exceptions?
· Can we create our own exception class?
· What are chained exceptions?
· What is serialization?
· How do we implement serialization actually?
· What’s the use of Externalizable Interface?
· What is JAVA doc utility?
Chapter 2: Threading
· What’s difference between thread and process?
· What is thread safety and synchronization?
· What is semaphore?
· What are monitors?
· What’s the importance of synchronized blocks?
· How do we create threads?
· What’s the difference in using run able and extends in threads?
· Can you explain Thread. Sleep?
· How to stop a thread?
· What is wait () and notify ()?
· Can you explain how Scheduling and Priority works in threads?
· Can you explain Yielding in threading?
· What are daemon threads?
· How do we implement single threaded model in servlets?
Chapter 3: JDBC
· How does JAVA interact with databases?
· Can we interact with non-relational sources using JDBC?
· Can you explain in depth the different sections in JDBC?
· Can you explain in short how you go about using JDBC API in code?
· How do you handle SQL exceptions?
Twist: - (A) Can you explain “SQL Exception” class in detail?
Twist: - (A) what is SQL State in SQL Exceptions?
· If there is more than one exception in SQL Exception” class how to go about
displaying it?
· Explain Type1, Type2, Type3, and Type4 drivers in JDBC?
· What are the advantages and disadvantages of using JDBC-ODBC bridge driver?
· What are the advantages and disadvantages of using Native-API/ Partially Java
Driver?
· What are the advantages and disadvantages of using Net-Protocol/ All-Java
driver?
· What are the advantages and disadvantages of using Native-protocol/ All-Java
driver?
· Advantages of using JDBC-ODBC bridge driver:-
· Disadvantages of using JDBC-ODBC bridge driver:-
· Advantages of using Native-API/ Partially Java Driver:-
· Dis-advantages of using Native-API/ Partially Java Driver:-
· Advantages of using Net-Protocol/ All-Java driver:-
· Disadvantages of using Net-Protocol/ All- Java driver:-
· Advantages of using Native-protocol/ All-Java driver:-
· Disadvantages of using Native-protocol/ All-Java driver:-
· Define meta-data?
· What is Database Metadata?
· Can you explain “Connection Factory” class?
· I want to display tables of a database how do I do it?
· Define “Result Set Meta Data”?
· What is the difference between “Result Set” and “Row Set”?
· Can “Result Set” objects be serialized?
· Explain “Result Set”, “Row Set”, “Cached Row set”, “JdbcRowset” and “Web
Row Set”?
· What are the different types of result set?
· Explain the concept of “Prepared Statement “statement interface?
· What’s the difference between “Statement” and “Prepared Statement”?
· How can we call stored procedure using JDBC?
· Can you explain “Callable Statement” interface in detail?
· How do you get a result set object from stored procedure?
· (A) How can we do batch updates using “Callable Statement” Interface?
· Define transactions?
· What is ACID in transaction?
· What are the four essential properties of a transaction?
· Explain concurrency and locking?
· What are different types of locks?
· What are the different types of levels of resource on which locks can be placed?
· Define lock escalation?
· What is Table level and Row level locking?
· What are the problems that can occur if you do not implement locking properly?
· What are different transaction levels?
· Twist: - what are different types of locks?
· What is difference between optimistic and pessimistic locking?
· What are deadlocks?
· How can we set transaction level through JDBC API?
· Can you explain transaction control in JDBC?
· What are Save points in a transaction?
Chapter 4: Servlets and JSP
· What are Servlets?
· What are advantages of servlets over CGI?
· Can you explain Servlet life cycle?
· What are the two important API’s in for Servlets?
· Can you explain in detail “javax.servlet” package?
· What’s the use of Servlet Context?
· How do we define an application level scope for servlet?
· What's the difference between Generic Servlet and Http Servlet?
· Can you explain in detail javax.servlet.http package?
· What’s the architecture of a Servlet package?
· Why is HTTP protocol called as a stateless protocol?
· What are the different ways we can maintain state between requests?
· What is URL rewriting?
· What are cookies?
· What are sessions in Servlets?
· What the difference is between get Session (true) and get Session (false)?
· What’s the difference between “do Post” and “do get” methods?
· Which are the different ways you can communicate between servlets?
· What is functionality of “Request Dispatcher” object?
· How do we share data using “get Servlet Context ()”?
· Explain the concept of SSI?
· What are filters in JAVA?
· Can you explain in short how do you go about implementing filters using Apache
Tomcat?
· Twist: - Explain step by step of how to implement filters?
· What’s the difference between Authentication and authorization?
· Explain in brief the directory structure of a web application?
· Can you explain JSP page life cycle?
· What is EL?
· How does EL search for an attribute?
· What are the implicit EL objects in JSP?
· How can we disable EL?
· What is JSTL?
· Can you explain in short what the different types of JSTL tags are?
· (I) How can we use beans in JSP?
· What is the use of?
· What is tag for?
· What are JSP directives?
· What are Page directives?
· What are including directives?
· Can you explain taglib directives?
· How does JSP engines instantiate tag handler classes’ instances?
· What’s the difference between JavaBeans and taglib directives?
· What are the different scopes an object can have in a JSP page?
· What are different implicit objects of JSP?
· What are different Authentication Options available in servlets?
· Can you explain how do we practically implement security on a resource?
· How do we practically implement form based authentication?
· How do we authenticate using JDBC?
· Can you explain JDBCRealm?
· Can you explain how do you configure JNDIRealm?
· How did you implement caching in JSP?
· What is the difference between Servletcontext and ServletConfig?
· How do we prevent browser from caching output of my JSP pages?
· Can we explicitly destroy a servlet object?
Chapter 5: EJB
· What is EJB?
· What are the different kind of Ebb’s?
· You are designing architecture for a project how do you decide whether you
should use session, entity or message driven bean?
· Can you explain “EJBHome” and “EJBObject” in EJB?
· Can client directly create object of session or entity beans?
· Can you explain the concept of local interfaces?
· What are the limitations of using Local object?
· Which application server have you used for EJB?
· Can you explain step by step practically developing and deploying EJB
component?
· What is Passivation and Activation in EJB?
· Can beans who are involved in transaction have “Passivation” process?
· How does the server decide which beans to passivity and activate?
· In what format is the conversational data written to the disk?
· Can you explain in brief Life cycle for Stateless and Stateful beans?
Chapter 6: Struts
· (I)What’s MVC pattern?
· (B) Define struts?
· (A) Can you explain the directory structure for a struts folder in brief?
· (I) Can you give an overview of how a struts application flows?
· Twist: - What are action and action form classes in Struts?
Chapter 7: XML and Web Services
· What is XML?
· What is the version information in XML?
· What is ROOT element in XML?
· If XML does not have closing tag will it work?
· Is XML case sensitive?
· What is the difference between XML and HTML?
· Is XML meant to replace HTML?
· Can you explain why your project needed XML?
· What is DTD (Document Type definition)?
· What is well formed XML?
· What is a valid XML?
· What is CDATA section in XML?
· What is CSS?
· What is XSL?
· What is element and attributes in XML?
· What are the standard ways of parsing XML document?
· In What scenarios will you use a DOM parser and SAX parser?
· What is XSLT?
· Define XPATH?
· What is the concept of XPOINTER?
· What is a Web Service?
· What is DISCO?
· What is SOAP?
· What is WSDL?
· Can you explain UDDI?
· Can you explain JAXP?
· What is a XML registry?
· What is JAXR?
· What is JAXM?
· Can you explain JAX-RPC?
· How do you practically implement Web Services?
· How do we consume a web service?
· Are web services Stateful?
Chapter 8: Internationalization
· Can you explain i18n and l10n?
· Can you explain internationalization and localization?
· What is Locale?
· How do we display numbers, currency and Dates according to proper Locale
format?
· what are resource bundles?
· How do we load a resource bundle file?
· How can we do inheritance in resource bundles?
Chapter 9: JNI
· What is Native Interface in JAVA?
· Can you say in brief steps required to implement Native interfaces in Java?
· Can JNI be used for VB6, C# or VB.NET directly?
· What are JNI functions and pointers?
· How does the garbage collector know JNI objects are no more used?
· Twist: - What are the different types of references JNI supports?
· Twist: - How to do you delete global objects?
· How does the native language C or C++ understand data types in JAVA?
· Can you explain exception handling in JNI?
· What are limitations for “JNIEnv” pointer in multi- threading scenarios?
· What are the advantages and disadvantages of using “JNI”?
Chapter 10: Architecture
· What are design patterns?
· Can you list down all patterns and their classification?
· What is the difference between Factory and Abstract Factory Patterns?
· What is MVC pattern?
· How can we implement singleton pattern in JAVA?
· How do you implement prototype pattern in JAVA?
· Can you give a practical implementation of FAÇADE patterns?
· How can we implement observer pattern in JAVA?
· What is three tier architecture?
· What is Service Oriented architecture?
· What is aspect oriented programming?
· How can you implement AOP practically in JAVA?
· What is Inversion of control?
· What is OR mapping?
Chapter 11: UML
· What is UML?
· How many types of diagrams are there in UML?
· What are advantages of using UML?
· What is the sequence of UML diagrams in project?
· Give a small brief explanation of all Elements in activity diagrams?
· Explain Different elements of a collaboration diagram?
· Explain Component diagrams?
· Describe the various components in sequence diagrams?
· What are the elements in State Chart diagrams?
· Describe different elements in Static Chart diagrams?
· Explain the different elements of a Use Case?
Chapter 12: Project Management
· What is project management?
· Is spending in IT projects constant through out the project?
· Who is a stakeholder?
· Can you explain project life cycle?
· Are risk constant through out the project?
· Can you explain different software development life cycles?
· What is triple constraint triangle in project management?
· What is a project baseline?
· What is effort variance?
· How is normally a project management plan document organized?
· (I)How do you estimate a project?
· What is CAR (Causal Analysis and Resolution)?
· What is DAR (Decision Analysis and Resolution)?
· What is a fish bone diagram?
· What is pare to principle?
· How do you handle change request?
· What is internal change request?
· What is difference between SITP and UTP in testing?
· What is the software you have used for project management?
· What are the metrics followed in project management?
· You have people in your team who do not meet there deadlines or do not perform
what are the actions you will take?
· What is black box testing and White box testing?
· What’s the difference between Unit testing, Assembly testing and Regression
testing?
· What is V model in testing?
· How do you start a project?
· How did you do resource allocations?
· How will you do code reviews?
· What is CMMI?
· What are the five levels in CMMI?
· What is continuous and staged representation?
· Can you explain the process areas?
· What is SIX sigma?
· What is DMAIC and DMADV?
· What are the various roles in Six Sigma implementation?
· What are function points?
· What are the different types of elementary process in FPA?
· What are the different elements in Functions points?
· Can you explain in GSC and VAF in function points?
· What are unadjusted function points and how is it calculated?
· Can you explain steps in function points?
· What is the FP per day in your current company?
· Do you know Use Case points?
· What is COCOMO I, COCOMOII and COCOMOIII?
· What is SMC approach of estimation?
· How do you estimate maintenance project and change requests?
Chapter 13: Database
· What is database or database management systems (DBMS)?
· What is SQL?
· What’s difference between DBMS and RDBMS?
· What are CODD rules?
· What are E-R diagrams?
· How many types of relationship exist in database designing? What is
normalization? What are different type of normalization?
· What is denormalization?
· Can you explain Fourth Normal Form?
· Can you explain Fifth Normal Form?
· What’s the difference between Fourth and Fifth normal form?
· Have you heard about sixth normal form?
· What are DML and DDL statements?
· How do we select distinct values from a table?
· What is like operator for and what are wild cards?
· Can you explain Insert, Update and Delete query?
· What is order by clause?
· What is the SQL In clause?
· Can you explain the between clause?
· I have an employee salary table how do we find the second highest from it?
· What are different types of joins in SQL?
· What is “CROSS JOIN”?
· You want to select the first record in a given set of rows?
· What is the default “SORT” order for a SQL?
· What is a self-join?
· What’s the difference between DELETE and TRUNCATE?
· .What are Wildcard operators?
· Twist: - What is like clause in SQL?
· What’s the difference between “UNION” and “UNION ALL”?
· What are cursors and what are the situations you will use them?
· What are the steps to create a cursor?
· What is “Group by” clause?
· What is the difference between “HAVING” and “WHERE” clause?
· What is a Sub-Query?
· What are Aggregate and Scalar Functions?
· Can you explain the SELECT INTO Statement?
· What is a View?
· What is “Correlated Sub queries”?
· What is SQl injection?
· What is “Data Warehousing”?
· What are Data Marts?
· What are Fact tables and Dimension Tables?
· Twist: - What is Dimensional Modeling?
· Twist: - What is Star Schema Design?
· What is Snow Flake Schema design in database?
· Twist: - What’s the difference between Star and Snow flake schema?
· What is ETL process in Data warehousing?
· Twist: - What are the different stages in “Data warehousing”?
· What is “Data mining”?
· Compare “Data mining” and “Data Warehousing”?
· What are indexes?
· What are B-Trees?
· I have a table which has lot of inserts, is it a good database design to create
indexes on that table?
· Twist: - Insert’s are slower on tables which have indexes, justify it?
· Twist: - Why do page splitting happen?
· What are “Table Scan’s” and “Index Scan’s”?
· What are the two types of indexes and explain them in detail?
· Twist: - What’s the difference between clustered and non-clustered indexes
· What is JIT (Just- in-Time) Compilation?
· What is Object Oriented Programming?
· What’s a Class?
· What’s an Object?
· What’s the relation between Classes and Objects?
· What are different properties provided by Object-oriented systems?
· How do you implement inheritance in Java?
· How can we implement polymorphism in Java?
· What is an Abstract class?
· What are Abstract methods?
· What’s the difference between “Abstract” classes and “Interfaces”?
· What’s difference between Static and Non-Static fields of a class?
· What are inner classes and what’s the practical implementation of inner classes?
· What are packages?
· What is a constructor in class?
· Can constructors be parameterized?
· What is the use if “instance of” keyword?
· What are Native methods in Java?
· How do refer to a current instance of object?
· Explain in depth Garbage collector?
· How does the garbage collector determine that the object has to be marked for
deletion?
· Can you explain “finalize ()” method?
· How can we force the garbage collector to run?
· What’s the main difference between “Switch” and “If” comparison?
· What’s the use of JAVAP tool?
· What are applets?
· In which package is, the applet class located?
· What are native interfaces in Java?
· What are Class loaders?
· What is Bootstrap, Extension and System Class loader?
· Can you explain the flow between bootstrap, extension and system class loader?
· Can you explain how can you practically do dynamic loading?
· What is Reflection API in Java?
· What’s the difference between static and dynamic class loading?
· How can you copy one array in to a different array?
· Can you explain the core collection interfaces?
· Can you explain in brief the collection classes which implement the collection
interfaces?
· What’s the difference between standard JAVA array and Array List class?
· What’s the use of “ensure Capacity” in Array List class?
· How can we obtain an array from an Array List class?
· What is “Linked List” class for?
· Can you explain Hash Set class in collections?
· What is Linked Hash Set class?
· What is a Tree Set class?
· What’s the use of Comparator Interface?
· How can we access elements of a collection?
· What is Map and SortedMap Interface?
· Have you used any collection algorithm?
· Why do we use collections when we had traditional ways for collection?
· Can you name the legacy classes and interface for collections?
· What is Enumeration Interface?
· What’s the main difference between Array List / Hash Map and Vector / Hash
table?
· Are String object Immutable, Can you explain the concept?
· What is a String Buffer class and how does it differs from String class?
· What is the difference between String Builder and String Buffer class?
· What is Pass by Value and Pass by reference? How does JAVA handle the same?
· What are access modifiers?
· What is Assertion?
· Can you explain the fundamentals of deep and shallow Cloning?
· How do we implement shallow cloning?
· How do we implement deep cloning?
· What’s the impact of private constructor?
· What are the situations you will need a constructor to be private?
· Can you explain final modifier?
· What are static Initializes?
· If we have multiple static initialize blocks how are the sequence handled?
· Define casting? What are the different types of Casting?
· Can you explain Widening conversion and Narrowing conversion?
· Can we assign parent object to child objects?
· Define exceptions?
· Can you explain in short how JAVA exception handling works?
· Can you explain different exception types?
· Can you explain checked and unchecked exceptions?
· Can we create our own exception class?
· What are chained exceptions?
· What is serialization?
· How do we implement serialization actually?
· What’s the use of Externalizable Interface?
· What is JAVA doc utility?
Chapter 2: Threading
· What’s difference between thread and process?
· What is thread safety and synchronization?
· What is semaphore?
· What are monitors?
· What’s the importance of synchronized blocks?
· How do we create threads?
· What’s the difference in using run able and extends in threads?
· Can you explain Thread. Sleep?
· How to stop a thread?
· What is wait () and notify ()?
· Can you explain how Scheduling and Priority works in threads?
· Can you explain Yielding in threading?
· What are daemon threads?
· How do we implement single threaded model in servlets?
Chapter 3: JDBC
· How does JAVA interact with databases?
· Can we interact with non-relational sources using JDBC?
· Can you explain in depth the different sections in JDBC?
· Can you explain in short how you go about using JDBC API in code?
· How do you handle SQL exceptions?
Twist: - (A) Can you explain “SQL Exception” class in detail?
Twist: - (A) what is SQL State in SQL Exceptions?
· If there is more than one exception in SQL Exception” class how to go about
displaying it?
· Explain Type1, Type2, Type3, and Type4 drivers in JDBC?
· What are the advantages and disadvantages of using JDBC-ODBC bridge driver?
· What are the advantages and disadvantages of using Native-API/ Partially Java
Driver?
· What are the advantages and disadvantages of using Net-Protocol/ All-Java
driver?
· What are the advantages and disadvantages of using Native-protocol/ All-Java
driver?
· Advantages of using JDBC-ODBC bridge driver:-
· Disadvantages of using JDBC-ODBC bridge driver:-
· Advantages of using Native-API/ Partially Java Driver:-
· Dis-advantages of using Native-API/ Partially Java Driver:-
· Advantages of using Net-Protocol/ All-Java driver:-
· Disadvantages of using Net-Protocol/ All- Java driver:-
· Advantages of using Native-protocol/ All-Java driver:-
· Disadvantages of using Native-protocol/ All-Java driver:-
· Define meta-data?
· What is Database Metadata?
· Can you explain “Connection Factory” class?
· I want to display tables of a database how do I do it?
· Define “Result Set Meta Data”?
· What is the difference between “Result Set” and “Row Set”?
· Can “Result Set” objects be serialized?
· Explain “Result Set”, “Row Set”, “Cached Row set”, “JdbcRowset” and “Web
Row Set”?
· What are the different types of result set?
· Explain the concept of “Prepared Statement “statement interface?
· What’s the difference between “Statement” and “Prepared Statement”?
· How can we call stored procedure using JDBC?
· Can you explain “Callable Statement” interface in detail?
· How do you get a result set object from stored procedure?
· (A) How can we do batch updates using “Callable Statement” Interface?
· Define transactions?
· What is ACID in transaction?
· What are the four essential properties of a transaction?
· Explain concurrency and locking?
· What are different types of locks?
· What are the different types of levels of resource on which locks can be placed?
· Define lock escalation?
· What is Table level and Row level locking?
· What are the problems that can occur if you do not implement locking properly?
· What are different transaction levels?
· Twist: - what are different types of locks?
· What is difference between optimistic and pessimistic locking?
· What are deadlocks?
· How can we set transaction level through JDBC API?
· Can you explain transaction control in JDBC?
· What are Save points in a transaction?
Chapter 4: Servlets and JSP
· What are Servlets?
· What are advantages of servlets over CGI?
· Can you explain Servlet life cycle?
· What are the two important API’s in for Servlets?
· Can you explain in detail “javax.servlet” package?
· What’s the use of Servlet Context?
· How do we define an application level scope for servlet?
· What's the difference between Generic Servlet and Http Servlet?
· Can you explain in detail javax.servlet.http package?
· What’s the architecture of a Servlet package?
· Why is HTTP protocol called as a stateless protocol?
· What are the different ways we can maintain state between requests?
· What is URL rewriting?
· What are cookies?
· What are sessions in Servlets?
· What the difference is between get Session (true) and get Session (false)?
· What’s the difference between “do Post” and “do get” methods?
· Which are the different ways you can communicate between servlets?
· What is functionality of “Request Dispatcher” object?
· How do we share data using “get Servlet Context ()”?
· Explain the concept of SSI?
· What are filters in JAVA?
· Can you explain in short how do you go about implementing filters using Apache
Tomcat?
· Twist: - Explain step by step of how to implement filters?
· What’s the difference between Authentication and authorization?
· Explain in brief the directory structure of a web application?
· Can you explain JSP page life cycle?
· What is EL?
· How does EL search for an attribute?
· What are the implicit EL objects in JSP?
· How can we disable EL?
· What is JSTL?
· Can you explain in short what the different types of JSTL tags are?
· (I) How can we use beans in JSP?
· What is the use of
· What is
· What are JSP directives?
· What are Page directives?
· What are including directives?
· Can you explain taglib directives?
· How does JSP engines instantiate tag handler classes’ instances?
· What’s the difference between JavaBeans and taglib directives?
· What are the different scopes an object can have in a JSP page?
· What are different implicit objects of JSP?
· What are different Authentication Options available in servlets?
· Can you explain how do we practically implement security on a resource?
· How do we practically implement form based authentication?
· How do we authenticate using JDBC?
· Can you explain JDBCRealm?
· Can you explain how do you configure JNDIRealm?
· How did you implement caching in JSP?
· What is the difference between Servletcontext and ServletConfig?
· How do we prevent browser from caching output of my JSP pages?
· Can we explicitly destroy a servlet object?
Chapter 5: EJB
· What is EJB?
· What are the different kind of Ebb’s?
· You are designing architecture for a project how do you decide whether you
should use session, entity or message driven bean?
· Can you explain “EJBHome” and “EJBObject” in EJB?
· Can client directly create object of session or entity beans?
· Can you explain the concept of local interfaces?
· What are the limitations of using Local object?
· Which application server have you used for EJB?
· Can you explain step by step practically developing and deploying EJB
component?
· What is Passivation and Activation in EJB?
· Can beans who are involved in transaction have “Passivation” process?
· How does the server decide which beans to passivity and activate?
· In what format is the conversational data written to the disk?
· Can you explain in brief Life cycle for Stateless and Stateful beans?
Chapter 6: Struts
· (I)What’s MVC pattern?
· (B) Define struts?
· (A) Can you explain the directory structure for a struts folder in brief?
· (I) Can you give an overview of how a struts application flows?
· Twist: - What are action and action form classes in Struts?
Chapter 7: XML and Web Services
· What is XML?
· What is the version information in XML?
· What is ROOT element in XML?
· If XML does not have closing tag will it work?
· Is XML case sensitive?
· What is the difference between XML and HTML?
· Is XML meant to replace HTML?
· Can you explain why your project needed XML?
· What is DTD (Document Type definition)?
· What is well formed XML?
· What is a valid XML?
· What is CDATA section in XML?
· What is CSS?
· What is XSL?
· What is element and attributes in XML?
· What are the standard ways of parsing XML document?
· In What scenarios will you use a DOM parser and SAX parser?
· What is XSLT?
· Define XPATH?
· What is the concept of XPOINTER?
· What is a Web Service?
· What is DISCO?
· What is SOAP?
· What is WSDL?
· Can you explain UDDI?
· Can you explain JAXP?
· What is a XML registry?
· What is JAXR?
· What is JAXM?
· Can you explain JAX-RPC?
· How do you practically implement Web Services?
· How do we consume a web service?
· Are web services Stateful?
Chapter 8: Internationalization
· Can you explain i18n and l10n?
· Can you explain internationalization and localization?
· What is Locale?
· How do we display numbers, currency and Dates according to proper Locale
format?
· what are resource bundles?
· How do we load a resource bundle file?
· How can we do inheritance in resource bundles?
Chapter 9: JNI
· What is Native Interface in JAVA?
· Can you say in brief steps required to implement Native interfaces in Java?
· Can JNI be used for VB6, C# or VB.NET directly?
· What are JNI functions and pointers?
· How does the garbage collector know JNI objects are no more used?
· Twist: - What are the different types of references JNI supports?
· Twist: - How to do you delete global objects?
· How does the native language C or C++ understand data types in JAVA?
· Can you explain exception handling in JNI?
· What are limitations for “JNIEnv” pointer in multi- threading scenarios?
· What are the advantages and disadvantages of using “JNI”?
Chapter 10: Architecture
· What are design patterns?
· Can you list down all patterns and their classification?
· What is the difference between Factory and Abstract Factory Patterns?
· What is MVC pattern?
· How can we implement singleton pattern in JAVA?
· How do you implement prototype pattern in JAVA?
· Can you give a practical implementation of FAÇADE patterns?
· How can we implement observer pattern in JAVA?
· What is three tier architecture?
· What is Service Oriented architecture?
· What is aspect oriented programming?
· How can you implement AOP practically in JAVA?
· What is Inversion of control?
· What is OR mapping?
Chapter 11: UML
· What is UML?
· How many types of diagrams are there in UML?
· What are advantages of using UML?
· What is the sequence of UML diagrams in project?
· Give a small brief explanation of all Elements in activity diagrams?
· Explain Different elements of a collaboration diagram?
· Explain Component diagrams?
· Describe the various components in sequence diagrams?
· What are the elements in State Chart diagrams?
· Describe different elements in Static Chart diagrams?
· Explain the different elements of a Use Case?
Chapter 12: Project Management
· What is project management?
· Is spending in IT projects constant through out the project?
· Who is a stakeholder?
· Can you explain project life cycle?
· Are risk constant through out the project?
· Can you explain different software development life cycles?
· What is triple constraint triangle in project management?
· What is a project baseline?
· What is effort variance?
· How is normally a project management plan document organized?
· (I)How do you estimate a project?
· What is CAR (Causal Analysis and Resolution)?
· What is DAR (Decision Analysis and Resolution)?
· What is a fish bone diagram?
· What is pare to principle?
· How do you handle change request?
· What is internal change request?
· What is difference between SITP and UTP in testing?
· What is the software you have used for project management?
· What are the metrics followed in project management?
· You have people in your team who do not meet there deadlines or do not perform
what are the actions you will take?
· What is black box testing and White box testing?
· What’s the difference between Unit testing, Assembly testing and Regression
testing?
· What is V model in testing?
· How do you start a project?
· How did you do resource allocations?
· How will you do code reviews?
· What is CMMI?
· What are the five levels in CMMI?
· What is continuous and staged representation?
· Can you explain the process areas?
· What is SIX sigma?
· What is DMAIC and DMADV?
· What are the various roles in Six Sigma implementation?
· What are function points?
· What are the different types of elementary process in FPA?
· What are the different elements in Functions points?
· Can you explain in GSC and VAF in function points?
· What are unadjusted function points and how is it calculated?
· Can you explain steps in function points?
· What is the FP per day in your current company?
· Do you know Use Case points?
· What is COCOMO I, COCOMOII and COCOMOIII?
· What is SMC approach of estimation?
· How do you estimate maintenance project and change requests?
Chapter 13: Database
· What is database or database management systems (DBMS)?
· What is SQL?
· What’s difference between DBMS and RDBMS?
· What are CODD rules?
· What are E-R diagrams?
· How many types of relationship exist in database designing? What is
normalization? What are different type of normalization?
· What is denormalization?
· Can you explain Fourth Normal Form?
· Can you explain Fifth Normal Form?
· What’s the difference between Fourth and Fifth normal form?
· Have you heard about sixth normal form?
· What are DML and DDL statements?
· How do we select distinct values from a table?
· What is like operator for and what are wild cards?
· Can you explain Insert, Update and Delete query?
· What is order by clause?
· What is the SQL In clause?
· Can you explain the between clause?
· I have an employee salary table how do we find the second highest from it?
· What are different types of joins in SQL?
· What is “CROSS JOIN”?
· You want to select the first record in a given set of rows?
· What is the default “SORT” order for a SQL?
· What is a self-join?
· What’s the difference between DELETE and TRUNCATE?
· .What are Wildcard operators?
· Twist: - What is like clause in SQL?
· What’s the difference between “UNION” and “UNION ALL”?
· What are cursors and what are the situations you will use them?
· What are the steps to create a cursor?
· What is “Group by” clause?
· What is the difference between “HAVING” and “WHERE” clause?
· What is a Sub-Query?
· What are Aggregate and Scalar Functions?
· Can you explain the SELECT INTO Statement?
· What is a View?
· What is “Correlated Sub queries”?
· What is SQl injection?
· What is “Data Warehousing”?
· What are Data Marts?
· What are Fact tables and Dimension Tables?
· Twist: - What is Dimensional Modeling?
· Twist: - What is Star Schema Design?
· What is Snow Flake Schema design in database?
· Twist: - What’s the difference between Star and Snow flake schema?
· What is ETL process in Data warehousing?
· Twist: - What are the different stages in “Data warehousing”?
· What is “Data mining”?
· Compare “Data mining” and “Data Warehousing”?
· What are indexes?
· What are B-Trees?
· I have a table which has lot of inserts, is it a good database design to create
indexes on that table?
· Twist: - Insert’s are slower on tables which have indexes, justify it?
· Twist: - Why do page splitting happen?
· What are “Table Scan’s” and “Index Scan’s”?
· What are the two types of indexes and explain them in detail?
· Twist: - What’s the difference between clustered and non-clustered indexes
Software Architecture Interview Questions
Basic architecture Interview questions
(B) What is the definition of software architecture?
(B) Can you explain your current project architecture?
(B) Which design pattern have you worked with?
(B) Which UML diagram have you used in your project?
(I) what things do you include in the technical document?
(A) Can you explain different software development life cycles?
(I) what is a definition of enterprise architecture?
(B) What is TOGAF ?
(I) Can you explain OOA and OOD ?
(A) What is the concept of load balancing?
(A) Can you explain stateless load balancing?
(I) Can you explain stateful load balancing?
(I) what is round-robin?
(A) Can you explain least connections, weighted distribution and response time ?
OOP
(B) What is OOP?
(B) What are the advantages of using OOP over functional programming?
(B) What are the characteristic of OOP?
(I) Can you explain interfaces?
(B) Can you explain aggregation and composition ?
(B) What are abstract classes?
(B) What’s the difference between abstract classes and interfaces?
(I) Can we create a object of a class whose constructor is private?
UML
(B) Define UML?
(I) Can you explain use case diagrams?
(I) Can you explain primary and secondary actors?
(I) How does a simple use case look like?
(I) Can you explain ‘Extend’ and ‘Include’ in use cases?
(I) Can you explain class diagrams?
(B) How do we represent private, public and protected in class diagrams?
(I) what does associations in a class diagram mean?
(I) Can you explain aggregation and composition in class diagrams?
(A) What are composite structure diagram and reflexive association in class diagrams?
(I) Can you explain business entity and service class?
(I) Can you explain System entity and service class?
(B) Can you explain generalization and specialization?
(B) How do we represent an abstract class and interface UML?
(B) How do we achieve generalization and specialization?
(I) Can you explain object diagrams in UML?
(I) Can you explain sequence diagrams?
(I) Can you explain collaboration diagrams ?
(I) Can you explain activity diagrams?
(I) What is state chart diagram?
(I) Can you explain stereotypes in UML?
(I) Can you explain package diagrams?
(B) Can you explain component diagrams?
(B) Can you explain deployment diagrams?
(I) Can you explain how UML flows in actual project?
Design Patterns
(B) What are design patterns?
(I) Which are the three main categories of design patterns?
(A) Can you explain factory pattern?
(I) Can you explain abstract factory pattern?
(I)Can you explain builder pattern?
(I) Can you explain prototype pattern?
(A) Can you explain shallow copy and deep copy in prototype patterns?
(B) Can you explain singleton pattern?
(A) Can you explain command patterns?
(I) what is Interpreter pattern?
(B) Can you explain iterator pattern?
(A) Can you explain mediator pattern?
(I) Can you explain memento pattern?
(B) Can you explain observer pattern?
(I) Can you explain state pattern?
(I) Can you explain strategy pattern?
(A) Can you explain visitor pattern?
(A) What the difference between visitor and strategy pattern?
(A) Can you explain adapter pattern?
(I) What is fly weight pattern?
(A) Can you explain bridge pattern?
(A) Can you explain composite pattern?
(I) Can you explain decorator pattern ?
(A) Can you explain Façade pattern?
(A) Can you explain chain of responsibility ( COR)?
(I) Can you explain proxy pattern?
(B) Can you explain template pattern?
(B)Can you explain MVC?
(A)What is aspect oriented programming?
(A)What is Inversion of control?
(I)What is OR mapping?
SOA (Service oriented architecture)
(B) What is SOA?
(I) In SOA do we need to build systems from scratch?
(I) Can you explain business layers and plumbing layers in SOA?
(I) what’s the difference between services and components?
(A) Can you describe the complete architecture of SOA?
(I) Can you explain a practical example in SOA?
(I) What are ends, contract, address, and bindings?
(I) Are web-services SOA ?
(B) What is SOAP?
(B) What is WSDL ?
(B) Can you explain UDDI ?
(A) What is BPEL?
(A) What are WS-* specifications?
(A) Can you explain SOA governance?
Estimation, Metrics and Measure
(B) What is meant by measure and metrics?
(B) What are the various common ways of estimation?
(B) Can you explain LOC method of estimation?
(B) How do we convert LOC in to effort?
(B) Can you explain COCOMO?
(I) Can you explain Intermediate COCOMO and COCOMO II?
(B) How do you estimate using LOC?
(A) Can you explain in brief Function points?
(B) Can you explain the concept Application boundary?
(B) Can you explain the concept of elementary process?
(B) Can you explain the concept of static and dynamic elementary process?
(I) Can you explain concept of FTR, ILF, EIF, EI, EO , EQ and GSC ?
(A) How can you estimate number of acceptance test cases in a project?
(I) Can you explain the concept of Use Case’s?
(I) Can you explain the concept of Use case points?
(B) What is a use case transaction?
(B) What is the definition of software architecture?
(B) Can you explain your current project architecture?
(B) Which design pattern have you worked with?
(B) Which UML diagram have you used in your project?
(I) what things do you include in the technical document?
(A) Can you explain different software development life cycles?
(I) what is a definition of enterprise architecture?
(B) What is TOGAF ?
(I) Can you explain OOA and OOD ?
(A) What is the concept of load balancing?
(A) Can you explain stateless load balancing?
(I) Can you explain stateful load balancing?
(I) what is round-robin?
(A) Can you explain least connections, weighted distribution and response time ?
OOP
(B) What is OOP?
(B) What are the advantages of using OOP over functional programming?
(B) What are the characteristic of OOP?
(I) Can you explain interfaces?
(B) Can you explain aggregation and composition ?
(B) What are abstract classes?
(B) What’s the difference between abstract classes and interfaces?
(I) Can we create a object of a class whose constructor is private?
UML
(B) Define UML?
(I) Can you explain use case diagrams?
(I) Can you explain primary and secondary actors?
(I) How does a simple use case look like?
(I) Can you explain ‘Extend’ and ‘Include’ in use cases?
(I) Can you explain class diagrams?
(B) How do we represent private, public and protected in class diagrams?
(I) what does associations in a class diagram mean?
(I) Can you explain aggregation and composition in class diagrams?
(A) What are composite structure diagram and reflexive association in class diagrams?
(I) Can you explain business entity and service class?
(I) Can you explain System entity and service class?
(B) Can you explain generalization and specialization?
(B) How do we represent an abstract class and interface UML?
(B) How do we achieve generalization and specialization?
(I) Can you explain object diagrams in UML?
(I) Can you explain sequence diagrams?
(I) Can you explain collaboration diagrams ?
(I) Can you explain activity diagrams?
(I) What is state chart diagram?
(I) Can you explain stereotypes in UML?
(I) Can you explain package diagrams?
(B) Can you explain component diagrams?
(B) Can you explain deployment diagrams?
(I) Can you explain how UML flows in actual project?
Design Patterns
(B) What are design patterns?
(I) Which are the three main categories of design patterns?
(A) Can you explain factory pattern?
(I) Can you explain abstract factory pattern?
(I)Can you explain builder pattern?
(I) Can you explain prototype pattern?
(A) Can you explain shallow copy and deep copy in prototype patterns?
(B) Can you explain singleton pattern?
(A) Can you explain command patterns?
(I) what is Interpreter pattern?
(B) Can you explain iterator pattern?
(A) Can you explain mediator pattern?
(I) Can you explain memento pattern?
(B) Can you explain observer pattern?
(I) Can you explain state pattern?
(I) Can you explain strategy pattern?
(A) Can you explain visitor pattern?
(A) What the difference between visitor and strategy pattern?
(A) Can you explain adapter pattern?
(I) What is fly weight pattern?
(A) Can you explain bridge pattern?
(A) Can you explain composite pattern?
(I) Can you explain decorator pattern ?
(A) Can you explain Façade pattern?
(A) Can you explain chain of responsibility ( COR)?
(I) Can you explain proxy pattern?
(B) Can you explain template pattern?
(B)Can you explain MVC?
(A)What is aspect oriented programming?
(A)What is Inversion of control?
(I)What is OR mapping?
SOA (Service oriented architecture)
(B) What is SOA?
(I) In SOA do we need to build systems from scratch?
(I) Can you explain business layers and plumbing layers in SOA?
(I) what’s the difference between services and components?
(A) Can you describe the complete architecture of SOA?
(I) Can you explain a practical example in SOA?
(I) What are ends, contract, address, and bindings?
(I) Are web-services SOA ?
(B) What is SOAP?
(B) What is WSDL ?
(B) Can you explain UDDI ?
(A) What is BPEL?
(A) What are WS-* specifications?
(A) Can you explain SOA governance?
Estimation, Metrics and Measure
(B) What is meant by measure and metrics?
(B) What are the various common ways of estimation?
(B) Can you explain LOC method of estimation?
(B) How do we convert LOC in to effort?
(B) Can you explain COCOMO?
(I) Can you explain Intermediate COCOMO and COCOMO II?
(B) How do you estimate using LOC?
(A) Can you explain in brief Function points?
(B) Can you explain the concept Application boundary?
(B) Can you explain the concept of elementary process?
(B) Can you explain the concept of static and dynamic elementary process?
(I) Can you explain concept of FTR, ILF, EIF, EI, EO , EQ and GSC ?
(A) How can you estimate number of acceptance test cases in a project?
(I) Can you explain the concept of Use Case’s?
(I) Can you explain the concept of Use case points?
(B) What is a use case transaction?
Tuesday, October 12, 2010
Hashtable Vs Hashmap, Vector Vs ArrayList
A Map is a class that stores key-value pairs and provides a way to locate a value based on the key. The Hashtable class is a synchronized implementation of the Map interface. The HashMap is better in terms performance because the hashing algorithm it uses. The Hashtable is synchronized so performance is slightly worse.
As to the difference between a Vector and an ArrayList:
I. Synchronization
Vectors are synchronized. Any method that touches the Vector’s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?
II. Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.
III. Usage patterns
Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean? It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.
As to the difference between a Vector and an ArrayList:
I. Synchronization
Vectors are synchronized. Any method that touches the Vector’s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?
II. Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.
III. Usage patterns
Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean? It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.
Java performance tips – Part 1 : Vector, ArrayList & LinkedList
When, where & how to use Vector & ArrayList
Even though both Vector & ArrayList are used for the same purpose – as a dynamic collection of related objects – there is a right time and place to use them. As we all know there is a major difference: Vector is thread-safe but ArrayList is not. If there is no need of synchronization we can use ArrayList instead of Vector. And that will definitely be a performance booster.
When size matters
Internally both Vector & ArrayList uses arrays to hold the elements. Both supports an initialCapacity parameter which decides the initial size of the array. (I really don’t remember the default value). Once if the capacity becomes insufficient to accommodate new elements either of these collections need to expand their capacity. Both Vector & ArrayList do it differently. Vector doubles the current capacity & ArrayList increases the capacity by 50%. Whenever we create a Vector we can specify a capacityIncrement parameter; which is an integer using which the capacity will get incremented whenever the Vector overflows.
Its also advised that, if we know the maximum number of elements that gonna be inserted in to the collection, we should set it as the initialCapacity while creating the collection itself. But its not practically possible every time.
Element access & performance
In both Vector & ArrayList addition/deletion of elements at one end & accessing the elements at a particular index wont take much effort (just O(1) ). But adding or deleting an element at the i-th position will take some effort based on the value of i (O(n-i), where n is the size of the collection). Use of a LinkedList can help us here. B’ coz in a LinkedList addition/deletion of elements is pretty easy as it’s a matter of adjusting the pointers (just O(1)).
LinkedList is good, but…
The problem with LinkedList is that it will create an object for each element being added to the list. Means double the duty for the garbage collector. And as LinkedList is not using arrays to hold elements, it’s a bit painful for it to access elements at a particular index (O(i), where i the index).
So, programmers should decide when to use what based on the requirement.
Even though both Vector & ArrayList are used for the same purpose – as a dynamic collection of related objects – there is a right time and place to use them. As we all know there is a major difference: Vector is thread-safe but ArrayList is not. If there is no need of synchronization we can use ArrayList instead of Vector. And that will definitely be a performance booster.
When size matters
Internally both Vector & ArrayList uses arrays to hold the elements. Both supports an initialCapacity parameter which decides the initial size of the array. (I really don’t remember the default value). Once if the capacity becomes insufficient to accommodate new elements either of these collections need to expand their capacity. Both Vector & ArrayList do it differently. Vector doubles the current capacity & ArrayList increases the capacity by 50%. Whenever we create a Vector we can specify a capacityIncrement parameter; which is an integer using which the capacity will get incremented whenever the Vector overflows.
Its also advised that, if we know the maximum number of elements that gonna be inserted in to the collection, we should set it as the initialCapacity while creating the collection itself. But its not practically possible every time.
Element access & performance
In both Vector & ArrayList addition/deletion of elements at one end & accessing the elements at a particular index wont take much effort (just O(1) ). But adding or deleting an element at the i-th position will take some effort based on the value of i (O(n-i), where n is the size of the collection). Use of a LinkedList can help us here. B’ coz in a LinkedList addition/deletion of elements is pretty easy as it’s a matter of adjusting the pointers (just O(1)).
LinkedList is good, but…
The problem with LinkedList is that it will create an object for each element being added to the list. Means double the duty for the garbage collector. And as LinkedList is not using arrays to hold elements, it’s a bit painful for it to access elements at a particular index (O(i), where i the index).
So, programmers should decide when to use what based on the requirement.
Subscribe to:
Posts (Atom)