Sponsors

Tuesday, July 13, 2010

How to disable user from right click on webpage

Here is the extract of the code which does it.
<script type="text/javascript">

function md(e)
{
try { if (event.button==2||event.button==3) return false; }
catch (e) { if (e.which == 3) return false; }
}
document.oncontextmenu = function() { return false; }
document.ondragstart = function() { return false; }
document.onmousedown = md;

</script>

Two Phase Commit using Hibernate and JTA Transaction Manager

Two Phase Commit works in below steps:

1. Create 2 / multilple Data Source
2. Create 2 / multiple Session Factory
3. Create 2 / multiple DAO's or Repository classes.
4. Create a Single Service class using multiple DAO's / Repository classes to perform distributed database operation.
5. Apply Transaction Demarcation to this Service Class using JTA transaction Manager.

Below is the extract of the spring configuration which is used to do two-phase commit.

<bean id="myDataSource1" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/myds1</value>
</property>
</bean>

<bean id="myDataSource2" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/myds2</value>
</property>
</bean>

<bean id="mySessionFactory1" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="dataSource">
<ref bean="myDataSource1"/>
</property>
</bean>

<bean id="mySessionFactory2" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>inventory.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.OracleDialect</prop>
</props>
</property>
<property name="dataSource">
<ref bean="myDataSource2"/>
</property>
</bean>

<bean id="myTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>

<bean id="myProductDao" class="product.ProductDaoImpl">
<property name="sessionFactory">
<ref bean="mySessionFactory1"/>
</property>
</bean>

<bean id="myInventoryDao" class="product.InventoryDaoImpl">
<property name="sessionFactory">
<ref bean="mySessionFactory2"/>
</property>
</bean>

<bean id="myProductServiceTarget" class="product.ProductServiceImpl">
<property name="productDao">
<ref bean="myProductDao"/>
</property>
<property name="inventoryDao">
<ref bean="myInventoryDao"/>
</property>
</bean>

<bean id="myProductService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="myTransactionManager"/>
</property>
<property name="target">
<ref bean="myProductServiceTarget"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="increasePrice*">PROPAGATION_REQUIRED</prop>
<prop key="someOtherBusinessMethod">PROPAGATION_MANDATORY</prop>
</props>
</property>
</bean>

Sunday, July 11, 2010

How to call store procedure in Hibernate?

Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data.


CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20))
BEGIN
SELECT * FROM stock WHERE stock_code = int_stockcode;
END $$




In Hibernate, there are three approaches to call a database store procedure.


1. Native SQL – createSQLQuery



You can use createSQLQuery() to call a store procedure directly.



Query query = session.createSQLQuery(

"CALL GetStocks(:stockCode)")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");

 
List result = query.list();
for(int i=0; i<result.size(); i++){

Stock stock = (Stock)result.get(i);
System.out.println(stock.getStockCode());

}


2. NamedNativeQuery in annotation


Declare your store procedure inside the @NamedNativeQueries annotation.



//Stock.java
...
@NamedNativeQueries({
@NamedNativeQuery(

name = "callStockStoreProcedure",
query = "CALL GetStocks(:stockCode)",
resultClass = Stock.class
)

})
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable {

...


Call it with getNamedQuery().



Query query = session.getNamedQuery("callStockStoreProcedure")
.setParameter("stockCode", "7277");

List result = query.list();
for(int i=0; i<result.size(); i++){

Stock stock = (Stock)result.get(i);
System.out.println(stock.getStockCode());

}


3. sql-query in XML mapping file


Declare your store procedure inside the “sql-query” tag.



<!-- Stock.hbm.xml -->
...
<hibernate-mapping>
<class name="com.mkyong.common.Stock" table="stock" ...>

<id name="stockId" type="java.lang.Integer">
<column name="STOCK_ID" />

<generator class="identity" />
</id>
<property name="stockCode" type="string">

<column name="STOCK_CODE" length="10" not-null="true" unique="true" />

</property>
...
</class>
 
<sql-query name="callStockStoreProcedure">
<return alias="stock" class="com.mkyong.common.Stock"/>

<![CDATA[CALL GetStocks(:stockCode)]]>
</sql-query>
 
</hibernate-mapping>


Call it with getNamedQuery().



Query query = session.getNamedQuery("callStockStoreProcedure")

.setParameter("stockCode", "7277");
List result = query.list();

for(int i=0; i<result.size(); i++){
Stock stock = (Stock)result.get(i);

System.out.println(stock.getStockCode());
}

Wednesday, July 7, 2010

What is the difference between URI, URL and URN?

URI

An URI identifies a resource. It is a locator. It includes a URI scheme, authority, path, query and fragment by syntax. For example, http: is a URI scheme.

A URI identifies a resource either by location, or a name, or both. More often than not, most of us use URIs that defines a location to a resource. The fact that a URI can identify a resources by both name and location has lead to a lot of the confusion in my opionion. A URI has two specializations known as URL and URN.

URN

The term “Uniform Resource Name” (URN) is used to identify a resource independent of its location. Example urn:ISBN:1-23-432536-5

A URI identifies a resource by name in a given namespace but not define how the resource maybe obtained. This type of URI is called a URN. You may see URNs used in XML Schema documents to define a namespace, usually using a syntax such as:

<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:example"

Here the targetNamespace use a URN. It defines an identifier to the namespace, but it does not define a location.

URL

The term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network “location”).

A URL is a specialization of URI that defines the network location of a specific resource. Unlike a URN, the URL defines how the resource can be obtained. We use URLs every day in the form of http://learnjavaindetail.blogspot.com, etc. But a URL doesn’t have to be an HTTP URL, it can be ftp://learnjavaindetail.blogspot.com, smb://learnjavaindetail.blogspot.com, etc.

What is JVM JRE JDK JIT ?

Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.

JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built upon. It is the component of the Java technology responsible for its hardware and platform independence. JVM largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their programmes from JDK.


Internals

Like a real computing machine, JVM has an instruction set and manipulates various memory areas at run time. Thus for different hardware platforms one has corresponding implementation of JVM available as vendor supplied JREs. It is common to implement a programming language using a virtual machine. Historicaly the best-known virtual machine may be the P-Code machine of UCSD Pascal.

A Java virtual machine instruction consists of an opcode specifying the operation to be performed, followed by zero or more operands embodying values to be operated upon. From the point of view of a compiler, the Java Virtual Machine (JVM)is just another processor with an instruction set, Java bytecode, for which code can be generated. Life cycle is as follows, source code to byte code to be interpreted by the JRE and gets converted to the platform specific executable ones.

Sun’s JVM

Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE. Sun’s JRE is availabe as a separate application and also available as part of JDK. Sun’s Java Development Tool Kit (JDK) comes with utility tools for byte code compilation “javac”. Then execution of the byte codes through java programmes using “java” and many more utilities found in the binary directory of JDK. ‘java’ tools forks the JRE. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

Just-in-time Compiler (JIT)

JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

What is cloning in Javva? What is Shallow Cloning and Deep Cloning ?

Clone is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In real world, if you clone Marilyn Monroe, will you get a copy of her with same beauty and characteristics? No, you will not get! This exactly applies to java also. See how java guys are good at naming technologies.

In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones. If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory method and provide it with a good documentation. When you are in a situation to use a third party component and produce copies of it using the clone method, then investigate that implementation carefully and get to know what is underlying. Because when you ask for a rabbit, it may give monkeys!

Shallow Copy

Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.

Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.

Deep Copy

When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.

One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like ArrayList by name. This completely removes the advantage and goodness of abstractness.

When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw a CloneNotSupportedException.

Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.

Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.

Static Binding vs Dynamic Binding

Difference between Dynamic Binding & Static Binding in Java

Dynamic Binding or Late Binding

Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only. Let's try to understand this. Suppose we have a class named 'SuperClass' and another class named 'SubClass' extends it. Now a 'SuperClass' reference can be assigned to an object of the type 'SubClass' as well. If we have a method (say 'someMethod()') in the 'SuperClass' which we override in the 'SubClass' then a call of that method on a 'SuperClass' reference can only be resolved at runtime as the compiler can't be sure of what type of object this reference would be pointing to at runtime.

...
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
...

superClass1.someMethod(); // SuperClass version is called
superClass2.someMethod(); // SubClass version is called
....

Here, we see that even though both the object references superClass1 and superClass2 are of type 'SuperClass' only, but at run time they refer to the objects of types 'SuperClass' and 'SubClass' respectively.

Hence, at compile time the compiler can't be sure if the call to the method 'someMethod()' on these references actually refer to which version of the method - the super class version or the sub class version.

Thus, we see that dynamic binding in Java simply binds the method calls (inherited methods only as they can be overriden in a sub class and hence compiler may not be sure of which version of the method to call) based on the actual object type and not on the declared type of the object reference.

Static Binding or Early Binding

If the compiler can resolve the binding at the compile time only then such a binding is called Static Binding or Early Binding. All the instance method calls are always resolved at runtime, but all the static method calls are resolved at compile time itself and hence we have static binding for static method calls. Because static methods are class methods and hence they can be accessed using the class name itself (in fact they are encourgaed to be used using their corresponding class names only and not by using the object references) and therefore access to them is required to be resolved during compile time only using the compile time type information. That's the reason why static methods can not actually be overriden.

What is a java marker interface? Is there any alternative to marker interface ?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.

Alternative to marker interface

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

Tuesday, July 6, 2010

How to add a Bookmarks and SetAsHomePage link on webpage

<script>
function addfav()
{
var BookmarkURL = "http://www.learnjavaindetail.blogspot.com"
var BookmarkTitle = "Java FAQ's"
if (document.all)
{
// Add to Favorites (Internet Explorer)
window.external.AddFavorite(BookmarkURL, BookmarkTitle)
}
else
{
// Add to Bookmarks (Mozilla Firefox)
window.sidebar.addPanel(BookmarkTitle, BookmarkURL, '');
}
}

function setHomepage()
{
if (document.all)
{
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage('http://www.learnjavaindetail.blogspot.com');
}
else if (window.sidebar)
{
if (window.netscape)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch(e)
{
alert("this action was aviod by your browser,if you want to enable,please enter about:config in your address line,and change the value of signed.applets.codebase_principal_support to true");
}
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage', 'http://www.learnjavaindetail.blogspot.com');
}
}
</script>
<a href="javascript:addfav()">Add To Favorites</a>
<a href="javascript:setHomepage()">Set As Homepage</a>

Thursday, July 1, 2010

Command Design Pattern

When two objects communicate, often one object is sending a command to the other object to perform a particular function. The most common way to accomplish this is for the first object (the "issuer") to hold a reference to the second (the "recipient"). The issuer executes a specific method on the recipient to send the command.

But what if the issuer is not aware of, or does not care who the recipient is? That is, the issuer simply wants to abstractly issue the command?

The Command design pattern encapsulates the concept of the command into an object. The issuer holds a reference to the command object rather than to the recipient. The issuer sends the command to the command object by executing a specific method on it. The command object is then responsible for dispatching the command to a specific recipient to get the job done.

Note the similarities between the Command design pattern and the Strategy design pattern.

In the above diagram, the invoker holds an abstract command and issues a command by calling the abstract execute() method. This command is translated into a specific action on a specific receiver by the various concrete command objects. It is also possible for a command to be a collection of commands, called a "macro" command. Calling the execute method of a macro command will invoke a collection of commands.

Monday, June 28, 2010

What is SQL SELECT INTO ?

The SELECT INTO statement is usually used to create backup copies of tables.
That also explain that SELECT INTO creates a new table and fills it with data computed by a query.

SELECT INTO syntax is:

SELECT [COLUMN NAME 1], [COLUMN NAME 2] ,...
INTO [BACKUP TABLE NAME]
FROM[TABLE NAME]


EXAMPLE 1 :

Let’s say we want to create a copy of the GameScores table and data.

SQL Statement:

SELECT * INTO GameScores_backup
FROM GameScores

SELECT INTO statement also can export the backup data to another database, let's see the example 2.


EXAMPLE 2 :

Let’s say we want to create a copy of the GameScores table and data to another database name backup_database.

SQL Statement:

SELECT * INTO GameScores_backup IN 'backup_database.mdb'
FROM GameScores

What is SQL Alias? What are types of SQL Alias?

There are two types of aliases that are used most frequently in SQL command: which is column alias and table alias.

Why ALIAS? There is some reasons alias to be use when querying a SQL command.

- alias in a long query can make your query easier to read and understand
- alias table is use when using a same table in one query
- alias column is to identify the column naming when used together with aggregate functions, then the column can be understand easily

Syntax for Column Name Alias is :

SELECT [COLUMN NAME] AS COLUMN_ALIAS FROM [TABLE NAME]

Syntax for Table Name Alias is :

SELECT [COLUMN NAME] FROM [TABLE NAME] AS TABLE_ALIAS

Exmaple for Table Alias

select a.* from mytable as a;


Exmaple for Column Alias

select count(*) as total from mytable;

what is SQL CROSS JOIN

SQL CROSS JOIN will return all records where each row from the first table is combined with each row from the second table. Which also mean CROSS JOIN returns the Cartesian product of the sets of rows from the joined tables.

A CROSS JOIN can be specified in two ways: using the JOIN syntax or by listing the tables in the FROM clause separated by commas without using a WHERE clause to supply join criteria.

SQL CROSS JOIN syntax:

SELECT * FROM [TABLE 1] CROSS JOIN [TABLE 2]

OR

SELECT * FROM [TABLE 1], [TABLE 2]


EXAMPLE :

Let's try with 2 tables below:

Table 1: GameScores

PlayerNameDepartmentIdScores
Jason13000
Irene11500
Jane21000
David22500
Paul32000
James32000

Table 2: Departments

DepartmentIdDepartmentName
1IT
2Marketing
3HR

SQL statement :

SELECT* FROM GameScores CROSS JOIN Departments

Result:

PlayerNameDepartmentIdScoresDepartmentIdDepartmentName
Jason130001IT
Irene115001IT
Jane210001IT
David225001IT
Paul320001IT
James320001IT
Jason130002Marketing
Irene115002Marketing
Jane210002Marketing
David225002Marketing
Paul320002Marketing
James330002Marketing
Jason130003HR
Irene115003HR
Jane210003HR
David225003HR
Paul320003HR
James330003HR

Saturday, June 26, 2010

Re-entrant and Non Re-entrant Code

Re-entrant means that once a method is called on your object, it should be possible for someone else to call that method. For an example of something that’s non-re-entrant the IBM XML Parser (version 1.x) comes to mind. When certain methods are called on the IBM DOM parser, and exceptions are thrown the entire object becomes frozen and no one can call any more methods on that object. This is an example of non-reentrant code.

Thread-safe vs. threaded classes

When you make thread-safe classes, you have to keep in mind that multiple threads could be trampling through the methods of your class. This requires special care in designing and coding these classes, becuase there is no way of knowing what thread will invoke what method (and in what sequence) on an object of this class. You have to take into account all possible scenarios or design in such a way that the number of possible states that your object can reach is minimized. I prefer to use the smart solution and design in such a way that the number of states my object can reach is minimized, that way I don’t have to think about too many possibilities of what might happen when multiple threads are trampling through the same instance of my class.

In order to make thread-safe classes there are a few simple rules to follow:

  • Mutator method access to any shared objects must be synchronized.
  • Accessor method access to any shared objects need not be synchronized.
    • There is an exception to this rule however. When your shared object’s value fluctuates very frequently (like stock prices), then it is necessary to synchronize the accessor too, in order to report the correct value of the object rather than some intermediate (and inaccurate) value of the object. There are more advanced techniques to get around making your accessors synchronized which I will show you in the advanced thread tutorial. But for now, be sure to synchronize everything!

Difference between Thread Class and Runnable interface



The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.

What does volatile do?

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

         int i1;              int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}

geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

  1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
  2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
  3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
  4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
  5. The thread releases the lock on the monitor for object this.

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

Friday, June 25, 2010

Difference between _jspService() and other life cycle methods.

JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().

The contents what we write in the JSP will go into _jspService() because we are implicitly implementing it. If we again try to override it explicitly, JSP compliler will giver error as ‘the method is already implemented and cannot override’. But in the case of other two methods we are not implementing it in the JSP. Therefore the JSP compiler will allow to override jspInit() and jspDestroy().

To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes.

What happens if you call destroy() from init() in java servlet?

destroy() gets executed and the initialization process continues. It is a trick question in servlets interview.

In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().

The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.

Why not declare a constructor in servlet?

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.

Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.

Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.

What is a java marker interface? Is there any alternate way that can serve the same purpose as marker interface?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

why inner class can access only final variable?

Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren’t final then the copy of the variable in the method could change, while the copy in the local class didn’t, so they’d be out of synch.


Anonymous inner classes require final variables because of the way they are implemented in Java. An anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the value of the local variable. The inner class isn’t actually using the local variable, but a copy. It should be fairly obvious at this point that a “Bad Thing”™ can happen if either the original value or the copied value changes; there will be some unexpected data synchronization problems. In order to prevent this kind of problem, Java requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees that the inner class’ copies of local variables will always match the actual values.

Difference between Hashtable and ConcurrentHashMap

ConcurrentHashMap is a pretty ignored class. Not many people know about it and not many people care to use it. The class offers a very robust and fast (comparatively, we all know java concurrency isn’t the fastest) method of synchronizing a Map collection.

I have read a few comparisons of HashMap and ConcurrentHashMap on the web. Let me just say that they’re totally wrong. There is no way you can compare the two, one offers synchronized methods to access a map while the other offers no synchronization whatsoever. What most of us fail to notice is that while our applications, web applications especially, work fine during the development & testing phase, they usually go tits up under heavy (or even moderately heavy) load. This is due to the fact that we expect our HashMap’s to behave a certain way but under load they usually misbehave.

Hashtable’s offer concurrent access to their entries, with a small caveat, the entire map is locked to perform any sort of operation. While this overhead is ignorable in a web application under normal load, under heavy load it can lead to delayed response times and overtaxing of your server for no good reason.

This is where ConcurrentHashMap’s step in. They offer all the features of Hashtable with a performance almost as good as a HashMap. ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.

Retrieval operations on a ConcurrentHashMap do not block unless the entry is not found in the bucket or if the value of the entry is null. In such a case the map synchronizes on the bucket and then tries to look for the entry again just in case the entry was put or removed right after the get in synchronized mode.

Removal operations do require a bit of overhead. All removal operations require the chain of elements before and after to be cloned and joined without the removed element. Since the value of the map key is volatile (not really, the value of the inner Entry class is volatile) if a thread already traversing the bucket from which a value is removed reaches the removed element, it automatically sees a null value and knows to ignore such a value.

Traversal in a ConcurrentHashMap does not synchronize on the entire map either. Infact traversal does not synchronize at all except under one condition. The internal LinkedList implementation is aware of the changes to the underlying collection. If it detects any such changes during traversal it synchronizes itself on the bucket it is traversing and then tries to re-read the values. This always insures that while the values recieved are always fresh, there is minimalistic locking if any.

Iteration over a ConcurrentHashMap are a little different from those offered by other collections. The iterators are not fail-fast in the sense that they do not throw a ConcurrentModificationException. They also do not guarantee that once the iterator is created it will list/show all elements that are added after its creation. The iterators do however guarantee that any updates or removal of items will be reflected correctly in their behaviour. They also guarantee that no element will be returned more than once while traversal.

In conclusion, give it a try, replace some Hashtable’s in your application with ConcurrentHashMap and see how they perform under load. The two are interchangeable so it shouldn’t be hard to update your app. Happy changing!