You are on page 1of 141

Technical Words

===============
Race Condition:
Semaphone in

Difference between association and aggregation (while programming implementation


for both):
the main difference is conceptual - Aggregation says that an object is made up o
f other objects, and association says that they have a relationship, they know o
f each other, or they use each other in some way.
As far as programming, the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here, but the child making u
p the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships, going from 1-1, all the way up to *-*.
To clarify, when implementing aggregation Car and Tire, the Car has an aggregati
on to Tire, and the car has between 4-5 Tire (as an example, one is spare in the
trunk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car, you have to check that it has at least 4 and no mo
re than 5 tires, and when implementing the Tire, you have to at all times have a
reference to the Car (which means passing the Car reference in the constructor)
. Furthermore, when the Car reference is set to null, you have to pro grammatica
lly make sure that the Tire references are also set to null in case of Aggregati
on but if u model your system as Car just having an association to Tire, this mi
ght not necessarily be true.
Above answer was rated as good by the following members:
dasarishiva
April 20, 2007 07:09:29
rashmitambe Member Since: April 2007 Contribution: 3
RE: how to identify strong aggregation (composition) r...
In strong aggregation or composition a part entity cannot exist without the cont
aining whole entity in 'whole-part' relationship.
For example. an university has multiple department. This a composition relations
hip between university and department entity. A department cannot exist on its o
wn with out the university.

Deadlock - what's it? How to deal with a Deadlock situation?


hat's Deadlock?

It's basically a situation where two or more threads are blocked forever waiting
for each other to release an acquired monitor to proceed further.

Let me try to explain it using an example. Suppose we have two thread - threadA
and threadB. There are two objects of a class TestClass - objA and objB and we h
ave two synchronized instance methods in TestClass named A and B. Method A accep
ts an argument of type TestClass and calls method B from the passed object refer
ence. Now, consider a situation where the first thread - threadA acquires the mo
nitor of objA and enteres into the synchronized method A() on objA with the pass
ed object reference as objB and at the same time threadB enteres into the same s
ynchronized method 'A' on the object reference - objB with the passed object ref
erence to the method as objA. Now, both the threads will keep waiting for the mo
nitors of the objects - objB and objA respectively to complete the execution of
the synchronized method A() and hence such a situation will result into a Deadlo
ck. Of course such a situation will probably happen only rarely, but it's defini
tely a possible scenario. Calling the start() method on a Thread instance only e
nsures that the particular thread will participate in the CPU Scheduling, but we
never know when exactly the thread will actually be allocated the CPU and in tu
rn will start the execution.

Example: Java program having a possibility of Deadlock

public class PossibleDeadlockDemo {

static class TestClass {


...
...

public synchronized void A (TestClass testClass) {


...
testClass.B();
}

public synchronized void B () {


...
}
}

public static void main(String[] args) {


final TestClass objA = new TestClass("ObjectA");
final TestClass objB = new TestClass("ObjectB");

Thread threadA = new Thread(new Runnable() {


public void run() { objA.A(objB); } });

Thread threadB = new Thread(new Runnable() {


public void run() { objB.A(objA); } });

threadA.start();
threadB.start();
}

How to deal with a Deadlock situation?

Probably the only possible way to rectify a Deadlock situation is to avoid it. O
nce the deadlock has already happened then you'll probably left with the only op
tion of restarting the JVM process again OR it may even require you to restart t
he underlying OS. This is very hard to reproduce and debug because one can never
be sure about when exactly the threads will be executed and hence the deadlock
may not happen when you test it and eventually it may happen when the code actua
lly goes into production. So, review the design of your mulithreaded application
before you really start coding. You may somehow manage to escape any such situa
tion or at least minimize the possibility to a great extent with a better design
.
=================================================================
Composition vs Aggregation. How is Association related to them?

Association - it's a structural relationship between two classifiers - classes o


r use cases. Cyclic association is also possible when the same entity plays two
different roles and contains an association describing the relationship between
the two roles.

In UML notation an association is depicted by a solid line. For example: suppose


we have two entities Employee (EmpNo, Name, EmailId, Salary, DeptNo, Address) a
nd Department (DeptNo, DeptName). Now these two entities are having an associati
on. An association can have any cardinality at any of the two ends depening on t
he particular relationship.

Aggregation - this is special type of association used for modelling 'Possession


' (not Ownership) with the restriction that it's NOT cyclic. That means, an enti
ty can't have an aggregation relationship with itself. This is the reason why an
aggregation relationship doesn't form a Graph, instead it forms a Tree.

Aggegation is normally understood as a "has-a" relationship. Here both the entit


ies continue to have their own independent existence. In UML notation, an aggreg
ation is depicted by an unfilled diamond and a solid line. For example: Consider
two entities Employee (EmpNo, Name, EmailId, Salary, DeptNo, Address) and Addre
ss (FlatNo, PlotNo, StreetName, Area, PinCode). As we might have noticed that ev
ery Employee has an Address, but the lifetime of the an Address instance is not
governed by any Employee instance. It may continue to exist even after the recla
imation of the Employee instance. Right?

Composition - this is also a special type of association used for modelling 'Own
ership'. This is very similar to Aggregation with the only difference that it de
picts a Whole-part relationship and the 'part' entity doesn't have its own indep
endent existence. The existence of entity depicting 'whole' giverns the lifetime
of the 'part' entity as well. For example: Consider two entities Employee (EmpN
o, Name, EmailId, Salary, DeptNo, Address) and EmailId (ID, domain). Now an inde
pendent instance of EmailId entity doesn't really make sense unless it's associa
ted with an Employee instance.

Composition is normally understood as a "contains-a" relations. Similar to Aggre


gation, a Composition also forms a Tree only and not a Graph as it can't be cycl
ic. In UML notation, a Compsoition is depicted by a filled diamond and a solid l
ine.

Aggregation vs Composition
* Aggregation represents a "has-a" relationship whereas Composition represen
ts a "contains-a" OR "whole-part" relationship.
* In case of Aggregation, both the entities will continue to have their inde
pendent existence whereas in case of Composition the lifetime of the entity repr
esenting 'part' of the "whole-part" is governed by the entity representing 'whol
e'.
* Aggregation represents a loose form of relationship as compared to that re
presented by Composition which depicts a stronger relationship.
* In UML notation, an Aggregation relationship is depicted by an unfilled di
amond and a solid line whereas a Composition relationship is depicted by a fille
d diamond and a solid line.
* A 'part' of a Composition relationship can have only one 'whole' at a time
i.e., a multiplicity of 1 whereas an Aggregation relationship can have any mult
iplicity 0..* at the aggregate end.
=================================================================
Concurrent execution of static and non-static synchronized methods

We have a scenario where we have a static synchronized method and a non-static s


ynchronized method. As we know that a static method can only access static membe
rs of the class whereas a non-static method can access both static as well as no
n-static members. This liberty can put us into a situation where a non-static me
thod might be updating some static data which a static method would also be chan
ging. What will happen if two different threads try to access the static and non
-static synchronized methods concurrently and in turn try to change the static d
ata using the two methods? Will the synchronization guarantee mutual exclusion i
n such a case?

No... synchronization won't guarantee mutual exclusion in such a case as both th


e threads may access the static and non-static synchronized methods concurrently
because a non-static synchronized method requires the invoking thread to acquir
e a lock of the particular object on which the thread invokes the non-static syn
chronized method whereas a static synchronized method will require the invoking
thread to acquire a lock on the java.lang.Class object associated with the parti
cular class (which the static method is a part of). Both these locks have nothin
g to do with each other and they can be acquired by different threads at the sam
e time and hence two different threads may execute a static method and a non-sta
tic synchronized method of a class respectively at the same time (of course once
they acquire the two locks).

It is certainly not advisable to allow such a thing to happen and hence the desi
gn of such a class needs to be re-checked. Otherwise the errors caused by simult
aneaous modification of the same static data by different threads may infuse som
e really-hard-to-detect bugs.
Thus, we see that only declaring the methods as synchronized doesn't ensure mutu
al exclusion and the programmer should always think about the locks involved to
achieve the actual purpose of synchronization.

Have a look at the following simple example where the same static data is being
modified by two public synchronized methods - one being static and the other bei
ng non-static. The whole purpose of synchronization is getting defeated here as
in such a case mutual exclusion can't be guaranteed, which is one of main purpos
es of using synchronization.

public final class BadDesign{


private static int sensitiveData;
public synchronized static void changeDataViaStaticMethod(int a){
//... updating the sensitiveData
sensitiveData = a;
}

public synchronized void changeDataViaNonStaticMethod(int b){


//... updating the sensitiveData
sensitiveData = b;
}

public static void showSensitiveDataStatic(){


System.out.println("Static: " + Thread.currentThread().getName()+ " - " + sensit
iveData);
}

public void showSensitiveData(){


System.out.println(Thread.currentThread().getName() + " - " + sensitiveData);
}

public static void main(String[] args){


new Thread(new TestThread11()).start();
new Thread(new TestThread11()).start();
}

}
class TestThread11 implements Runnable{

public void run(){


int i = 0;
do{
BadDesign.changeDataViaStaticMethod(5);
BadDesign.showSensitiveDataStatic();

//... new object for every iteration


//... so synchronization of non-static method
//... doesn't really do anything significant here
BadDesign bd = new BadDesign();
bd.changeDataViaNonStaticMethod(10);
bd.showSensitiveData();
}while (i++ < 100);
}
}

An excerpt from the output:-


...
Static: Thread-0 - 5
Thread-0 - 10
Static: Thread-0 - 5
Thread-0 - 10
Thread-1 - 10
Static: Thread-0 - 5
Static: Thread-1 - 5
Thread-1 - 10
...

By looking at the above exceprt you can easily conclude that the static and non-
static synchronized method calls are intermixed between the two threads: Thread-
0 and Thread-1. In this case the non-static synchronized method is always being
called on a new object (as the do-while loop of the run() method is creating a n
ew object of the class BadDesign for every non-static synchronized method call)
by both the threads and hence synchronization doesn't really do anything signifi
cant for them as every new object will have its own lock which will be easily ac
quired by the invoking thread everytime the do-while loop iterates. I've kept th
is just to make the code simple as my purpose of the above example is just to sh
ow that static synchronized methods and non-static synchronized methods are comp
letely independent of each other and both of them can run at the same time by di
fferent threads for the simple reason that both these methods are governed by di
fferent locks which may be acquired at the same time by two different threads.
=================================================================
Composition vs Aggregation. How is Association related to them?

Association - it's a structural relationship between two classifiers - classes o


r use cases. Cyclic association is also possible when the same entity plays two
different roles and contains an association describing the relationship between
the two roles.

In UML notation an association is depicted by a solid line. For example: suppose


we have two entities Employee (EmpNo, Name, EmailId, Salary, DeptNo, Address) a
nd Department (DeptNo, DeptName). Now these two entities are having an associati
on. An association can have any cardinality at any of the two ends depening on t
he particular relationship.

Aggregation - this is special type of association used for modelling 'Possession


' (not Ownership) with the restriction that it's NOT cyclic. That means, an enti
ty can't have an aggregation relationship with itself. This is the reason why an
aggregation relationship doesn't form a Graph, instead it forms a Tree.

Aggegation is normally understood as a "has-a" relationship. Here both the entit


ies continue to have their own independent existence. In UML notation, an aggreg
ation is depicted by an unfilled diamond and a solid line. For example: Consider
two entities Employee (EmpNo, Name, EmailId, Salary, DeptNo, Address) and Addre
ss (FlatNo, PlotNo, StreetName, Area, PinCode). As we might have noticed that ev
ery Employee has an Address, but the lifetime of the an Address instance is not
governed by any Employee instance. It may continue to exist even after the recla
imation of the Employee instance. Right?

Composition - this is also a special type of association used for modelling 'Own
ership'. This is very similar to Aggregation with the only difference that it de
picts a Whole-part relationship and the 'part' entity doesn't have its own indep
endent existence. The existence of entity depicting 'whole' giverns the lifetime
of the 'part' entity as well. For example: Consider two entities Employee (EmpN
o, Name, EmailId, Salary, DeptNo, Address) and EmailId (ID, domain). Now an inde
pendent instance of EmailId entity doesn't really make sense unless it's associa
ted with an Employee instance.

Composition is normally understood as a "contains-a" relations. Similar to Aggre


gation, a Composition also forms a Tree only and not a Graph as it can't be cycl
ic. In UML notation, a Compsoition is depicted by a filled diamond and a solid l
ine.
Aggregation vs Composition
* Aggregation represents a "has-a" relationship whereas Composition represen
ts a "contains-a" OR "whole-part" relationship.
* In case of Aggregation, both the entities will continue to have their inde
pendent existence whereas in case of Composition the lifetime of the entity repr
esenting 'part' of the "whole-part" is governed by the entity representing 'whol
e'.
* Aggregation represents a loose form of relationship as compared to that re
presented by Composition which depicts a stronger relationship.
* In UML notation, an Aggregation relationship is depicted by an unfilled di
amond and a solid line whereas a Composition relationship is depicted by a fille
d diamond and a solid line.
* A 'part' of a Composition relationship can have only one 'whole' at a time
i.e., a multiplicity of 1 whereas an Aggregation relationship can have any mult
iplicity 0..* at the aggregate end.
=================================================================
Alternatives of stop, suspend, resume of a Thread

Did you go through the first part of the article which discussed - Why Thread.st
op() method is deprecated in Java? Why ThreadDeath is a subclass of Error and no
t of Exception? Can't we catch the ThreadDeath and fix the damaged objects? What
will happen if stop() method is called on a thread which is yet to start? ... Y
ou may like to go through the first part before proceeding with this part.
This part of the article tries to answer the following questions:-
* What should we do instead of using stop() method?
* How can we stop a long waiting (maybe due to I/O) thread?
* What if a thread doesn't respond to Thread.interrupt() call?
* Why are Thread.suspend & Thread.resume deprecated?
* What should be done instead of using suspend & resume?
* What's Thread.destroy()?
What should be done instead of using stop() method?
If stop() is deprecated and therefore suggested not to be used then how should a
situation requiring the usage of stop() method should be handled? Good question
... we can follow the recommended approach by Sun which requires to have a varia
ble, which should either be volatile or the access to the variable should be syn
chronized. The thread will check this variable regularly and hence the thread ma
y be stopped in an orderly fashion by setting an appropriate value to the variab
le which will communicate the thread that it should stop in an orderly way now.
For example:
Instead of having the stop() as
...
private Thread theCurrentThread;
...
public void run(){
theCurrentThread = Thread.currentThread();
...
...
}
public void stop(){
theCurrentThread.stop();
}
we can have a graceful and safe stop as
...
public void stop(){
theCurrentThread = null;
}
What'll happen if we use the above mentioned graceful stop alternative on a thre
ad which is into an infinite loop? Read this article to understand that - Impact
of assigning null to a running thread executing an infinite loop >>.
How can we stop a thread that waits for long periods maybe for I/O?
We can follow the same graceful stop technique discussed above in this case as w
ell. We just need to call the interrupt() method of the thread after assigning n
ull to the thread. For example, we may have the stop method as:-
...
public void stop(){
Thread t = theCurrentThread;
theCurrentThread = null;
t.interrupt();
}
Why do we need to have another reference to call interrupt() on? Why don't we ca
ll on the same thread reference 'theCurrentThread' in this case? Easy question,
I know. But leaving for you to think ... just to ensure that you're still awake
:-)
Ans yes, in this approach if any method catches this InterruptedException thrown
from the stop() method, then that method should either have InterruptedExceptio
n in its throws list OR it should re-interrupt itself by throwing calling the in
terrupt() method again otherwise the purpose of rasing the InterruptedException
from the stop() method will go in vain.
What if Thread.interrupt doesn't affect a thread?
It's bizarre, but if the thread stops responding to Thread.interrupt() method th
en we need to some application specific tricks to overcome the situation. For ex
ample, if the thread is waiting on a Socket and stops responding to interrupt()
method, then we may close the Socket which will cause the thread to return immed
iately.
Be sure that if a thread doesn't respond to interrupt() method, it will not resp
ond to the stop() method either. So, don't be tempted to use stop() in such situ
ations.
Why are Thread.suspend and Thread.resume deprecated?
suspend() and resume() methods are deprecated as it may cause a deadlock to happ
en. The reason for this is that the suspend() method doesn't release the acquire
d monitors and if a suspended thread has already acquired the monitor of a criti
cal resource then an attempt to acquire the same resource in the thread which wo
uld resume the suspended target thread will cause a deadlock.
What should be done instead if using suspend() and resume()?
The same approach what we follow to have a graceful stop can be followed in this
case as well. We'll simply have a variable which will signify the various state
s of the thread and the target thread will keep polling the value of the variabl
e and if the value indicates a suspend state then the thread will wait by callin
g the Object.wait method and if a value indicating the resumed state will cause
the target thread to be notified using Object.notify method.
What does the method Thread.destroy do?
public void destroy() - this method was originally designed to destroy a thread
without any clean-up i.e., without releasing any of the acquired monitors, which
may cause deadlocks. This method was never implemented and a call to this metho
d throws NoSuchMethodError always.
=================================================================
Asserions in Java? Assertions vs Exception? Where to Use & Where NOT?
Assertion in Java
An assertion is a special statement which contains one boolean expression and if
that boolean expression returns 'false' then the program throws an AssertionErr
or which is an unchecked exception and it normally terminates the current progra
m/application.
This boolean expression is normally used to verify our assumptions which we used
while designing our application. Thus, assertions can be used to write correct
programs i.e., the programs which run in accordance with their specifications. A
ssertions can be easily enabled or disabled (by defauly they are disabled) and t
his greatly helps improving the maintainability of the application.
An assertion statement can have two forms in Java:-
* assert BooleanExpression; - AssertionError is thrown if BooleanExpression
is false.
* assert BooleanExpression : ExpressionReturningSomeValue; - in this case th
e returned value of ExpressionReturningSomeValue is paased to the constructor of
the AssertionError class, which is inturn used to provide a String representati
on of this value as the detailed error message which caused this AssertionError.
Remember that the second expression should should always return some value, so
we can't use a method call whose return type is void. For all other return types
(separate ones for all primitive types and Object type for all reference types
and Arrays) the AssertionError class has separate overloaded constructors which
are called based on the type of the passed parameter.

Where assertions should NOT be used?


Assertions should never be a part of the implementation of some functionality of
the application. They should only be used to verify the assumptions - just to b
e sure that whatever we assumed while desinging the solution is actually valid i
n practical as well. Below are few situations where you may get tempted to use a
ssertions, but you should NOT use them:-
* Do NOT use assertions to implement any application functionality - enablin
g/disbaling them may cause servere damage to the state of the application and it
s usability.
* Do NOT use assertions for argument checking of public methods - public met
hods represent the public interface of the underlying class to the outside world
and the methods should always behave the same. If we use assertions for argumen
t checking then enabling or disabling assertions may change the behavior of the
method dramatically, which is of course highly undesirable. In addition, using a
ssertions in such cases won't give us actual cause of the error as it can only t
hrow AssertionError (with a message) and it's obviously not as good as getting t
he actual cause like IndexOutOfBoundsException, NullPointerException, IllegalArg
umentException, etc., which we will otherwise get if we check the arguments with
out using assertions.

Where to use Assertions?


As we know that assertions should be used to test the assumptions so that we can
guarantee a correct program. Hence, they should be used at the places where the
execution assumes something and proceeds accordingly. Few of such scenarios are
:-
* Implementing Pre-conditions - assertions can be used to effectively implem
ent pre-conditions. A pre-condition means something which must be true at the ti
me of invokation of a method (otherwise the method may go erratic). An example o
f such a pre-condition can be checking whether the current thread holds (or does
n't hold) a lock on an object before the thread actually executes a method.
* Implementing Post-Conditions - similar to Pre-Conditions, these are the as
sumptions which are expected to be true once the control returns from a method.
Assertions can be used effectively to check if it's actually as per the assumpti
on or not. If not then it's better to stop the execution and terminate the appli
cation as proceeding further in such a scenario may lead the application to an i
nconsistent state.
* Implementing Class Invariants - assetions can be used effectively to check
if the assumed relationship between various members of a class is intact or not
. This especially helps when an instance is in transition from one consistent st
ate to another and using an assertion to confirm before proceeding further will
reduce the possibility of having the application in an inconsistent state.

Assertion vs Exception
We just discussed that assertions should be used to verify the assumptions so th
at we can guarantee that the application always executes complying with the spec
ifications. Thus we see that assertion is basically a mechanism which helps us w
riting correct programs. Whereas Exception is a mechanism of checking if the imp
lementation is executing without any expected or unexpected errors or not. So, w
e see that exceptions are basically used for handling even the unforseen conditi
ons during the execution of an application in a better way and hence using excep
tions effectively results into a robust application.
Just visualize the difference between something being correct and something bein
g robust. 'correct' obviously means that whenever the application runs, it runs
correctly in accordance with specs whereas 'robust' means whenever the applicati
on encounters an error condition either expected in case of checked expection OR
unexpected in case of unchecked exceptions, it always handles the execution in
a controlled way - either by ignroing the exception or by handling the exception
(maybe by saving the state and terminating gracefully).
Therefore, we see that assertions and exceptions are not rivals. In fact they ar
e complimentary to each other and an effective combination of both can ensure th
e development of a correct and robust application.
=================================================================
Why stop, suspend, & resume of Thread are Deprecated
This is a slightly longer article and hence divided into two parts. This is the
first part of the article, which will try to answer the following questions:-
* Why Thread.stop() method is deprecated in Java?
* Why ThreadDeath is a subclass of Error and not of Exception?
* Can't we catch the ThreadDeath and fix the damaged objects?
* What will happen if stop() method is called on a thread which is yet to st
art?
Why Thread.stop() has been deprecated?
Thread.stop() - public final void stop() - This method is deprecated for the sim
ple reason that it's unsafe and may lead the program to some unexpected circumst
ances. Thread.stop() when called, it causes the thread to release all the acquir
ed monitors and throw a ThreadDeath error, which ultimately causes the thread to
die. Since, the thread releases all the acquired monitors immediately, so it ma
y leave few objects (whose monitors were acquired by the thread) in an inconsist
ent state. Such objects are called damaged objects and obviously they may result
into some arbitrary behavior.
In case a Security Manager is installed, the this method causes the checkAccess
method to be called first which may result into a SecurityException and this exc
eption will of course be raised in the calling thread. If the stop() method is b
eing used to stop a different thread (than the calling thread) then the Security
Manager's checkPermission method will also be called in addition to the checkAc
cess method. Both of these methods may result into a SecurityException to be thr
own in the calling thread.
Can't the ThreadDeath object be caught and all the damaged objects be fixed?
Thoretically yes, but practically NOT possible as a thread may throw this Thread
Death error almost anywhere and what if a ThreadDeath is thrown while executing
the catch or finally block of the first ThreadDeath which we just caught... and
so on. Don't you think that it may soon become practically infeasible to guarant
ee a fixed version of all the damaged objects? This is why the designers of Java
preferred to deprecate the method than to ask the developers to do such a compl
ex and almost infeasible work to ensure damage-control in all the cases while us
ing stop method.
Why did they have it in the first place and why didn't they remove it altogether
?
Maybe because we may face scenarios (of course not frequently, but only very rar
ely) where the side effect of stop() method (or any other deprecated method for
that matter) may become insignificant than the actual affect which the method ca
n do. So, designers can't simply remove the method to maintain the completeness
of the language - they either need to design an equivalent method free from all
the side-effects OR to allow the developers to use if they badly need it. Markin
g such methods as deprecated simply serves the purpose of discouraging the devel
opers for using those methods and noe they will use them only if they are left w
ith no other possible workaround.
Why Thread.stop(Throwable) has been deprecated?
Thread.stop(Throwable) - public final void stop(Throwable obj) - this variant of
the stop method causes the thread to complete abnormally and to throw the passe
d parameter of type Throwable as an exception. This abnormal completion of the t
hread makes this method unsafe and potentially dangerous for the same reasons as
discussed in the other variant of the stop() method and hence it's deprecated.
In addition this variant may require a checked exception to be thrown which the
target thread may not be prepared to handle and throw. This may lead to a very a
wkward situation and a defined behavior is probably not guaranteed in such a cas
e.
A null value passed as the parameter will expectedly result into a NullPointerEx
ception in the calling thread. In case a Security Manager is installed, this var
iant may also throw SecurityException the same way as the other variant may.
What will happen if we call stop() method on a thread which is not yet started?
Interesting question, isn't it? Well... We're allowed to call stop() method (bot
h the variants) on a thread which is yet to be started. In such a case, if the t
hread starts then the stop() method causes it to die immediately.
Why are they allowed then? Okay... how can we handle it otherwise? At compile ti
me we can't check if the thread is started or not and at run time the stop() (wi
th zero arguments) method call requires a ThreadDeath object to be thrown, so ho
w will this requirement be met if we don't wait for the thread to eventually sta
rt and then be terminated by throwing ThreadDeath? Maybe we can create, start an
d terminate a dummy thread immediately when such a call is encountered. But, wha
t will we gain by doing this? In fact that will be the same as the worst possibl
e scenario where all such threads (un-started threads) actually get
started and terminated. In all possibilities, we may even have few such threads
which don't start for the entire life cycle of the application. So why to waste
time doing something in advance which will ultimately be done if required. Simil
ar explanation can be given for the other variant of the stop() method because t
hat also requires the target thread to complete abnormally - in addition that re
quires the passed Throwable type object to be thrown. Even worse situation to ha
ndle in advance, what do you say?
What's ThreadDeath? Why is ThreadDeath a subclass of Error and not of Exception?
public class ThreadDeath extends Error - an object of this class is thrown when
the Thread.stop() method is called without any argument. If a method catches thi
s thrown object then it should rethrow the error so that the thread actually die
s. This is the reason why the ThreadDeath class has been made a subclass of the
Error class and not of the Exception class. Many applications simply use Excepti
on type to capture all the exceptions and handle them either by simply ignoring
OR maybe by doing something in the handler. The ThareadDeath when thrown should
not be handled that way. It's thrown only when Thread.stop() method is called an
d that simply expects the thread to die and not to be handled some other way.
The second part of the article answers the subsequent questions to complete the
article. These questions are:-
* What should we do instead of using stop() method?
* How can we stop a long waiting (maybe due to I/O) thread?
* What if a thread doesn't respond to Thread.interrupt() call?
* Why are Thread.suspend & Thread.resume deprecated?
* What should be done instead of using suspend & resume?
* What's Thread.destroy()?
=================================================================
Error/Exception Handling in JSP - using JSPs or Servlets

An unrecoverable error while executing a JSP page can be handled by specifying t


he error JSP pages. These error JSP pages can either be specified in the Deploym
ent Descriptor (web.xml) OR a JSP can have its own error page specified with the
errorPage attribute of the page directive. The specifed error pages must have i
sErrorPage attribute of the page directive set to 'true'. This causes the Web Co
ntainer to declare a new implicit variable 'exception' which can be used in thes
e error pages (using either scriptlets or custom tages) to display the cause of
the error/exception on that error page.

If an error page is specified for a type of exception in the Deployment Descript


or and the page throwing that exception has also got an error page specified the
n the specified error page takes precedence.

Example: entries in Deployement Descriptor for error handling in JSP

<!-- Reporting an error using a JSP page -->


<error-page>
<exception-type>Fully Qualifies Exception Class</exception-type>
<location>/HandlerJSP.jsp</location>
</error-page>
...

The error JSP page uses isErrorPage attribute so that it can use 'exception' imp
licit object inside the scriptlets or in custom tags to know about the captured
error/exception.

<%@page isErrorPage="true" %>


<HTML>
<HEAD>
<TITLE>Some Error</TITLE>
...

say if the error JSP page wants to know the name of the captured exception class
, it can use the following scriptlet for that:-

<%= exception.getClass().getName() %>

Servlets and custom tags may access the captured exception object by calling the
method PageContext.getError().

How are the Exceptions Reported?

When an exception is received by the underlying Web Container then it first chec
ks if the JSP page raising that exception has any error page mentioned or not (o
f course if the exception is raised inside a try-catch block in a JSP the corres
ponding catch blocks would be examined first). If an error page is specified for
the JSP, the 'exception' implicit object is passed to that error page. We'll se
e later in this article how this object is passed.

If the JSP page doesn't specify any error page and if none of the available catc
h blocks are able to handle the raised exception (if the exception is raised in
try block) then the Web Container starts looking for an error page for that exce
ption in the Deployment Descriptor. If no error page is found for that exception
then the Container looks an error page for the exception's superclass and this
continue until the Container finds an appropriate error page or until it reaches
Throwable class (the topmost superclass of the entire exception handling mechan
ism in Java).

Can we use Servlets as error handles as well?

Yeah... the syntax is same as what we have for the JSP error pages. One sample e
ntry in the Deployment Descriptor may look like:-

<!-- redirecting an error to a servlet -->


<error-page>
<error-code>404</error-code>
<location>/errorServlet</location>
</error-page>
...

Both the elements <error-code> and <exception-type> can be used with any Web res
ource (JSP/Servlet) in the application. The element <error-code> specifies the H
TML error codes. Thus we see that the errros can be identified either by the Jav
a exception type or by the HTML error codes.

Question: why do we have the implcit object 'exception' of type Throwable and no
t of the type Exception? (Question raised by one of our regular visitors Lavnish
in response to the article - Implicit Objects in JSP >>. Thanks Lavnish for you
r contribution.)

Answer: Because the JSP page may throw exceptions of type Error as the root caus
e (though very rarely - may be due to JVM failure, error in a native method, etc
.) as well and if we have the type of the implicit object as Exception (instead
of Throwable), we would not have been able to capture such an error.

How the implicit object 'exception' is passed?

All the JSP exceptions passed to an error handler (JSP/Servlet) are actually pas
sed via request after being saved by the Web Container in an attribute of the re
quest named "javax.servlet.jsp.jspException". The saved exceptions are of the ty
pe javax.servlet.jsp.JspException. The constructors of the class JspException ar
e:-
* public JspException(java.lang.String msg) - normally for writing a custom
message to the server log or maybe for displaying that to the user.
* public JspException(java.lang.String message, java.lang.Throwable rootCaus
e) - if the 'exception' implicit object is not-null then that is passed as the r
ootCause parameter.
* public JspException(java.lang.Throwable rootCause) - a not-null 'exception
' implicit object is passed as the parameter.
It's quite evident that the JspException constructor is capable of accepting Thr
owable type parameter as the rootCause and hence keeping the type of the 'except
ion' implicit object as 'Exception' will not allow the exceptions of type 'Error
' to be specified as the root cause.

Okay... why don't the exceptions are thrown directly? Why do we need to wrap the
m in a JspException object?

Well... I can think of few probable reasons. One, it gives us a flexibility of c


reating (and hence throwing) an exception without the occurrence of any error/ex
ception condition. We can use the first constructor of JspException class which
requires just a String message and we can use this approach for writing some mes
sage to a log or may be to display that message to the user or something of that
sort.

Another possible reason to wrap the exceptions in a JspException is to facilitat


e additional text about the error condition. We may specify some custom message
for the exception before throwing that to make the user comprehend the error in
a better way. But, you may say that we can specify a detailed message to the con
structor of the particular exception class (as Throwable and all its sub types c
onventionally have a constructor accepting a String parameter). Yeah... we can c
ertainly specify the message that way also. But, the JspException constructor ma
y provide extra details relevant to the particular page as the same exception ma
y have different reasons on different JSPs OR may be in the different sections o
f a single JSP. The bottom line is that it just gives little extra flexibility :
-)
=================================================================
Difference between forward and sendRedirect
forward - public void forward(ServletRequest request ServletResponse response) -
it forwards a request from one servlet to another respource - dynamic/static (t
he resource can be another servlet, JSP, or a static HTML file). In such a case,
the calling servlet only does the preliminary work for the request processing a
nd doesn't usually write anything on the response object. Writing anything on th
e response object in the calling servlet will result into an IllegalStateExcepti
on for the forward() call if the output is flushed already otherwise the uncommi
tted response buffer is cleared before the forward() call. This action is perfor
med internally by the Servlet (or JSP which actually converts into a Servlet onl
y) and the client browser is not at all involved in it. Client browser is simply
unaware of it and the URL remain intact. Hence, any refresh/reload in the clien
t browser will simply repeat the same request. This is the reason why a forward
should not be used for serving a request involving some data modification as an
accidental refresh/reload of the browser may duplicate that change. forward() is
usually preferred in the cases where we simply read the data i.e., in the cases
where we use SELECT operation.
The same request and response objects are passed as parameters to the forward()
call hence the called resource can use all the objects defined in the request sc
ope of the previous request. Passed response object gets cleared (if the calling
servlet has written something before the forward() call) and hence it remains e
mpty for the new resource and the called resource builds the response object whi
ch it ultimately sends to the client.
We can specify the resource with a relative URL only for a forward action. forwa
rd() called on a RequestDispatcher obtained from an objet of the class implement
ing ServletRequest interface accepts an URL relative either to the underlying re
quest or to the underlying servlet context. Whereas forward() called on an Reque
stDispatcher obtained from a ServletContext implementation will require you to s
pecify an URL only relative to the underlying context. Read more about this - Re
questDispatcher of ServletRequest & ServletContext >>. We can NOT specify an abs
olute URL in forward() method.
sendRedirect - public void sendRedirect(java.lang.String location) - in this cas
e first the request is intercepted/processed by the server and then a new URL is
built and sent back to the client (this new URL is built using the URL what we
specify in the sendRedirect method). We can specify either a relative URL or an
absolute URL. If a relative URL if specified without a leading '/' then the Cont
ainer interprets it as being relative to the current request whereas a relative
URL with a leading '/' is interpreted as being relative to the underlying contex
t. The Container interprets the relative URL and converts it into an absolute UR
L before sending it back to the client. Now the newly constructed URL is again r
equested from the client. This URL change is quite visible in the client browser
.
Thus we see that sendRedirect is basically a two phase process and hence it's sl
ightly slower than forward() method. Since, the new URL is requested as an altog
ether new request hence the objects placed in the previous request scope can't b
e accessed in the new request.
Unlike the forward() method, an accidental (or intentional) refresh/reload of br
owser window will not repeat the original request. Only the new URL will be requ
ested in this case as the browser's address bar is already updated with the new
URL. Hence, the operation involving modification should prefer sendRedirect() ov
er forward() to avoid any accidental duplicacy.
Example: affect of accidental refresh/reload on forward() and sendRedirect()
Suppose the first request takes you to a page requesting you to transfer some fu
nds online and then the second resource just notifies whether the transfer was d
one successfully or not. In case of a forward() call, an accidental refresh/relo
ad of the browser window will execute the original request of transferring the f
und again (as the browser has still the original URL) and then the status page w
ill be shown. That means both the resources will again be executed and you may n
ed up transferring the fund twice :-) In case of sendRedirect(), the processing
of the original transfer request will redirect the status URL to the client brow
ser and hence an accidental (or maybe intentional) refresh/reload will only exec
ute the resource (maybe a JSP) showing you the status of the previous transfer a
nd that's what you would probably like to have. sendRedirect() avoids the execut
ion of the original request again because in this case the browser's address bar
is already updated with the new URL.
Difference between forward() and sendRedirect()
* forward() call is unknown to the client browser and nothing is visible in
the URL whereas sendRedierct() makes the new URL visible.
* forward() accepts only relative URLs (either relative to the request or re
lative to the context) whereas sendRedirect() can accepts relative URLs (which a
re converted into absolute URLs by the Container) as well as absolute URLs.
* forward() is slightly faster than sendRedirect() as it avoid an extra phas
e of sending the new URL back to the client browser and getting it requested fro
m there as a new request.
* forward() can use the objects in the request scope as the same request is
passed as the parameter to the forwarded resource whereas in case of sendRedirec
t() the call is treated as a new request and hence can't use the previous reques
t scope.
* forward() is preferred for SELECT operations requiring no modification to
avoid the duplicacy caused by an accidental refresh/reload of the clinet browser
window as a refresh causes the same original request to be processed again wher
eas sendRedirect() is preferred for INSERT/UPDATE kind of operations which actua
lly modify some state.
=================================================================
A thread problem - what will 'threadObject = null' do for an active thread?
package test;
public class Thread1 extends Thread{
public void run() {
int counter = 0;
while(true){counter++;
System.out.println("Inside Thread1 - " + counter);}
}
}
package test;
public class Class2 {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
thread1.start();
thread1 = null;
}
}
What will be the output when Class2 is run? 'thread1 = null' - what will this do
?
Outout:
Inside Thread1 - 1
Inside Thread1 - 2
Inside Thread1 - 3
....
..... till the stack overflow occurs or till you forcibly terminate :-)
Did you anticipate anything else? Except the statement 'thread1 = null', everyth
ing else is pretty straightforward - the main() method will start the execution
in the 'main' thread and during the execution, it'll create a new thread 'thread
1', which will start its execution in a separate thread of execution. The 'main'
thread being the parent thread will keep waiting for the child thread 'thread1'
to finish its execution and only then the 'main' thread will exit. The child th
read 'thread1' is running an infinite loop in its run() method, so it'll keep ex
ecutiing unless it's forcibly terminated either by user's intervention OR may be
due to stack overflow.
Okay... so if we include the statement 'thread1 = null' then why do you expect s
omething else to happen? Maybe because you think that assigning 'null' to an obj
ect will simply make that object eligible for garbage collection (as in this cas
e thread1 will have no other active references) and hence the thread should stop
execution. Well... threads don't get terminated that way.
In Java, the JVM continues executing a thread until either of the following thre
e occurs:-
* Runtime.exit() method (or its equivalent System.exit() method) is called a
nd the underlying Security Manager has permitted the method to execute. This inv
okes the JVM Shutdown Sequence (Read More in this article - JVM Shutdown Sequenc
e >>) which eventually halts the entire JVM process (the thread under execution
will just be a part of this process).
* Runtime.halt() method is called and the underlying Security Manager is oka
y with the call. This abruptly and immediately halts the entire JVM process.
* The thread under execution has returned from its run() method either by co
mpleting the execution of this method OR by thowing an uncaught exception which
propagates beyond the run() method. A parent thread can return only when all of
its child threads have already returned.

Now we can easily understand that 'thread1 = null' statement will not terminate
the thread and the main thread will keep executing and eventually keep waiting (
as thread1 is in infinite loop) for any of the above three cases to occur for th
e thread1 to terminate and after that the 'main' thread will also get terminated
. In our example, we're not explicitly calling Runtime.exit() or Runtime.halt(),
so they may be called only if we log off the machine or shut it down. Otherwise
, only third case will cause the thread to terminate. run() being in an infinite
loop will never complete its execution, so only an uncaught exception can termi
nate this thread. This uncaught exception can be either due to stack overflow OR
may be due to some user intervention. Thus, we can say that having 'thread1 = n
ull' will not at all affect the execution of any of the threads. The output will
remain the same with without having this statement as well.
=================================================================
Difference between Runtime.exit() and Runtime.halt() in Java
Runtime.exit() - public void exit(int status) - this method causes the shutdown
sequence of the underlying JVM to be invoked. This method indicates an abnormal
termination of the JVM and the parameter status may be used as a staus code for
the various abnormal circumstances which caused the termination of the JVM proce
ss.
The shutdown sequence of a JVM is consists of two phases - One, execution of all
registered shutdown hooks (read more about them in this article - Shutdown Hook
s in Java >>) and Two, execution of all uninvoked finalizers (if finalization-on
-exit is enabled) and then halting the JVM process.
If this method is called once the shutdown of the JVM has already started then t
his method will block indefinitely in case any registered shutdown hook is still
under execution. Otherwise, if all the registered shutdown hooks have already c
ompleted their execution and if the finalization-on-exit is enabled, then a non-
zero status code as the parameter will simply halt the JVM process whereas a zer
o status code will causes the method to be blocked indefinitely.
This method can be conveniently called by using the more popular System.exit() m
ethod as well. Since, System.exit(n) will be internally converted into RunTime.g
etRuntime().exit(n) only, hence it hardly matters which one of the two you choos
e. Choosing the former may seem to be little more convenient while the latter wi
ll skip the conversion step.
Runtime.halt() - public void halt(int status) - this method terminates the under
lying JVM process forcibly. That means the invokation of this method will not in
itiate the shutdown sequence and hence no shutdown hooks or finalizers will be e
xecuted. status as a parameter serves the same purpose as it does in the Runtime
.exit() method - it may be used to indicate the status code of the abnormal situ
ation that invoked this Runtime.halt() method.
Difference between Runtime.exit() and Runtime.halt()
You might have noticed so far that the difference between the two methods is tha
t Runtime.exit() invokes the shutdown sequence of the underlying JVM whereas Run
time.halt() forcibly terminates the JVM process. So, Runtime.exit() causes the r
egistered shutdown hooks to be executed and then also lets all the uninvoked fin
alizers to be executed before the JVM process shuts down whereas Runtime.halt()
simply terminates the JVM process immediately and abruptly.
=================================================================
Question: Can we have constructors in Servlets?
Answer: Yeah... we can have constructors in Servlets (the classes which implemen
t javax.servlet.Servlet interface), but we generally don't have them for the fol
lowing reasons:-
* Initialized by the Web Container - Servlets are not instantiated explicitl
y unlike regular Java classes as they additionally require a special ServletConf
ig object for their initialization, which can only be created by the Web Contain
er as it contains an instance of ServletContext as well, which is container envi
ronment based. There are two approaches, which a Servlet Container follows to in
itialize the servlets. Read more in this article - Preinitialization & Lazy Init
ialization of Servlets >>. Constructors are used to initialize an explicitly cre
ated object and probably to emphasize the implicit instantiation and initializat
ion, servlets use a different method 'init()' for their initialization.
* Interfaces don't contain constructors - Servlet (javax.servlet.Servlet) is
only an interface and not a class. Interfaces in Java don't have any constructo
rs as it doesn't make sense for them to have one. And a constructor of an implem
enting class can of course not be declared in the Servlet interface for the obvi
ous reason that we wouldn't be knowing the name of the implementing class(es). T
he classes implementing them may certainly have a constructor, but as specified
above, those constructors won't serve their usual purpose. The Servlet Container
will only use the init() method to initialize the servlet.

Thus we see that even though it's possible to have a constructor in a class impl
ementing the Servlet interface, it's advised not to have it for the simple reaso
n that the constructor will not serve its usual purpose. we may think of init()
as a renamed constructor for a servlet and everything which we would have like t
o put in the constructor can be put inside the init() method. In fact, servlets
provide additional ways of specifying initialization parameters - by specifying
them in the Deployment Descriptor (web.xml).
=================================================================
include() before forward() throws IllegalStateException - why?

Question: Calling include() before forward() throws IllegalStateException - why?


Answer: Because, the RequestDispatcher.include() method calls response.flushBuff
er() method and this flushBuffer() method sets the 'committed' flag for that res
ponse object. And hence the exception is thrown in such a scenario as we know th
at any forward() call on a 'committed' response results in an IllegalStateExcept
ion. Read more in this article - Why and when an IllegalStateException is thrown
?
Thus we can conclude that RequestDispatcher.forward() method should typically be
used only in the scenarios where the servlet calling this method is not suppose
d to do anything for building the response. All the response building task shoul
d be delegated to the servlet to which the request is forwarded. Any modificatio
n to the response object (header or body or both) will simply cause the RequestD
ispatcher.forward() method to throw an IllegalStateException for the simple reas
on that the forward() method is not capable to form a data pipeline among multip
le servlets. How can we have moduler Response-Writers in Servlets? How can we fo
rm the response object by using multiple servlets? Read the answers to these que
stions in this article - Implementing modular response-writers for Servlets>>
=================================================================
Question: Why and when do we get IllegalStateException in a Servlet?
Answer: public class IllegalStateException extends RuntimeException - this runti
me exception is thrown by a servlet to indicate that some requested operations h
ave been called in an inappropriate state of the application or the environment.
For example: If we try to write something on a response object which is already
committed to the client then we'll get an IllegalStateException.
There are two common variants of this exception:-
* Header Already Sent - java.lang.IllegalStateException: Header already sent
- this exception is thrown we have already committed one or more headers to the
client, so we can't set any headers anymore.
* OutputStream or Writer Already Obtained -java.lang.IllegalStateException:
Cannot forward as Output Stream or Writer has already been obtained - this excep
tion is thrown if the servlet calls the forward() method after it has already ob
tained the Writer or the OutputStream associated with the response object by cal
ling response.getWriter() or response.getOutputStream() methods respectively. Th
at means the response has already been (or may have been) written and hence the
response is not suitable for forwarding anymore.

How to avoid IllegalStateException in Servlets?


There may potentially be many reasons for this exception to occur, but we can fo
llow the following guidelines to avoid it in most of cases:-
* Don't use forward() once the Servlet has already used either response.getW
riter() or response.getOutputStream()
* Use a return statement immediately after using response.sendRedirect() met
hod or requestDispatcher.forward() method to avoid writing to a response object
which has already been committed to the client or in an inappropriate state.
=================================================================
What's Servlet Preinitialization & Lazy Initialization?

Preinitialization of Servlets
As the name suggests, Servlet Preinitialization means having a servlet initializ
ed beforehand i.e., having a servlet initialized before being requested to servi
ce an incoming request.
This is done by the Application Server where the Web Application (having the ser
vlets) is deployed. Most of the popular application servers use an element calle
d 'load-on-startup' in their Deployment Descriptor file named web.xml to specify
the servlets which are supposed to be pre-initialized at the time of the server
startup itself. Read more in this article - Using 'load-on-start' to Pre-initia
lize Servlets >>
Lazy Initialization or Lazy Loading of Servlets
This process causes a servlet to be initialized (or loaded by the Servlet Engine
) only after an incoming request call it for the first time. These servlets are
obviously those which are not mentioned in the web.xml file for pre-initializati
on. All the servlets which are responsible to service the routine type and frequ
est tasks are generally pre-initialized and those which serve only some rare spe
cific purpose are normally preferred to be initialized only when they are called
for the first time.
Advantages and Disadvantages of the two
Quite obvious to figure out. Pre-initialization will cause a servlet to perform
little faster even for the first incoming request as it's already loaded and rea
dy to serve the request. Other the other hand, lazy initialization will cause th
e first request to be served with a slight delay as the Servlet Engine will star
t the initialization of the servlet only after the first request has already bee
n received. The disadvantage of pre-initilization is that it makes the server st
artup process little longer as the server needs to initialize all the servlets m
entioned in the deployment descriptor during its startup. Another potential disa
dvantage of pre-initialization is that if a rarely used servlet is pre-initializ
ed then it may waste the precious memory for a long time until the first request
for this servlet comes.
=================================================================
ServletConfig interface vs ServletContext interface in Java

ServletConfig interface
public interaface ServletConfig (javax.servlet) - A ServletConfig object is used
by a Servlet Container to pass the initialization information to a servlet duri
ng its initialization. This object is built by the Servlet Container by using th
e information mentioned in the <init-param> element of the Deployment Descriptor
(web.xml) for that particular servlet. If no initialization parameres are provi
ded then a default ServletConfig object is built by the Container and passed to
the servlet. A typical entry in the web.xml for this may look like:-
<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>Fully Qualified Class Name</servlet-class>
<init-param>
<param-name>NameOfTheInitParameter1</param-name>
<param-value>ValueOfTheInitParameter1</param-value>
</init-param>
<init-param>
<param-name>NameOfTheInitParameter2</param-name>
<param-value>ValueOfTheInitParameter2</param-value>
</init-param>
...
</servlet>
ServletContext interface
public interface ServletContext (javax.servlet) - this interface declares a set
of methods used by a servlet to communicate with the Servlet Container. These me
thods are used by the servlets to get those tasks done which are controlled and
maintained by the Servlet Container - example: writing to a log file, calling re
quest dispatcher, fetching the MIME type of a file, etc.
Every JVM will have a separate ServletContext for a Web Application in case it i
s distributed (in this case the Web Application will be marked as "distributed"
in its deployment descriptor file) across multiple JVMs. ServletContext can be u
nderstood as a gateway for the servlets to access the environment in which they
execute.
<context-param> element can be used in the deployment descriptor file to specify
the parameters, which will be used by the Container to build the ServletContext
objects. These ServletContext objects will be unique per JVM per web applicatio
n. A typical entry in web.xml for this may look like:-
<context-param>
<param-name>NameOfTheContextParameter1</param-name>
<param-value>ValueOfTheContextParameter1</param-value>
</context-param>
...
Every ServletConfig object contains a ServletContext object as well. Both the ob
jects are created by the Servlet Container and the ServletConfig object is passe
d to every servlet while its initialization.
Difference between ServletConfig interface and ServletContext interface
Do I still need to mention the difference explicitly? ServletConfig may be uniqu
e for every servlet and it's used by the Servlet Container to initialize that pa
rticular servlet whereas ServletContext is same for all the servlets of one Web
Application running on a JVM and it's used by the servlets as a gateway to acces
s the environment in which they execute.
=================================================================
Why Java needs Inner Classes?

Why Java needs Inner Classes?


Though there are various other uses of Inner Classes as well, but there is one s
cenario where it seems that it's the only practical solution. This is the scenar
io where we need a construct like 'method pointers' in C/C++. We may need a bloc
k of code to be referenced without having a handle to the object or class that b
lock is a part of.
This can be implemented in Java by implementing the 'callback' approach using In
ner Classes. This is implemented typically by wrapping the code in an adapter cl
ass and this class is made to implement the required interface. These adapter cl
asses are implemented using inner classes and since these are classes having mul
tiple entry points - they provide better flexibility as compared to what a progr
ammer achieves by using function pointers in C/C++.
Another benefit of this approach is that it's simpler than the function pointer
approach and it keeps the runtime environment stable. The adapter classes implem
ented using inner classes normally improve performance as well as they can be op
timized to greater extent than their top-level adapter counterparts.
Other common uses of Inner Classes include:-
Providing alternate interface to an existing class - we simply add another metho
d with the return type as the new interface and return the object of that type b
y using anonymous inner classes.
class ExistingClass implements someInterface{
...
...
public AlternateInterface getAlternateType(){
return new AlternateInterface() {
//...implementation of the alternate interface
...
...
};
}
...
}
Implementing custom Enumerations - the implementation will look quite similar to
the above implementation. We use anonymous inner classes to implement and retur
n custom Enumerations.
Accessing local final variables - local inner classes and anonymous inner classe
s can be used to access local final variables of the block of code they are defi
ned into, which is typically a method.
Adding behavior to GUI - another distinguished usage scenario is the one where w
e anonymous inner classes for adding behavior to GUI components. These component
s already have their names and what all they need is the addition of a specific
behavior and anonymous inner classes fittingly do that. Following any other appr
oach for implementing this scenario makes the code clumsy and lengthy. Read more
about the uses of Nested Classes in Java, their potential disadvantages, etc. i
n this article - Why do we need Nested Classes in Java?
=================================================================
Why inner classes can access only local final variables?

Why inner classes can access only local final variables?


Local Inner Classes and Anonymous Inner Classes can access the local final varia
bles of the block of code they have been defined into. This block of code is typ
ically a method.
The reason why the access has been restricted only to the local final variables
is that if all the local variables would be made accessible then they would firs
t required to be copied to a separate section where inner classes can have acces
s to them and maintaining multiple copies of mutable local variables may lead to
inconsistent data. Whereas final variables are immutable and hence any number o
f copies to them will not have any impact on the consistency of data.
Note: All the inner classes will continue to have access to all the members of t
he enclosing class. No inner class instance can exist without the corresponding
enclosing class instance.
=================================================================
Yahoo MailDeliciousGoogle BookmarksStumbleUponFacebookMister-WongFurlTwitterTech
norati FavoritesCiteULikeWindows Live SpacesFunPInstapaperXerpiWinkBibSonomyBlog
MarksKhabbrYoolinkTechnotizieNewsVineFriendFeedSquidooBlinklistAIMHotmailAOL Mai
lSegnaloYouMobFarkTwiddlaMindBodyGreenunalogNowPublicPropellerTumblrCurrentYampl
eLinkatopiaYahoo MessengerGlobal GrindViadeoWistsConnoteaMyLinkVaultSphinnCare2
NewsHyvesFeVoteBitty Browser
DiggRedditWindows Live FavoritesAsk.com MyStuffMa.gnoliaMixxPownceShoutwireJumpt
agsHemidemiBzzsterPhoneFavsNetvouzDiigoTagglyTailrankYahoo My WebBookmarks.frMyS
paceMultiplyPingProtopage BookmarksFavesGmailYiGGPushaSlashdotImera BrazilLinkaG
oGoFeedmarker BookmarksHuggYahoo BookmarksThoofLiveJournalSpurlOneviewSimpyLinke
dInBuddyMarksMapleGraveeBackflipSiteJotDZoneDesign FloatDiglogSphere
Consider for a decision?
Powered by Add to Any
skip to main | skip to sidebar
Geek Explains
a comprehensive technical/hr interview guide
* Home
* Java/J2EE
* Tips/Hacks
* Oracle
* C/C++
* Puzzles
* HR
* Archives
* Offers
Saturday, May 31, 2008
Explain the JDBC Architecture - 2 tier and 3 tier both

Explain the JDBC Architecture - 2 tier and 3 tier both


JDBC APIs support both the architectures - 2-tier and 3-tier models for accessin
g a relational database.
JDBC for a 2-tier architecture
In such an architecture, the Java application (or Applet) communicates directly
with the data source (or database). The database may reside on the same machine
or may be on another machine to which the clinet machine needs to be connected t
hrough a network. In the latter case it will be a clinet-server configuration an
d the server will hold the database. The client will send the statements to the
database residing on the server and the result will be communicated back to the
client.
In this architecture, the client machine will typically be a Java application an
d the server machine will have a Relational Database installed on it.
JDBC for a 3-tier architecture
In such an architecture, the client machine will send the database access statem
ents to the middleware, which will then send the statements to the database resi
ding on the third tier of the archirecture, which is normally referred to as the
back end. The statements will be processed there and the result be returned bac
k to the client through the middle tier. This approach will have all the advanta
ges associated with the 3-tier architecture, such as better maintainability, eas
ier deployment, scalability, etc.
This scenario will typically have a Java Applet or a Web Browser as the clinet t
ier, an Application Server as the Middle-tier, and a Relational DBMS as the Back
-end.
Share/Save/Bookmark

Posted by Geek at 7:25 PM 0 comments


Labels: Java
What's a database transaction?

What's a database transaction?

A database allows multiple users to use it concurrently and hence while a user i
s making some changes to data in the DB, some other user might be accessing the
same data concurrently. This can lead to inconsistent data and hence such a situ
ation should be managed with proper care. Most of the DBMSs use the concept of t
ransactions to handle such a situation, which helps them to maintain data consis
tency as well as data concurrency.

A transaction is a basically a set of one or more SQL stataments, which will eit
her execute as an atomic unit or will simply rollback and will leave the databas
e as it was prior to the start of execution of the set of SQL statements of the
transaction. If all the statements of the transaction gets executed as a stomic
unit then the transaction ends with 'commit' statement which makes the changes t
o the database permanent,otherwise the changes are rolled back using the 'rollba
ck' statement and the database returns to the state it was before the start of t
he transaction.

The database management system must have the capability to allow access to only
one transaction to update a data item at a time otherwise the atomicity of the t
ransaction will be violated and consequently the data will become inconsistent.
The DBMSs use the concept of 'locks' to ensure this. A lock is a database object
used to ensure that only one transaction gets access to manipulate a data item
at a time. Every transaction requires to obtain the lock associated with the dat
a item it intends to change and only after acquiring that lock it can proceed wi
th the changes it needs to make on that data item.

For example: a table lock will not allow that table to be dropped unless an unco
mmitted transaction on that table gets committed/rolled-back. Similarly a row lo
ck will prevent that row to be modified (or even accessed in required) while ano
ther transaction is still modifying that row. The row will become accessible to
any other transaction when the transaction accessing it either gets committed or
rolled-back.

Share/Save/Bookmark

Posted by Geek at 7:23 PM 0 comments


Labels: Oracle
What is a Relational Database? What're Integrity Rules?
Relational Database
It's a database which stores and manages the information in tables, which are co
mposed of rows and columns. The name 'Relational' came from that fact that the t
ables in such a database are nothing but a collection of similar type of informa
tion stored in form of rows. This is the reason why a table is also referred to
as a relation in such a DB.
Integrity Rules
These are the rules which a relational database follows in order to stay accurat
e and accessible. These rules govern which operations can be performed on the da
ta and on the structure of the database. There are three integrity rules defined
for a relational databse,which are:-
* Distinct Rows in a Table - this rule says that all the rows of a table sho
uld be distinct to avoid in ambiguity while accessing the rows of that table. Mo
st of the modern database management systems can be configured to avoid duplicat
e rows.
* Entity Integrity (A Primary Key or part of it can not be null) - this rule
says that 'null' is special value in a relational database and it doesn't mean
blank or zero. It means the unavailability of data and hence a 'null' primary ke
y would not be a complete identifier. This integrity rule is also termed as enti
ty integirty.
* Referential Integrity - this rule says that if a foreign key is defined on
a table then a value matching that foreign key value must exist as th e primary
key of a row in some other table.

Share/Save/Bookmark

Posted by Geek at 7:18 PM 0 comments


Labels: Oracle
Role of JDBC in Java? What are JDBC components?

Role of JDBC in Java

JDBC is probably used to achieve the following three tasks in Java:-


* Connect to data source - it helps the Java program to establish a connecti
on to a data source, such as a database.
* Sending/Executing SQL statements - once the connection gets established th
en JDBC can be used to prepare, send, and execute SQL queries or Update statemen
ts on the data source, the connection is established to.
* Retrieving results and processing them - finally the JDBC APIs can be used
to retrieve the results of the fired SQL statements and helps them getting proc
essed to be used in the Java application.

Example:
//Connecting to the data source
Connection con = DriverManager.getConnection("url", "userid","password");
//preparing SQL statement
Statement stmt = con.createStatement();

//sending/executing SQL queries and retrieving the result


ResultSet rs = stmt.executeQuery("SELECT ...");

//processing the result


while (rs.next()) {
...
}

Components of JDBC
* JDBC API - The JDBC 4.0 APIs come in two packages: java.sql and javax.sql
and these packages contain all the APIs which provide programmatic access to a r
elational database (like Oracle, SQL Server, MySQL, etc.) from Java.
* JDBC Driver Manager - There are two ways of connecting to a database - One
, by using the DriverManager class (the traditional way of establishing connecti
on to a database from Java) and Two, by using a Data Source. This method require
s javax.naming and javax.sql packages to find a DataSource object registered wit
h JNDI, and to establish connection using that DataSource object. This is the re
commended approach of establishing connection to a database from Java.
* JDBC Test Suite - this test suite will of course not be exhaustive, but th
ey do contain almost all the standard test cases required to test the many JDBC
features. You may only need to add the application specific test cases.
* JDBC-ODBC Bridge - as the name suggests this enables JDBC access via ODBC
drivers. Though this is normally used only for development and testing purposes
and not for production use.

Share/Save/Bookmark

Posted by Geek at 7:09 PM 0 comments


Labels: Java
Why Prepared Statements are faster? Are they compiled?

Question: Why Prepared Statements are faster? Are they compiled?

Answers: Prepared Statements are faster not because they are compiled (in fact t
hey are not compiled), instead the reason for them being faster is that they are
bound to the underlying JDBC Driver. Whenever you create a prepared statement,
all the columns involved in that SQL statement get bound to the JDBc driver and
hence the binding overhead gets eliminated while execution which in turn makes t
he prepared statements faster. We use Connection.prepareStatement() to create a
prepared statement.
Share/Save/Bookmark

Posted by Geek at 7:05 PM 0 comments


Labels: Java, Trivia
Difference between Client-side & Server-side DB cursors?

Question: Difference between client side and server side DB cursors?


Answer: There is nothing like client side DB cursor. What you may think of a cli
net side DB cursor is actually the current row of either the ResultSet in case o
f JDBC or the Result in case of ODBC. DB cursor is only a server side entity and
it resides and runs only on the server.

Share/Save/Bookmark

Posted by Geek at 6:59 PM 0 comments


Labels: Oracle, Trivia
Friday, May 30, 2008
Oracle Database - How to tune for better performance?

Oracle Database - How to tune for better performance?


Why to tune?
Simply to improve performace of the overall system by enabling the best possible
resource utilization. The resource here includes all the resources involved inc
luding Software, Hardware, and Human Resources. Thankfully the Oracle Databse ca
n be tuned to a great extent and it's probably one of the biggest responsibiliti
es of a DBA to ensure whether the DB is well tuned or not.
When to tune?
Whenever the DBA discovers that the DB is not well tuned :-) There can be a veri
ety of
reasons why the DB may not look like to be well tuned. Few of them might be:-
* The system is not running at a pace matching with what your business requi
res
* The system is too slow to respond to the users and thereby wasting the pre
cious human time
* The hardware are probably not being utilized properly and hence hardware c
ost is rising

How to tune it?


There are so many areas where the DBA can concentrate on for tuning the Oracle D
B. Few of these areas are quire dependent on each other, so it's DBA's responsib
ility to ensure that focusing on one area doesn't produce some side effects to a
ny other tunes area. So, it's important to focus on these areas in a proper orde
r. For example, you can't jump on to SQL Tuning before having a fixed Database D
esign for the obvious reason that it's pretty difficult (if at all possible) to
have a refined SQL statement without having a refined database schema. Some of t
he areas to focus are:-
* Design of the Database - the design of the database if of utmost importanc
e and the DBA should be very sure that the current design is what he can think o
f as the best possible considering so many factors including normalization (or s
elective denormalization to improve performance), access paths, replication, etc
.
* SQL Tuning - probably the second most important area to focus on. There ar
e a variety of ways how the performance of a SQL query can be improved and the D
BA should not leave even a single stone unturned :-) Poor SQL statements can cau
se lot of performance problems during peak hours.
* Memory Tuning - it's important to allocate sufficient memory to the variou
s memory structures of the Oracle Instance. These memory structures are Shared P
ool, Buffer Cache, Redo Log Buffer, Large Pool, etc.
* Input/Output Tuning - Disk I/O is probably the most time consuming stuff i
nvolved in the entire operation of the DB, so the DBA must consider all the poss
ible scenarios involving Disk I/O and try reduce them to minimum possible.
* Connection Tuning - DB locks and latches must be reduced to the minimum an
d for the least time possible.
* OS Tuning - finally the DBA might focus on the underlying OS and see if it
's in the right shape to ensure the proper execution of the Oracle DB installed
on the system.

Share/Save/Bookmark

Posted by Geek at 10:00 PM 0 comments


Labels: Oracle
Thursday, May 29, 2008
All types of database files used in Oracle DB

All types of database files used in Oracle DB


The physical structure of the Oracle DB consists of three file types, which are:
-
* Datafiles - as the name suggests, these type of files store the data on di
sk.These files are almost always written only by the Mandatory Background proces
s named DBWR (Database Writer). There are only a few exceptions when these files
are written by some other system processes. From the logical structure of Oracl
e DB, we can visualize that Datafiles reside in the logical container of the tab
les and indexes. This container is called 'Tablespaces'.
* Control files - these are binary files and they store information about th
e database, such as name of the database. The control files contain so vital inf
ormation that the Oracle DB won't start if these files are not available. Probab
ly that's the reason why Oracle allows to maintain duplicate copies of control f
iles. This process is called multiplexing of control files and it'll always be a
good idea to keep duplicate copies on separate disks for obvious reasons.
* Redo Log files - these files are used to record all the changes made to th
e Oracle DB. These files comes very handy in situation like DB crash. Suppose yo
u have scheduled periodic backup every 15 days and if the disk crashes on say 14
th day then it may be quite difficult to recover the data in absence of these re
do log files. Redo log files will be of so much help in this case that you will
simply need to restart the database to recover all the lost data. These Redo Log
files are online log files and Oracle DB requires at least two online Redo Log
files. When one is full it switches to the other. You can have multiplexed Redo
Log files as well and for that'll be handy if these online Redo Log files themse
vles get corrupted.

In addition to these three types of files, Oracle DB uses many other types of fi
les as well and each of these files have their own special uses. Some of these f
ile types are:-
* Parameter file - this file is also called init.ora in Oracle DB. It contai
ns the configuration details which are used for during startup of the database.
Some of the information contained by this file is: the location of the Control f
iles, the size of RAM the Oracle DB would be using, location of the trace files,
etc. As you can easily understand that without these information, the database
won't start. Oracle DB supports two types of parameter files: One, Manual parame
ter file which is also known as PFILE and Two, server side parameter file aka SP
FILE.
* Trace files - Oracle DB creates these files in many cases including sessio
n failure, disk crash, etc. It can be created by issuing commands by users of Or
acle DB as well.
* Networking configuration files - tnsnames.ora and listener.ora fall in thi
s category of files. As the name suggests, these files are used to store the con
figuration details of the different network components used by the underlying Or
acle DB.
* Oracle Binary files - these binary files contain the instructions to run t
he Oracle DB.

Share/Save/Bookmark

Posted by Geek at 10:29 PM 0 comments


Labels: Oracle
Library Cache vs Data Dictionary Cache in Oracle

Library Cache
This part of the Shared Pool memory structure is used for storing the recently e
xecuted SQL and PL/SQL statements and hence these statements if encountered agai
n will be shared which will subsequently boost the performance of the database.
This memory structure is managed by a LRU (Least Recently Used) algorithm and th
is memory structure is also composed of two structures. One, Shared SQL area - f
or storing the most recently executed SQL statements and Two, Shared PL/SQL area
- for storing the most recently executed PL/SQL statements.
Data Dictionary Cache
This part of the Shared Pool memory structure is used for storing the most recen
tly used data definitions in the Oracle DB. These data definitions may include i
nformation about: database files, tables, indexes, privileges, users, etc.
Caching these inforamtion in memory improves the performance especially for quer
ies and updates using DML. During the parsing phase, the server process scans th
is memory structure to resolve the database object names and validate access.
Library Cache vs Data Dictionary Cache
Thus we see that Library Cache is used to store the recently executed SQL and PL
/SQL statements, which eliminates the need for parsing and compiling the stateme
nts again if used subsequently and hence improves performance. Whereas, the Data
Dictionary Cache is used to store the information which improves the validation
phase of the execution of those SQL and PL/SQL statements. So, both the memory
structures can be visualized as being complimentary to each other.

Share/Save/Bookmark

Posted by Geek at 10:27 PM 0 comments


Labels: Oracle
SGA Memory Structure of the Oracle DB - Explained

SGA Memory Structure of the Oracle DB

SGA (System Global Area) is the fundamental component of an Oracle Instance and
is one of two memory areas of an Oracle Server. This memory area contains severa
l memory structures each of which is designated to a specific task required by t
he Oracle DB during its execution. SGA is dynamic and the allocation is done in
granuels. The maximum size of the SGA is stored in the parameter named SGA_MAX_S
IZE. The primary memory structures contained by SGA are:-
* Shared Pool - this memory structure is used to store most recently execute
d SQL or PL/SQL statements and most recently used data definitions. For storing
these two different types of data, this memory structure is divided into two sub
-structures which are Library Cache and Data Dictionary Cache. Library Cache is
used to store the most recently executed SQL or PL/SQL statements whereas the Da
ta Dictionary Cache is used to store the most recently executed data definitions
. The maximum size of the Shared Pool is stored in the parameter named SHARED_PO
OL_SIZE.
* Database Buffer Cache - this memory structure is used to store the blocks
of data recently obtained from the datafiles and it improves the performace to a
great extent while fetching or updating the recent data. The size of this cache
is stored in the parameter named DB_BLOCK_SIZE.
* Redo Log Buffer - this memory structure is used to store all the changes m
ade to the database and it's primarily used for the data recovery purposes. The
size of this memory structure is stored in the parameter named 'LOG_BUFFER'.

In addition, there are other memory structures as well including those which are
used for lock and latch management, statistical data, etc.

SGA can support two other optional memory structures as well, but it needs to be
configured for that. These additional memory structures are:-
* Large Pool - This memory structure is used to reduce the burden of the Sha
red Pool memory structure. This memory structure can be used as the Session memo
ry for the Shared Server and as the temporary storage for the I/O involved in th
e server processes. This memory structure can also be used for the backup and re
store operations or RMAN. This memory structure doesn't use LRU (Least Recently
Used) list. The size of this memory structure is stored in the parameter named '
LARGE_POOL_SIZE'.
* Java Pool - As the name suggests, this optional memory structure is used J
ava is installed and used on the Oracle Server. Size of this memory structure is
stored in the parameter named 'JAVA_POOL_SIZE'.

Share/Save/Bookmark

Posted by Geek at 10:23 PM 0 comments


Labels: Oracle
Oracle Server Architecture - Main Components

Oracle Server Architecture - Primary Components


Well... most of the components themselves comprise of so many other logical comp
onents. Let's start with the major components first and the we'll dive deep into
the details of the sub-components of each of these components.
Oracle Server - what's it?
It's a DBMS that facilitates a comprehensive management of information. It provi
des an open and integrated approach towards information management.
Components of Oracle Server
It is made up of two main components:-
* Oracle Instance: this is not the actual database, but you can not access t
he actual DB directly and you need to use this component to access the DB. It ca
n have only one DB open and connected to it. This component is responsible for f
acilitating all the memory and process structures, which are used for the smooth
and expected execution of the Oracle DB. The memory structure consists of two m
emory areas: One, SGA (System Global Area) and Two, PGA (Program Global Area). S
GA is the fundamental component of an Oracle Instance and is allocated at the ti
me of Instance startup, whereas the other memory area, PGA is allocated when the
server process is started. PGA is basically the memory area reserved for every
user process which connects to the underlying Oracle DB. It is allocated at the
time of process creation and gets de-allocated when the process terminates. User
processes are the processes which are started at a time when an user tries to e
stablish connection with the Oracle Server. Server processes are the processes a
re used to connect to the Oracle Instance in response to a user process requesti
ng for the connection and it establishes the session as well. Background process
es are the processes which are used for doing periodic and routine activities. T
hey get started when the Oracle Instance is started and they keep running in the
background since then. The background processes include five mandatory processe
s and many other optional background processes. Mandatory Background Processes a
re: PMON (Process Monitor), SMON (System Monitor), CKPT (Checkpoint), LGWR (Log
Writer), and DBWR (Database Writer). Details of these mandatory background proce
sses and other optional processes will make this article too big, so I'll post t
hem separately.
* Oracle Database: as the name suggests, it's the actual DB which stores the
data. Putting it differently, Oracle DB is a collection of data and this data i
s treated as a unit. The physical structure of Oracle DB includes three types of
files which are Datafiles, Control Files, and Redo Log files. The logical struc
ture of an Oracle DB can be seen as a hierarchy, which includes Tablespaces, Seg
ments, Extents, and Blocks. Tablespace is right at the top of the hierarchy and
it consists of segments, which are themseves made of extents. These extents are
made up of sevaral blocks and these blocks are finally used for storing the info
rmation.

Share/Save/Bookmark

Posted by Geek at 10:13 PM 0 comments


Labels: Oracle
What's the Role of the Future interface in Java?

Future interface
public interface Future - this interface was added in Java 1.5 and it holds the
result of an asynchronous computation. This interface contains methos to check i
f the asynchronous computataion is complete or still in progress, to wait for th
e completion of the computation and to block the call until the completion of th
e computation, and apparently to retrieve the result of the computation.
You can use Future in that case also where you simply want to either check if a
task is complete or not or to simply cancel an ongoing task, but you don't want
to return any significant result. Use Future to declare the type and return 'nul
l' as the result in such a case.
Methods of the Future interface:-
* boolean cancel(boolean mayInterruptIfRunning) - this method cancels the ta
sk if it's still under progress and returns 'true' in case it successfully cance
ls it. 'false' is returned if the task has alraedy completed or if the attempt o
f this method to cancel the task fails due to some other reasons. If the task ha
s not started when the cancel method is called the the task should never run. Th
e parameter mayInterruptIfRunning is used to determine if the thread executing t
his task should be interrupted or not. If it's true then the thread is interrupt
ed otherwise the taks in progress are allowed to complete and the attempt to can
cel the task fails.
* boolean isCancelled() - it returns 'true' if the task got cancelled before
its completion
* boolean isDone() - it returns 'true' in case the task got completed either
due to normal completion or due to exception or due to cancellation of the task
using the cancel() method.
* V get() - if the task has completed, it returns the result, otherwise wait
s for thr task to get completed first and then returns the result. This method m
ay throw three exception:- One, CancellationException - in case the task was can
celled using cancel() method; Two, ExecutionException - if an exception occured
during the execution of the task; Three, InterruptedException - if the thread ex
ecuting the task was interrupted while it was in the waiting state.
* V get(long timeout, TimeUnit timeUnit) - As the parameters suggest this va
riant of get will wait for the specified time only and if the task gets complete
d before the expiry of the timeout then it returns the result if the computation
otherwise returns TimeoutException. It may throw the other three exceptions as
well similar to the other variant of get() method.
Share/Save/Bookmark

Posted by Geek at 10:05 PM 0 comments


Labels: Java, Multithreading
start() method vs run() method in Java

start method

public void start() - this method is responsible for causing the thread (it's ca
lled upon) to begin execution. The name may seem to be a misnomer here as this m
ethod only causes and not actually starts the execution. It just schedules the t
hread and when the CPU Scheduler picks this thread for excution then the JVM cal
ls the run() method to actually start the execution of the thread.

This method will obviously result into two concurrent threads - one, from which
this method is called and two, the new thread which executes the run() method of
the new Thread instance.

A thread will throw IllegalStateException in case you try to call the start() me
thod on an already started thread instance. That means, a thread can not be star
ted more than once. As per the Java specifications a thread may not be restarted
after completing its execution. You'll be required to create and start the exec
ution of a new thread in that case.

run method

public void run() - this is the only method of the Runnable interface and the cl
asses which intend to execute their code in a separate thread of execution first
implement the Runnable interface and subsequently define this method and put al
l the code expected to be executed in the separate thread inside the scope of th
is run method.

The other way, such classes can follow for the same is by extending the Thread c
lass and in that case also they should oevrride the run method of the Thread cla
ss and put all the code supposed to be executed in the new thread inside the sco
pe of the overriden run method.

Difference between start() and run() methods

start() methods only schedules the thread for execution and not actually begins
the execution of the thread. The execution of the thread is started when the JVM
calls the run() method of the thread once the CPU Scheduler picks this schedule
d thread for execution.

Share/Save/Bookmark
Posted by Geek at 10:00 PM 0 comments
Labels: Java, Multithreading
Threads and Daemon Threads in Java.

Threads
A thread represents an execution environment. It's quite similar to a process wi
th the difference that threads within the same process share much of the same st
ate including the address space and other open I/O resources of the process. The
Java Virtual Machine allows multithreading which means that more than one threa
d can continue to execute concurrently in the same process.
Threads are used to execute a task and based on the importance of the task we ca
n assign priority to the thread executing it. Obviously the threads having a hig
her priority will be given preference over those threads which are having a rela
tively lower priority.
Daemon Threads
There may be cases when you may like to have certain periodic and routine tasks
running as background threads. You can set any thread as daemon thread for that
purpose by using the setDaemon() method. This ensures that this thread will be k
illed and discarded only when all other threads of the application have already
exited. The Java Interpreter thread continues to run until all the non-daemon th
reads running in that JVM have exited. If it finds that the only active threads
are daemon thraeds, then the Java Interpreter thread exits. Example of creating
a daemon thread in Java:-
public class BackgroundThread extends Thread{
BackgroundThread(){
setDaemon(true); //setting the thread as a daemon thread
start(); //scheduling the thread for execution
}
public void run() {
//the code which is required to be run under this thread
}
}
When does a thread stop its execution?
On start up of a JVM, only a single non-daemon thread exists. This thread eventu
ally calls the main() method of a designated class. All the threads running in a
JVM keep on executing until one of the following two cases occur:-
* The security manager has approved the exit operation - this happens when t
he exit method of the class Runtime has been called and the underlying security
manager is okay with the call.
* The non-daemon thread has died in the JVM - this happens when the non-daem
on thread has either returned from its run method after completing the designate
d task or throws an exception which is not handled in the run method and hence p
ropagates beyond that method.

Share/Save/Bookmark

Posted by Geek at 9:50 PM 0 comments


Labels: Java, Multithreading
Callable interface vs Runnable interface in Java

Callable interface

public interface Callable, where V is the return type of the method call. This i
nterface has a single method 'call', which needs to be defined by all the classe
s which implement this interface. This method takes no arguments and returns a r
esult of type V. This method can throw checked exceptions as well.

Runnable interface

public interface Runnable - this interface is implemented by those classes whose


instances are supposed to be executed in a different thread. This interface has
only one method 'run', which takes no arguments and obviously all the classes i
mplementing this interface need to define this method.

This interface is implemented by the Thread class as well and it's a common prot
ocol for all the objects who wish to execute in a different thread. It's one of
the ways of creating threads in Java. The other way to create a thread is by sub
classing the Thread class. A class implementing Runnable interface can simply pa
ss itself to create a Thread instance and can run thereafter. This eliminates th
e need of subclassing the Thread class for the purpose of executing the code in
a separate thread.

As long as we don't wish to override other methods of the Thread class, it may b
e a better idea to implement the Runnable interface to enable multithreading cap
abilities to a class than enabling the same by extending the Thread class.

Callable vs Runnable

Though both the interfaces are implemented by the classes who wish to execute in
a different thread of execution, but there are few differences between the two
interface which are:-
* A Callable instance returns a result of type V, whereas a Runnable instanc
e doesn't
* A Callable instance may throw checked exceptions, whereas a Runnable insta
nce can't

The designers of Java felt a need of extending the capabilities of the Runnable
interface, but they didn't want to affect the uses of the Runnable interface and
probably that was the reason why they went for having a separate interface name
d Callable in Java 1.5 than changing the already existing Runnable interface whi
ch has been a part of Java since Java 1.0.

Share/Save/Bookmark

Posted by Geek at 9:41 PM 0 comments


Labels: Java, Multithreading
Wednesday, May 28, 2008
How do you modify the Manifest File of a JAR?

Question: How do you modify the Manifest File of a JAR?


Answer: Let's discuss first why would we need to modify a Manifest File? Well...
there can be various reason. One being the change of Entry Point of a stand-alo
ne application. The Main-Class header of the Manifest file contains the Class Na
me whose main() method wil be used to start the execution. If you want to specif
y any other Class as the Entry Point, you may need to modify the Manifest File.
Similarly, the Manifest File may be modified to add any other special purpose he
aders with appropriate values.
How to modify it?
We can only merge other info to the already existing manifest file of a JAR. 'ja
r' tool automatically creates one default manifest file and we can add any extra
info to the contents of the default manifest file. Subsequently, if we want to
add even more info then also we need to follow the same procedure and that extra
info will be added to the contents of the existing manifest file.
For adding any extra info we need to create a text file having the details in a
proper format. Once the text file is ready then we can use the 'jar' tool with '
m' option to add that info to the contents of the already existing manifest file
. Proper format means the data you have in the text file should form the content
s of a valid manifest file and every line of the text file must end with a new l
ine or a carriage return.
Caution: don't forget to add a new line after the last line of the text file as
well otherwise that line may not be parsed properly.
Command for adding some info right at the time of creating the JAR file can be l
ike this:-
jar cfm JArFileName.jar ManifestAdditionTextFile.txt InputFilesOfTheJAR
Here option 'c' means 'create a new JAR', option 'f' means 'the output should go
to a file and not to the standard output', and option 'm' means 'merge info to
the already existing (in this case default) manifest file'.
The order of options 'm' and 'f' must be in the same order as you provide the co
rresponding arguments to the command. 'c' option doesn't require any argument an
d normally comes as the first one.
Share/Save/Bookmark
Posted by Geek at 9:40 PM 5 comments
Labels: Java
What does 'e' option do with 'jar' command in Java?

Question: What does the option 'e' do with 'jar' command in Java?
Answer: This option is used to set an entry point to a stand-alone application b
undled as a JAR file. This option was introduced in Java 6.0 and it either creat
es or overrides the Main-Class attribute value set in the manifest file of the J
AR (which is also used for the same purpose). We can use this option either whil
e creating the JAR or while updating it and it saves the effort of either editin
g or creating the manifest file.
Example: Creating a JAR file and setting the entry point:-
Option 'c' is for create and 'f' indicates that the output of the command will g
o to a file instead of going to the standard output.
jar cfe JarFileName.jar PackageName.EntryPointClass PackageName/EntryPointClass.
class
Running the stand-alone application using the entry point:
java -jar JarFileName.jar
The execution will start with the main() method of the class named EntryPointCla
ss as we set the entry point of the stand-alone application as this class.
Similarly, we can set the entry point while updating a JAR file using the 'u' op
tion for update and then we can simply run the JAR file as we do in the above ca
se:-
jar ufe JarFileName.jar PackageName.EntryPointClass PackageName/EntryPointClass.
classJava -jar JarFileName.jar

Share/Save/Bookmark

Posted by Geek at 9:34 PM 0 comments


Labels: Java
Puzzle: 15 pirates, 100 Coins - how to distribute?

Puzzle: There are fifteen pirates all ranked by their years of service i.e., Pir
ate 15 is having 15 years of service, Pirate 14 is having 14 years of service, a
nd so on. They find 100 gold coins. To divide these coins they agree on the cond
ition which says "The most senior pirate will propose a way of distributing the
coins, and then all the pirates (including the one who proposed) will vote and i
f he gets at least 50% votes then everyone will accept that proposal otherwise h
e'll be forced to leave the place without any coin. The next senior most will fo
llow the same... and so on until a proposal gets approved."
Considering that all the pirates are able enough to see which proposal will ensu
re them the maximum gain. Their prefernces will be in the order to stay alive fi
rst, maximize the number of gold coins, and if at all there are equal outcomes i
n two situations then to have fewer number of pirates left with them.

After thinking for a while, the most senior pirate proposes a solution, which ma
ximizes his share of gold coins, and others also accept that as none could think
of any better alternative. What plan did the most senior pirate suggest?

Solution: The key here is to think about the pirates who the most senior pirate
needs to take care of while proposing a plan. Okay... what will be the least num
ber of pirates left to divide the gold coins among themselves? The least number
will 1 when all other pirates get their plans dumped and hence leave the place.
Now, if there is only 1 pirate left then he'll obviously get his own vote which
will ensure 100% vote for him and he'll take home all the 100 coins.

Similarly, if there are only 2 pirates left then pirate 2 will be the most senio
r among them and he'll 50% vote by his own vote only and hence will take home al
l 100 coins. So, in this case pirate 1 won't get any coins.

If there are 3 pirates then the pirate 3 being the most senior may offer only 1
gold coin to pirate 1 to ensure his vote and will safely take home the rest 99 c
oins. Pirate 1 knows that if he dumps the plan proposed by pirate 3 then pirate
3 will leave the place and pirate 2 being the senior most will take home all 100
coins. So, pirate 1 will have no ther choice but to accept the plan prposed by
pirate 3 in this case.

If there are 4 pirates then pirate 4 being the senior most pirate requires one m
ore vote to ensure 50%. He knows that in case there are only 3 pirates left then
pirate 2 gets 0 coins, so he'll offer 1 gold coin to pirate 2 and pirate 2 will
have no other option but to accept it. Pirate 4 will take home 99 coins.

If there are 5 pirates then pirate 5 being the senior most requires 2 votes exce
pt his own vote to ensure 50%+. So, he will offer 1 coin to pirate 3 and 1 coin
to pirate 1, which pirate 3 and pirate 1 will have to accept because in absence
of pirate 5, pirate 4 will become the senior most and in that case pirate 1 and
pirate 3 will get nothing. So, pirate 5 will take home 98 gold coins.

Similarly, if there are 15 pirates then pirate 15 being the most senior requires
7 other votes except his own vote to ensure 50%+ and hence he'll offer 1 coin e
ach to all the pirates who won't get anything in absence of pirate 15. These pir
ates will be pirate 13, pirate 11, pirate 9, pirate 7, pirate 5, pirate 3 and pi
rate 1. All these seven pirates will accept the plan proposed by pirate 15 becau
se they know that if he leaves and pirate 14 becomes the senior most then they'l
l go home with 0 coins :-)

Share/Save/Bookmark

Posted by Geek at 9:29 PM 0 comments


Labels: Puzzles
Significance of the Manifest File in a JAR?
Question: Significance of the Manifest File in a JAR?
Answer: The Manifest File in a JAR contains meta-information (information about
other information) about the other contents of it.
One common usage of Manifest File is to specify the entry point of a stand-alone
application bundled as a JAR. The Main-Class header is used to specify the clas
s whose main method will be called to start the execution if the JAR file is run
by the command "java -jar JarFileName.jar".
Other uses of Manifest File is to provide information about Dependencies of the
JAR file on other JAR files, Version of the JAR file, Security Information, etc.
This file exists in the META-INF directory of the JAR with the filename "MANIFES
T.mf".

Share/Save/Bookmark

Posted by Geek at 9:27 PM 0 comments


Labels: Java
How to invoke an Applet packaged as a JAR?

Question: How do you invoke an Applet packaged as a JAR?

Answer: By including archive attribute to the 'applet' element in the HTML code,
which invokes the Applet. This attribute will have the value as the JAR file na
me containing the Applet class. (...archive="nameOfTheJARFile.jar"...)

Share/Save/Bookmark

Posted by Geek at 9:19 PM 0 comments


Labels: Java, Trivia
Probability of seeing a car in 5 minutes - Puzzle

Puzzle: If the probability of observing a car on a highway in 20 minutes time is


609/625 then what is the probability of observing a car in 5 minutes time on th
e same highway (considering all the factors involved to be uniform)?
Solution: Probability of seeing a car in 20 minutes = 609/625
=> Probability of not seeing a car in 20 minutes = 1 - 609/625 = 16/625
=> (Probability of not seeing a car in 5 minutes)^4 = 16/625
=> Probability of not seeing a car in 5 minutes = (16/625)^(1/4)
=> Probability of not seeing a car in 5 minutes = 2/5
Hence, the Probability of seeing a car in 5 minutes = 1 - 2/5 = 3/5
Share/Save/Bookmark

Posted by Geek at 9:13 PM 0 comments


Labels: Puzzles
Archives from the Category Tips/Hacks - 1

Archived Articles from the Category - Tips/Hacks


* Free 2/3 - Col XML Templates. How to apply a new Skin in Blogger?
* Inserting Google AdSense Ad code in Body, Sidebar, etc. in Blogger?

Share/Save/Bookmark

Posted by Geek at 8:00 PM 0 comments


Labels: Archives
Tuesday, May 27, 2008
Externalizable in Java? What is it used for?

Externalizable in Java

It's an interface which subclasses the java.io.Serializable marker interface. Th


is interface contains two methods:
* void writeExternal(ObjectOutput out)
* void readExternal(ObjectInput in)

This interface is implemented by a class to handle the responsibility of saving


and restoring the contents of its instances to (or from) streams by itself, whic
h it does by implementing the above two methods. Only the identity of the class
which implements Externalizable interface is saved in the serialization stream.
The control is entirely delegated to the class to handle the saving and restorin
g all of its contents. It needs to take care of the saving/restoring the state o
f its super types as well.

Every object which requires to be stored is first tested whether it's Externaliz
able or not. If yes, then the writeExternal() method is called to do the task of
saving of contents otherwise the state of the object is saved using ObjectOutpu
tStream (using writeObject() of this class). If the class is not even Serializab
le (in case the class doesn't even implement java.io.Serialzable interface) then
we get NotSerialzableException. Similarly, an Externalizable instance is restor
ed by first using the public no-argument constructor and then by calling the rea
dExternal() method. If the class is not Externalizable, but it's Serializable th
en the restore is done by ObjectInputStream (readObject() method of this class).

writeExternal method
This method saves the contents of objects either by calling the methods of the D
ataOutput interface for primitive data types or by calling the writeObject() met
hod of the ObjectOutput interface for all kind of objects (including arrays). Th
is method throws IOException if it encounters any problem while writing the cont
ents to the output stream.

readExternal method

This method restores the contents of objects either by calling the methods of th
e DataInput interface for primitive data types or by calling the readObject() me
thod of the ObjectInput interface for all kind of objects (including arrays). Th
is method throws either IOException in case it encounters any I/O error while re
ading from the input stream OR ClassNotFoundException in case the class for the
object being restored is not found.

Read Next: You may like to go through the article - Serializability in Java >>,
if you have not already gone through. Proceed next to the article - Security ris
ks with Externalizable interface & its inapplicability >>
Share/Save/Bookmark

Posted by Geek at 9:46 PM 4 comments


Labels: Java
InvalidClassException and serialVersionUID in Java

InvalidClassException and serialVersionUID in Java

When you implement java.io.Serializable interface to make a class serializable,


the compiler looks for a static, final field named "serialVersionUID" of type lo
ng. If the class doesn't have this field declared explicitly then the compiler w
ill create one such field and assign it with a value which comes out of a implem
entation dependent computation of serialVersionUID. This computation depends upo
n various aspects of the class and it follows the Object Serialization Specifica
tions given by Sun. But, the value is not guaranteed to be the same across all c
ompiler implementations.

This value is used for checking the compatibility of the classes with respect to
serialization and this is done while de-serializing a saved object. The Seriali
zation Runtime verifies that the serialVersionUID of the sender class (which was
used for saving the state of the object on the stream) and that of the receiver
class (the class which is being used to restore the object, possibly at some ot
her system) both are exactly same. If the receiver system has loaded the class h
aving some other serialVersionUID than that of the class used while serializatio
n process then we get an InvalidClassException.

Caution: It's highly recommended that you explicitly declare and initialize the
static, final field of type long and named 'serialVersionUID' in all your classe
s you want to make Serializable instead of relying on the default computation of
the value for this field. This computation is extremely sensitive and may vary
from one compiler implementation to another and hence you may turn up getting th
e InvalidClassException even for the same class just because you used different
compiler implementations on the sender and the receiver ends of the serializatio
n process.

In most of the cases you would be using 'private' access specifier only for this
field as the declaration normally applies only to the class declaring it and we
don't really need to either inherit this field in the subclasses OR to access i
t from outside. So, there is hardly any reason why we shouldn't keep it 'private
'.

Share/Save/Bookmark

Posted by Geek at 9:34 PM 0 comments


Labels: Java
How do you avoid InvalidClassException for arrays?

Question: Arrays are objects in Java. How do you ensure that you don't get Inval
idClassException due to potentially different serialVersionUID across different
Java Compiler implementations?

Answer: Java specifications ensure that for us. Nothing specific required for ar
rays in this regard. Okay... the next question which may come to our mind is:- w
hy the requirement of matching the serialVersionUID is waived for Arrays in Java
? The underlying reason for this waiver is that even though Arrays are treated a
s objects in Java, we don't really have a Class which we can change for adding t
his new field explicitly, so we can not declare and initialize serialVersionUID
field the way we do for any other class we ensure uniform serialization for. Arr
ay classes will continue to have only the default computed value for serialVersi
onUID. And hence the waiver is probably the only solution to avoid a potential I
nvalidClassException across different Java Compiler implementations.

Share/Save/Bookmark

Posted by Geek at 9:23 PM 0 comments


Labels: Java
What is Serializability in Java? How does it work?

Serializability in Java

It's a mechanism in Java to ensure that the objects of classes implementing java
.io.Serializable interface will have the capability of storing their states on a
persistent storage that can be loaded back into the memory with the same state
whenever needed.
The Serializable interface is only a marker interface and has no methods or fiel
ds in it. It just serves the purpose of notifying the JVM about the Class implem
enting it that the Class may require to save its state on a persistent medium an
d subsequently may need to restore the same saved state in the memory when neede
d. The compiler handles it either by identifying serialVersionUID field in the c
lass or by adding one to the class (the next post talks in detail about serialVe
rsionUID) and presence of this field notifies the Runtime Environment to treat t
he instance creation appropriately.

The subclasses of a Serializable class are automatically Serializable, and if yo


u want to Serialize sub classes of non-serialized classes then you need to ensur
e that the super class has a no-argument constructor. Reason being, on marking t
he sub class as a Serialized class, it tries to save and restore the state of pu
blic, protected, and package (of course only if accessible) fields of the super
class also. The sub class can do this only if the super class has a no-argument
constructor. Otherwise, you'll get a runtime exception.

While De-Serialization also the state of the public, protected, and package (onl
y if accessible) fields of the non-serialized super classes are restored using t
he no-argument constructor of the super class. The state of the fields of the se
rialized sub-class is restored from the stream.

Custom handling of objects while Serialization/Deserialization

In addition to the default serialization or deserialization of objects, Java als


o supports special handling of the serialization (or deserialization) of objects
. You just need to implement the following three special methods in that case an
d do whatever way you want the save/restore of the objects to go. These special
methods are:-
* private void writeObject(java.io.ObjectOutputStream out) throws IOExceptio
nprivate
* private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundExceptionprivate
* private void readObjectNoData() throws ObjectStreamException

writeObject method

As the name suggests, this method is used for writing the state of the object to
the output stream passed as its parameter. Usually the defaultWriteObject() met
hod (or methods from the DataOutput interface for primitive types) of the Object
OutputStream class is used to write non-static and non-transient fields of the c
urrent class to the output stream. The defaultWriteObject() method can be called
from within a writeObject method only, otherwise it throws NotActiveException.
Some I/O error while writing the date to the stream will cause the IOException t
o be thrown by this method.

readObject method

This method reads the data saved by the writeObject method and restores the stat
e of the object. This method normally calls readDefaultObject() method (or metho
ds from DataInput interface for primitive types) of the ObjectInputStream class
to restore the non-static and non-transient fields of the object.

An interesting scenario: Suppose you have a class having 4 non-static and non-tr
ansient fields namely fld1, fld2, fld3, and fld4. Now you create an instance and
save the state of the object on a persistent medium using writeObject method. D
own the line the class evolves and you need to add two new non-static, non-trans
ient fields namely fld5, fld6. What will happen, if you try to restore the previ
ously saved state of the object with an object reference of the new version of t
he Class?

Well... nothing serious. Actually the readDefaultObject() method reads the data
and the field name from the stream and assigns the corresponding named field of
the current object. So, in our case fld1, fld2, fld3, and fld4 will get restored
from the stream and the other two fields fld5 and fld6 will continue having def
ault values.

readObjectNoData method

Suppose you have a class named Class1 and you have saved the state of an object
of this class on a persistent medium. You send that saved state to some other ap
plication, which has a different version of the same class 'Class1'. Say the rec
ipient application is having a version where Class1 extends another class named
'Class2'. Now, if you try to restore the saved state shipped to the recipient ap
plication, you need to use readObjectNoData method and not the readObject method
. Reason being, the recipient application will try to look for the state of the
superclass of Class1, which is Class2 and obviously it won't find that in the sa
ved state. This may happen in that case also where the saved state of the object
gets tempered. readObjectNoData method simply initializes the state of the supe
rclass in any of the above two scenarios.

Read Next - What is Externalizable interface in Java? Once done with this artcil
e you may like to compare the two interfaces and see the differences between the
two. This may help you understanding when to use which one of the two interface
s? What are the potential problems and security risks with using these interface
s? ... The artcile - Serializability vs Externalizability in Java covers these t
opics.

Share/Save/Bookmark

Posted by Geek at 8:57 PM 0 comments


Labels: Java
Monday, May 26, 2008
Train, Tunnel, and Man. How faster is the train running?

Puzzle: A man has entered into a tunnel and has crossed only 1/4 of it while it
hears a whistle from a train behind him. He turns and runs towards the train wit
h the same speed and he could barely get out of tunnel before the train (running
with a constant speed) could hit him at the entrance of the tunnel. Had he move
d in the same direction with the same speed then also he could have crossed the
tunnel before the train could have hit him at the exit of the tunnel. Assume tha
t the speed of the man is uniform, he takes zero time to turn back, and instantl
y gets his speed while turning back. How faster is the train moving as compared
to the man?

Solution: Let the speed of the train be X and that of the man be Y. Let the leng
th of the tunnel be T and the distance of the train from the entrance of the tun
nel at the time the man turned back is E.

Now, we can easily form two euqations with the given data. One, The man covered
T/4 distance and the train covered E distance in the same time, hence

E/X = (T/4)/Y
=> X/Y = E/(T/4)
=> X/Y = 4E/T ..... (i)

Two, The man could have covered 3T/4 distance and the train could have covered E
+ T in the same time, hence

(E+T)/X = (3T/4)/Y
=> X/Y = (E+T)/(3T/4)
=> X/Y = 4(E+T)/3T ..... (ii)

Comparing (i) & (ii), we get

4E/T = 4(E+T)/3T
=> E = (E+T)/3
=> 3E = E + T
=> T = 2E

putting this value in equation (i), we get

X/Y = 4E/2E
=> X/Y = 2

That means the train is running twice as fast as the man.

Share/Save/Bookmark
Posted by Geek at 8:28 PM 0 comments
Labels: Puzzles
Extension Mechanism in Java. What, How, etc.

Extensions in Java

Extension are nothing but a set of packages or classes or related resources all
bundled into a Java Archive (JAR) file and stored at (or referenced from) a spec
ified location. You can have two types of extensions in Java based on whether yo
u store the JAR at a specified location OR reference the JAR from a specified lo
cation. These are:
* Installed Extension: If you store the JAR file in a particular directory (
inside the current Java Runtime Environment), which is especially meant to store
Java extensions then such extensions are named installed extensions.
* Download Extenssion: If you specify the JAR file from the manifest file of
another JAR file (accessible to the application) then in this case the extensio
ns are named download extensions.

Installed Extensions

The special directory used to keep the installed extensions is jdk<version>/jre/


lib/ext. These installed extensions become part of the Core API of the underlyin
g Java platform, so they will be visible and hence available in all the processe
s running in the current Java Runtime Environment, so do take care of the direct
ory structure of the classes in the JAR file before bundling them. It should be
similar to what we have for the other standard APIs in Java.

Java 6 goes one step further and allows you to store the installed extensions at
an independent location and all the JREs installed on a particular system can s
hare the same extensions. Prior to Java 6, the extensions were looked only in ..
/jre/lib/ext directory, but from Java 6 they will be looked in a series of direc
tories staring with this directory. So, the first directory of that series will
always be .../jre/lib/ext and maybe you can have the independent location as the
second entry. Currently this independent location is independent only to the JR
Es installed on a system, but fixed for a particular Operating System. Like, thi
s directory should be SystemRoot\Sun\Java\lib\ext for MS Windows OS, /usr/jdk/pa
ckages/lib/ext for Solaris OS, and /usr/java/packages/lib/ext for Linux OS.

Download Extensions

In this case the extension JAR files are referenced from the manifest file of an
y other JAR of the current JRE. The JAR file referring to the download extension
need to be itself an extension. It can be a normal JAR file somehow reachable t
o the application (i.e., the directory having this JAR file should be there some
where in the CLASSPATH). There are two ways of referring to an external JAR file
in a manifest file: One, by using a Class-Path header and Two, by using an Exte
nsion-List header. A maximum of one of each of the headers is allowed in a manif
est file. But, one header can refer any number of extension JARs.
The difference between the two ways is that the download extensions referred by
a Class-Path header are downloaded only for the lifetime of the application whic
h downloads them. For example, a Web Browser running an Applet may require certa
in functionalities to be shipped via download extensions for the smooth executio
n of the Applet in the browser window. The advantage of using this approach is t
hat you don't need to install anything on the clinet machine. The clinet machine
should be capable of running a Web Browser. That's it. The disadvantage is also
quite clear - you download it every time you need. Download extentions referred
by an Extension-List header cause the extensions to be downloaded the first tim
e they are needed and they are directly installed in the .../jre/lib/ext directo
ry of the underlying JRE that time only. So, they become similar to an installed
extension afterwards. This is the advantage that you need to download them only
once, but the disadvantage is that the deployment of Extension-List header base
d download extentions is complex as compared to Class-Path header based download
extensions.

Share/Save/Bookmark

Posted by Geek at 7:51 PM 0 comments


Labels: Java, JVM
Sunday, May 25, 2008
Properties and System Properties in Java

One of our visitors, Ran Vijay posted the following two questions:-
* What are System Properties in Java?
* What is the difference between loading a JDBC Driver using System Properti
es and loading it using Class.forName()?

Let's first discuss Properties in Java and then we'll move on to System Properti
es and finally to the second question, which is regarding loading of JDBC Driver
s.
Properties in Java
In Java, Properties are actually configuration values which are managed as the t
raditional key-value pairs. Both the Key and the Value in every pair will be Str
ing values only. As the name suggests, the Key will be used to retrieve the corr
esponding Value and hence it must be unique in a properties file. These files ar
e plain text files and by convention we give them ".properties" extension. To ma
nage properties in Java, we need to create instance of java.util.Properties clas
s. This class contains all the methods required to manage and access the propert
ies file. The properties files are used quite frequently in Java applications fo
r storing and managing the configuration value which your application may requir
e during various phases of its execution. For Example, you may have a property n
amed "DBURL" and you can simply use the value associated with this key to fetch
the Database URL you would like to use at run time. The advantage of using this
approach is that if you want to change the DBURL then you don't need to touch th
e code now. The all you need is to go and change the Value associated with the "
DBURL" Key in the properties file being accessed in your application. This will
make your application far more flexible and maintainable. If a user (say a teste
r) doesn't know Java then it'll be difficult for him/her to change the URL in th
e Java code, but changing the value in a text-file will be easy for everyone and
hence such an approach will enhance the usability of your application as well.
getProperty(String key) and getProperty(String key, String defaultValueifkeyNotF
ound) are the methods used to read the properties. Similarly, setProperty(String
key, String value) is the method to add another Key-Value pair to the Propertie
s object.
Caution: Access to a properties file requires approval from the current security
manager of the running application. So, you may not like to put any such code i
nside an applet as the browser, your code will run into, may not have enough pri
viledges to access a file on the local disk. Moreover, it's hard to assume that
the property you require in your applet will be there in the properties file (or
even a file with that name will exist) on the local disk.

System Properties in Java


The way we use custom proprties file to maintain the configuration details of ou
r application, the Java platform also uses a Properties object to maintain the c
onfiguration details of the current runtime environment. This object is called S
ystem Properties and it stores hell lot of Key-Value pairs for different propert
ies the Java runtime environment uses to maintain the execution environment. Som
e of these properties store the Current User, Version of the Java Runtime Env, P
ath Separator character, OS Name, OS Version, User's Working Directory, User's H
ome Directory, JDBC Drivers, etc. Many of these System Properties are standard,
but few additional platform dependent System Properties may also exist.
Reading/Writing to the System Properties
Reading is pretty simple. You just need to use 'System.getProperty()' method. Th
is method has two variants. One, which requires only one String argument. Two, w
hich requires two String arguments. For the one which requires only one argument
, you need to give the name of the System Property you're trying to get the valu
e of. This method returns 'null' if the property with that name doesn't exist. T
he second variant of this method requires you to specify the second String argum
ent as the value you would like to be returned (instead of 'null') in case a pro
perty with the name given as the first argument doesn't exist.
Writing to the System Properties is not quite similar to what we use to write to
a normal Properties onject. We use 'System.setProperties()' method, which requi
res a Propereties object. You need to set this object with all the required Key-
value pairs. Beware, it replaces the entire set of system properties with those
represented by the passed properties object. The changes made by this method wil
l last only for the current run time environment and the Java run time system re
-initializes the system properties each time it starts up. If you want to make t
he changes permanent then you need to write the value to some file before shutti
ng down the application and load and set the System Properties each time the app
lication starts up.
Caution: Read/Write access to the System Properties is also governed by the curr
ent Security Manager of the running application, so you may be denied the access
in various situation - most common of them being 'accessing them in Applets'.

Difference between loading the JDBC Drivers through System Properties and throug
h Class.forName()?
Well... no real difference in the functioning of the drivers. It's just the time
of loading and instantiating the drivers that gets different in these two cases
. In case of loading the drivers through System Properties, they get loaded and
instantiated during the start up of the Java Runtime Environment itself while lo
ading them through Class.forName() will cause the loading and instantiating of t
he driver during the execution of this Java statement. You may like to read the
article 'Role of DriverManager Class and Driver Interface in Java' for more deta
ils.

Share/Save/Bookmark

Posted by Geek at 5:08 PM 0 comments


Labels: Java, JVM
Saturday, May 24, 2008
Why Java does not have Clear Screen functionality?

Why Java does not have Clear Screen functionality?

Clear Screen functionality has not been implemented in Java as it's simply not p
ossible without sacrificing Platform Independence. So, how to handle a situation
asking this? Well... Java has not been designed to develop applications requiri
ng a direct console based interaction. You may think of using Swing or AWT based
GUI instead. It's not impossible to have such a functionality in Java, but cert
ainly not portable and hence not preferrable. We do have few platform dependent
workarounds to achieve it in Java and the best among the lot still remains the s
ame - using JNI.

In Java, we don't have the concept of a typical console as we have in C/C++. Ins
tead all I/O in Java is stream-based. I don't think Clear Screen can be implemen
ted for a stream as the steam may point to a file, a printer (it will be a reall
y challenging scenario, isn't it?), or may be to a console on certain platforms.
Since, you never know what this stream would be pointing to at run time, you ca
n't assume it to be a console in all the cases and hence can not have that funct
ionality. Clear Screen will obviously make sense only for clearing the console a
nd not for a file (logs etc.).

System.out.println() is far more easier to implement in all environments maintai


ning platform independence as irrespective of what the stream points to at runti
me, it can always be written on. This holds true for C/C++ as well. And probably
this is the reason why 'printf()' works fine in all environments in case of C/C
++ (Now in Java also ... Java 5.0 onwards) and not 'clrscr()'.

C++ also has the concept of Streams similar to that in Java and I think Clear Sc
reen function is not a part of any class based on streams. It's a separate metho
d altogether and it has a specific implementation only for those environments wh
ich have the concept of Console. For different platforms we may need to look for
different vendor specific extension to have that functionality even in case of
C/C++. For instance, Turbo C/C++ has the function 'clrscr()' in the vendor speci
fic header file 'conio.h'. We don't have that header file available for Linux pl
atform.
Similar explanation can be given for other platform dependent tasks such as 'acc
epting input without ENTER being pressed - a functionality getch() provides in C
/C++', 'applying font color, background color, etc. on the console', and so on.
Such tasks have not been implemented consistently across all platforms even in C
/C++, so forget about Java. The goals of Java will probably never allow such tas
ks to be implemented not at least by using standard library functions. You got t
o use platform-dependent vendor specific packages to achive them unless of cours
e, all the environments start following the same standards for console and other
related stuff.

I thank Lavnish (one of our regular visitors) for raising this point in response
to the post on 'Limitations of Java Language'. He runs a blog and writes freque
ntly on Java. You can find his post on the Clear Screen functionality here. I ho
pe our visitors will continue chipping in with their valuable comments and makin
g this place better and better for us.

Update from Java 6.0

Java 6.0 has gone C/C++ way to facilitate better interaction with character-base
d console devices by using standard library functions. It seems that it wasn't p
ossible for them to have such features for traditional Java Streams and hence th
ey created a new Java Class named java.io.Console. This Class is mainly for read
ing from and writing to the Console and not for clearing it (as of now).

The Sun Java Doc of this class clearly says that the class contains methods to a
ccess the character-based console device, if any, associated with the current JV
M. We can obviously see a compromise with Platform Independence here as the code
written using this Class can never be guaranteed to behave uniformly across all
platforms and hence not portable. System.console() method simply returns 'null'
on the platforms which doesn't have an associated Console with the underlying J
VM.

On the platforms where it finds a Console, it probably uses JNI internally to ge


t the task done. We always have such solutions provided by third party vendors a
nd the only good thing about the addition of this new class is probably that it'
s now a part of the standard library and it might be having little more efficien
t code than the code supplied by the third party vendors.

BTW, the center of our discussion 'Clear Screen functionality' is still not ther
e in this class. Let's see if at all they provide that also in the newer release
s of Java.

The bottom line remains the same - we would probably never have any such functio
nality without compromising Platform Independence and in most of the cases the A
PIs would probably be using JNI only. A true Java solution to this problem still
remains a topic of research.

Share/Save/Bookmark
Posted by Geek at 11:23 PM 1 comments
Labels: Java, JVM
Friday, May 23, 2008
Rope Bridge, Torch, Four People - Puzzle

Puzzle: Four people need to cross a rope bridge, which is strong enough to suppo
rt only two people at a time. First person takes 1 minute to cross the bridge, S
econd person takes 2 minutes, Third person takes 5 minutes, and the Fourth perso
n takes 10 minutes to cross the bridge. They have a torch which has battery left
only for 17 minutes and the bridge can not be crossed without light. How will t
hey manage to cross the bridge?

Solution: Let's say the four people as P, Q, R, and S. Based on the info we have
, let's consider P takes 1 minute, Q takes 2 minutes, R takes 5 minutes, and S t
akes 10 minutes to cross the bridge.
Now, they can manage to cross the bridge in time if they follow the below steps:
-
* Step #1: P and Q cross the river. Total time taken so far = 2 minutes
* Step #2: Q comes back. Total time taken so far = 2 + 2 = 4 minutes
* Step #3: R and S cross the river. Total time takes so far = 4 + 10 = 14 mi
nutes
* Step #4: P comes back (he's at the other end). Total time so far = 14 + 1
= 15 minutes
* Step #5: P & Q cross the river. Total time taken so far = 15 + 2 = 17 minu
tes

We can have another valid solution similar to the above in case P comes back ins
tead of Q in Step #2:-
* Step #1: P and Q cross the river. Total time = 2 minutes
* Step #2: P comes back. Total time = 2 + 1 = 3 minutes
* Step #3: R and S cross the river. Total time = 3 + 10 = 13 minutes
* Step #4: Q comes back. Total time = 13 + 2 = 15 minutes
* Step #5: P and Q cross the river. Total time = 15 + 2 = 17 minutes

Share/Save/Bookmark

Posted by Geek at 9:57 PM 0 comments


Labels: Puzzles
Adobe - Reverse the order of words in a char seq

Question: Write an efficient algorithm to Reverse the order of words in a given


array of character which form a sequence of words.
Note: Memory-based question, suppodely a part of 'Engineering' section of the wr
itten test for a Dev position at Adobe.

Solution: Find below one possible algorithm to solve this problem:-


* Allocate memory for another array of same size
* Iterate through the array and find words (by finding white spaces)
* Put the word reversed (order of characters reversed) in the new array
* Put the white spaces as well (you won't reverse them as they are same eith
er way)
* Continue and complete the iteration for all the words in the array
* Copy the new array reversed into the original array and you're done!

Example: Suppose you have one array "int char float" in the beginning. The expec
ted result should be "float char int" in this case. Let's dry run the above algo
rithm for this test array and see if it gets us the expected result.

NewArray = " " (a array of 14 characters, currently all blank)


Iteration starts here
First word found: "int", so NewArray = "tni "
Second word found: "char", so NewArray = "tni rahc "
Third word found: "float", so NewArray = "tni rahc taolf"
Iteration ends here

Now reverse of the NewArray = "float char int"

Share/Save/Bookmark

Posted by Geek at 9:49 PM 0 comments


Labels: Adobe Interview, Algorithms
Adobe - C code for allocating a 2D (or 3D) array

Question: Write C code to dynamically allocate and free memory for a 2D (or 3D)
array.
Note: Memory-based question, suppodely a part of 'C Programming' section of the
written test for a Dev position at Adobe.

Solution: Here, I'm taking the case of a 2D array only. Allocation of a 3D array
will also be quite similar. Let number of rows be ROW and number of columns be
COL. There are at least three ways of doing the allocation, which are:-
Method #1: Store the elements of the array as a set of ROW, each of which holds
COL integers. An array of ROW integer pointers, each of which will point to the
corresponding row having COL integers each. Array is accessed as arr[i][j]. The
allocation may be Non-Contiguous in this case.

Find above the C-code for allocating and freeing a 2D array following this metho
d. Click the image to enlarge it.
Method #2: Store the elements of the array as a 1D array of ROW*COL integers wit
h an array of ROW integer pointers which refer to the appropriate places in the
previously allocated 1D array for the arr[i][j] type of access. In this case the
allocation will always be Contiguous.

Find above the C-code for allocating and freeing a 2D array following this metho
d. Click the image to enlarge it.
Method #3: This method is just a variant of the second method. In this case we a
llocate memory for 1D of ROW*COL integers and access the elements as arr[COL * i
+ j], instead of arr[i][j]. The allocation is always Contiguous in this case as
well.

Find above the C-code for allocating and freeing a 2D array following this metho
d. Click the image to enlarge it.

Share/Save/Bookmark

Posted by Geek at 9:37 PM 0 comments


Labels: Adobe Interview, C Language
General HR Interview Questions - Set #2

When would you expect your next promotion?

It's difficult to predict an exact time for this due to a variety of reasons, so
you may straightaway answer this by saying "Well... it's pretty difficult to gi
ve you an exact time frame without knowing the hierachical structure of employee
s in the company, the responsibilities attached to each of the positions in that
hierarchy, what all does it take to reach to next level in the company, and how
long does it take to reach in the best case, etc. The only thing which I can sa
y here is that I'm very sure of exceeding the expectations the company has from
me with my focused hard work & right attitude and in reply I certainly expect to
reach to the next level in the hierarchy in the minimum possible time frame."

Why are you looking for a change / a new job?

Almost a certain question in all your interviews if you're making a switch. Fres
hers will be lucky here. Anyway, the key here is to focus on what value addition
the new company can provide you. At the same time, do mention all the skills yo
u developed while working for your current company. Change is the only constant
thing in life, so no body minds if you have a valid reason. But, criticising the
current company may cost you dearly, as even the new company knows that you're
not (in most of the cases) going to stay there for the rest of your career, and
hence you might be saying similar stuff about them at some time down the line. Y
ou may answer this question by saying "I've worked for <these many> years/months
and it's been a nice stay so far. I've grown both as a person and as a professi
onal here. Now my expectations have exceeded and I'm not able to align myself wi
th the goals of <the current company>. I need some diversification - different p
rojects, different environments, different technologies, etc. to enhance other s
kills, which I couldn't do here." If you're moving from a company not having any
on-site opportunities to a company having that then you may go on and add "My c
urrent company is not having any on-site opportunities and I'm looking for worki
ng in a different culture, different environment, different country, etc. This w
ill not only help me to grow even better as a professional, but also provide me
an opportunity to earn extra, which is undeniably an important motivating factor
". If you think that you're going to get a very good salary hike in the new comp
any then you may mention that as well because they anyway know that and hiding t
hat won't impress them for sure.

Share/Save/Bookmark

Posted by Geek at 9:27 PM 0 comments


Labels: HR
Thursday, May 22, 2008
Adobe - Larger of two int without Logical or Relational ops

Question: Find the larger of two integers without using logical or relational op
erators.
Note: This question was supposedly asked sometime back in the 'C Programming' se
ction of the written test for a Dev position at Adobe. The question is purely ba
sed on memory and collected either from friends, colleagues, or Web. No guarante
e whether the same question actually appeared in their test. However, you may us
e it to your advantage by having a feel of the type of questions Adobe asks.

Solution: In C, UINT_MAX represents the maximum value an unsigned integer can ha


ve and INT_MAX represents the maximum value of an integer variable.
So, (UINT_MAX >> 1) will have the same value as INT_MAX and consequently ~(UINT_
MAX >> 1) = ~(INT_MAX) with all the bits as '0' and only the sign bit set as '1'
.
If the given two integers are 'a' and 'b' then (a - b) will be negative for the
case where 'a' < 'b' and hence the sign bit will be '1' for (a - b) in that case
. Right? Now (a - b) & ~(UINT_MAX >> 1) will be 'true (1)' in this case as for b
oth the operands of the operator '&', the leftmost bit is '1'. Other bits will b
ecome '0' as the second operand has all other bits set as '0'.
That means (a - b) & ~(UINT_MAX >> 1) will be true in case 'a' < 'b'. We can eas
ily understand that (a - b) will be true (some positive number) in case of 'a' >
'b'. Otherwise, both the operands will be equal i.e., 'a' == 'b' in which case
both the above conditions will return 'false (0)'.
Code Snippet in C:
if ((a - b) & ~(UINT_MAX >> 1)) /*... OR, (a - b) & ~INT_MAX ...*/
/*... a is less than b ...*/
else if (a - b)
/*... a is greater than b ...*/
else
/*... a is equal to b ...*/

Share/Save/Bookmark

Posted by Geek at 8:47 PM 1 comments


Labels: Adobe Interview, C Language
Adobe Interview - C Function to Reverse a String

Question: Write a C Function to Reverse a String


Note: This question was supposedly asked sometime back in the 'C Programming' se
ction of the written test for a Dev position at Adobe. The question is purely ba
sed on memory and collected either from friends, colleagues, or Web. No guarante
e whether the same question actually appeared in their test. However, you may us
e it to your advantage by having a feel of the type of questions Adobe asks.

Solution: Fairly easy one, I guess. The steps are as follows:


* Compute the length and store in a variable
* Declare one temporary variable to iterate through the string
* Iterate through the string array (only half length) from both the ends
* Keep swapping the characters during the iteration
* Exit from the loop. The string is reversed now :-)

Find above the Code Snippet in C (as it was supposedly asked in the C Programmin
g section :-)). Click the image to enlarge it.

Share/Save/Bookmark

Posted by Geek at 8:30 PM 0 comments


Labels: Adobe Interview, Algorithms, C Language
Wednesday, May 21, 2008
What is the age of the oldest child who plays Piano?

Puzzle: Two freinds (say A & B) see each other after a very long time, say 20 ye
ars. After a brief conversation, A finds that B is married and having 3 children
. When inquired about the age of the children B replies to A "The product of the
ir ages is 72 and the sum of their ages is same as the number on that building (
pointing to a building)". A tries to think for a while and then says "Oh... I co
uldn't find the ages". Then B promptly realizes something and responds "The olde
st plays Piono". Now A smiles and says that his oldest child is also of the same
age. How old is the oldest child of A (or B)? Consider that all the ages are na
tural numbers only.

Solution: The only concrete piece of info we have here is that the product of th
ree natural numbers is 72. We can think of all such triplets in not more than fe
w minutes. But, this info is not sufficient. A can see the number on the bulding
that means he know the sum and still couldn't find the triplet. Therefore, ther
e would be more than one triplet for the same sum. Otherwise A would have easily
found the correct triplet and in turn the age of the children. Right?

B's reponse brings up only one point that the highest of the correct triplet is
unique and then only he can say that the oldest child plays piano.

Good. We have enough info now. We just need to write down the triplets now and t
he answer will be quite apparent then. The triplets satisfying the first info (p
roduct being 72) are: (1, 1, 72 -> Sum = 74), (1, 2, 36 -> Sum = 39), (1, 3, 24
-> Sum = 28), (1, 4, 18 -> Sum = 23), (1, 6, 12 -> Sum = 19), (1, 8, 9 -> Sum =
18), (2, 2, 18 -> Sum = 22), (2, 3, 12 -> Sum = 17), (2, 4, 9 -> Sum = 15), (2,
6, 6 -> Sum = 14), (3, 3, 8 -> Sum = 14), and (3, 4, 6 -> Sum = 13).

You can easily see that there are two triplets with the same 'sum'. Hence, the b
uilding next to A & B has this number '14'. These triplets are (2, 6, 6) and (3,
3, 8).

Now, the info 'the oldest' eliminates the triplet (2, 6, 6) as in this case the
highest number has two occurrences and hence A would not be having a single 'old
est child'. Instead he would have been having twins in that case :-)

So, the only choice left is (3, 3, 8) and hence the oldest child of A (or B as b
oth are of the same age) is 8 years old.

Share/Save/Bookmark

Posted by Geek at 10:13 PM 0 comments


Labels: Puzzles
What all Request Response Patterns do we have in SOA?

Request-Response Patterns used in SOA

Following are the most popular Request Response Patterns used in SOA:-
* One Way Message - Here the client doesn't require the response at all. It'
s used to implement the 'ping' type services where the client simply pings a pie
ce information (for example, one server acting as a client may ping to another s
erver that it's up and running or any other info for that matter) to the server
and the communication terminates. In BPEL, it's implemented using one Invoke act
ivity.
* Synchronus Interaction - Here the connection is maintained till the respon
se reaches the requester. In BPEL, it's normally implemented with one Invoke act
ivity at the Consumer end and one Receive & one Reply activity at the Provider e
nd.
* Asynchronous Interaction - In this case the consumer requests and goes int
o a blocking call, but the Provider doesn't maintain the connection and responds
as per its convenience. In BPEL, it's implemented with one Invoke & one Receive
activity at the Consumer end and one Receive & one Invoke at the Provider end a
s well.
* Asynchronous Interaction with Timeout - Here the Consumer go into the bloc
king call only till the Timeout expires (or if the response reaches in the mean
time it resumes the execution). In BPEL, it's implemented with one Invoke & one
Pick at the Consumer end and one Receive & one Invoke at the Provider end. In th
e Pick ACtivity, we can specify the timeout period.
* Asynchronous Interaction with Multiple Mandatory Responses - Mandatory res
ponses mean we can't you the concept of timeout here. So, Receive activity will
be used here and not the Pick activity. In BPEL, it can be implemented with one
Invoke & Multiple Receive activities at the Consumer end and one Receive & Multi
ple (the same number as the number of Receive at the Consumer end) Invoke activi
ties at the Provider end.
* Asynchronous Interaction with Notification Timer - Unlike the Async with T
imeout, the Consumer doesn't unblock and keeps waiting for the response, but it
raises notifications after certain time periods. In BPEL, it can be implemented
with one Invoke & one Receive (with OnAlarm for notification) at the Consumer en
d and one Receive & one Invoke at the Provider end.
* Asynchronous Interaction with a Mandatory Response(s) and an Optional Resp
onse(s) - For the mandatory response, we'll those many Receive activities at the
Consumer end and the same number of Invoke activities at the Provider end. For
optional responses we need to use onMessage at the Consumer end Optional Invoke(
s) at the Provider end.

Share/Save/Bookmark

Posted by Geek at 9:52 PM 0 comments


Labels: SOA
Tuesday, May 20, 2008
Enterprise Service Bus (ESB) - What and Why?

What is Enterprise Service Bus (ESB)?

SCA foundation is built using ESB Infrasture layer to enable "Separation of Conc
erns" which facilitates the client to become free from knowing and implementing
so many details, which the client would be forced to do otherwise.

Example: Let's assume there are two business processes BP-1 and BP-2 and we have
a requirement saying that BP-1 should get called only when the value of a certa
in input variable is greater than 500 otherwise BP-2 should get called. Without
ESB how would we do that? By stuffing that logic in the client code. We will che
ck that variable at that end and call either of the two web services implementin
g BP-1 & BP-2 based on the value of the input variable under consideration.

With the help of ESB, we don't need to do that at client side. Actually ESB infr
astructure forms another layer between the client and the actual Web Services an
d all such tasks are performed at ESB layer, which makes the implementation far
more maintainable and stable.

Another example scenario can be where an input variable needs to be transformed


before the service gets called and the service should accept only the transforme
d value. In addition the response may also need to be tranformed back to some ot
her format before being given to the client. Let's say the client accepts only P
in Code numbers whereas the service requires the area name associated with Pin C
ode and not the raw pin code number. We can achieve all such transformations qui
te easily and effectively using the ESB Infrastructure.

Why ESB?

Well... There are quite a few reasons. Some of them are:-


* Virtualization - You don't require to maintain the URL of the actual Web S
ervice. What you require is to know the URL of the ESB, which will act as the We
b Service for the client. The ESB will route the request to the appropriate URL
and return back the response to the client.
* Transformation - The data in the request can be tranformed easily and effe
ctively before being set to the actual service and similarly the response can al
so be tranformed before reaching the client.
* Routing - The requests can be filtered at the ESB layer and based on the i
mplemented Routing Rules they can be forwarded to the desired Web Service URLs.
This routing can either be content-based or header-based. An example of content-
based routing: an input variable is checked and let's say if that variable has a
value '1' then the request will be forwarded to an external Web Service whereas
the value of that input variable as '0' will route the request to an internal W
eb Service for faster performance or any other reason. Similarly an example of h
eader-based routing: if the request is coming from '*.abc.com' frward it to an i
nternal Web Service otherwise route to an external Web Service.
* Validations - ESB layer can be used to validate the request XML or respons
e XML against selected XSDs. Validation based on an XSD is a relatively performa
nce intensive task, so now the valiadtion can also be done against a 'Schematran
(.sch files)' for better performance. SCH has also become a standard for Open-S
OA now.
* Event Handling - At ESB level you can either subscribe to or raise busines
s events. For example, let's say the business requirement is such that as soon a
s a new customer is added to the system, a business event should be raised for t
he creation of his/her email account. Using ESB Infrastructure you can easily cr
eate, raise, and publish that event which will eventually be received by the com
ponent responsible for Email Account creation.
* Interactions - Using ESB you can easily implement Synchronous or Asynchron
ous interactions between consumers and providers.
* Security Enforcements - In addition to the above advantages, the ESB layer
can also be used to enforce security of various levels. Example: you may like t
o authenticate all the requests coming from a particular domain. You can easily
do that using ESB. Far more advanced security measures can also be implemented q
uite easily using ESB.

Share/Save/Bookmark

Posted by Geek at 9:11 PM 3 comments


Labels: Miscellaneous
Archives from the Category Java - 9

Archived Articles from the Category Java


* Guarded Blocks in Java - what are they & why are they used?
* Deadlock - what's it? How to deal with this situation?
* Ways of implementing Variable Argument Lists in Java
* Facts about IEEE 754 floating-point arithmetic in Java
* Composition vs Aggregation. What's Association in UML?
* Java Architecture, JVM, JRE, Java Platform, & JDK
* Loading, Linking, & Initialization of a Type - Class/Interface
<<Older Articles
Share/Save/Bookmark

Posted by Geek at 8:21 PM 0 comments


Labels: Archives
Monday, May 19, 2008
Service Component Architecture (SCA). SCA vs SOA

Service Component Architecture (SCA)


It's a set of specifications that defines an assembly model model for composite
services and also provides a programming model to build applications which are S
OA-based.

A composite service can have serveral business processes, bindings, properties,


human workflows, etc. all put together. We define a Composite and once the Compo
site is ready it's for you to be treated as a single component and can easily be
exposed as a composite service the way you expose a web service.

SCA makes the deployment design very easy. Suppose your application have n busin
ess processes and let's say BP-1 is the entry point to the application then you
can define a composite by specifying the navigation details among the various bu
siness processes and/or human workflows and then you can expose BP-1 as a compos
ite service. Now, the composite service is having a well defined assembly of all
the components involved in your application and ready to be deployed. You don't
need to deploy the individual components separately. All will be handled by SCA
. All the assembly information is stored in an SCA Descriptor.
SCA vs SOA

SCA focuses on the assembly of various components to provide an easier design an


d deployment while SOA provides an architecture or style to design and develop t
he individual components. SCA comes into pictures only when you're ready with al
l the components. So, you create components with SOA and assemble them using SCA
mainly to make the deployment easier.

Share/Save/Bookmark

Posted by Geek at 10:38 PM 0 comments


Labels: SOA
Web Services - What, Why, How, and Shortcomings

Web Services
W3C defines it as a "software system designed to support interoperable Machine t
o Machine interaction over a network". Web Services are actually Web based (http
protocol based) appications or components that use XML-based standards and prot
ocols to communicate with the clients. Web Services are language and platform in
dependent as XML is a standard and it uses XML-based open protocols for expressi
ng requests and responses and hence eliminates the dependence on the underlying
operating system and programming language.

A Web Service normally implements a discrete business functionality completely.


It's self-contained and self-describing and discovered using UDDI. An applicatio
n based on Web Services is loosely coupled and easier to develop and maintain as
the requirements are broken down into various modules, which are designed and d
eveloped almost independently and in parallel. The granularity of the services p
lay a big role here. There will always be a trade-off between network latency an
d ease of use for coarse-grained and fine-grained services. The choice is depend
ent mainly on the context you're supposed to use the service in.

Why Services?
* Platform Independence
* Interoperatability
* Faster Development
* Easier to maintain/upgrade with least down-time
* Integration
* Modular Approach

How does it work?

A Web Service is a Web based application that means it's 'http' protocol based.
It uses XML as a language for communication between different platforms. The Web
Services platform can be broken down in three elements which are:
* SOAP (Simple Object Access Protocol) - this is the communication protocol
used by Web Services to communicate between application. SOAP is a XML based pro
tocol and it facilitates a standard format for sending messages over http. Since
, it's XML based, so it's extensible and language independent.
* UDDI (Universal Description, Discovery, and Integration) - It's a director
y for storing information about Web Services. The information is stored in form
of WSDL documents.
* WSDL (Web Services Description Language) - As the name suggests, WSDL is a
XML-based language which describes a Web Service. A WSDL document gives answer
to these questions: What the Service takes as input(s) and what it returns as ou
tput, How the Service can be accessed, Where the Service is located. (Note: A de
tailed post on the details of WSDL will follow soon.)

Shortcomings of Web Services

Platform and Language independence comes with one inherent limitation that a Web
Service call will be relatively slower. This is due to the network latency, tim
e taken in conversion to and from XML while sending and receiving requests and r
esponses.

This architecture is still in the very early stages and many new features and en
hancements are still awaited. Features like Security and Routing are still missi
ng and hopefully they will also be introduced very soon.

Share/Save/Bookmark

Posted by Geek at 10:24 PM 1 comments


Labels: SOA
Role of DriverManager class and Driver interface in Java

DriverManager class

It's used for establishing JDBC connections and for managing JDBC drivers. JDBC
2.0 API has a new interface DataSource and the preferred means of connecting to
a data source has now become by using a DataSource object.

DriverManager tries to load the driver classes mentioned in the 'jdbc.drivers' s


ystem property while the initialization. You can explicitly load JDBC drivers at
any time by using the 'Class.forName("driver class");' syntax.

getConnection method of the DriverManager class tries to locate a suitable drive


r from amongst those loaded either during the initialization or by using Class.f
orName() explicitly. On successful invocation, this method returns a Connection
object. You need to specify the database url having the subprotocol & subname, u
ser id, password, etc. If any error occours during the database access then a SQ
LException is thrown.
Driver interface

Every databse driver needs to implement this interface. As mentioned above you c
an load as many databse drivers you want, but all of them must implement this in
terface. Each driver will provide a class implementing the Driver interface. Onc
e these classes are loaded, an instance of it created and registered with the Dr
iverManager. Loading, instance creation, and registration all done by calling th
e forName method 'Class.forName("driver class");'.

This method has a method named 'connect()', which accepts URL of the database an
d other required info of type java.util.Properties which contains the user id, p
assword, etc. kind of information. This method returns either a Connection objec
t on successful invocation. The failure can occur in two cases:
* If driver manager tries the url with the wrong driver (as it passes the ur
l to every driver unless it either gets success or SQLException) in which case t
he method returns 'null'.
* Else if the driver manager tries the url with the right driver, but the co
nnection doesn't get established due to some databse problems then the method re
turns SQLException.

Share/Save/Bookmark

Posted by Geek at 10:07 PM 2 comments


Labels: Java
Why would you like to work for us?

Like most of the other HR questions, this question will also have different answ
ers for different people and positions. The key here is to focus on what all mai
n qualities (required to be successful in the role you applied for) the company
is good at. You can almost always find few quite good things about the company y
ou are looking for.

Hmm... so start focusing on what are the areas the company is really good at fro
m an employee point of view such as innovation, actual development work, quality
of development work, etc. Completed? Good. You would now be having a list of th
e areas the company is impressive at and you're half done by now. What's next? N
othing great. You just need to see how the position you applied for, will fit in
the scheme of the things.

So, a person applying for a design and developmet position may start with saying
"I would like to work for the company for quite a few reasons and one main reas
on is that the company is really innovative and it's regarded as one among the b
est for this in India (or globe whatever). This will give me a chance to develop
and refine my skills to a great extent and in turn it will help me growing as a
better developer...". You can go on saying why you're suitable for such a compa
ny/position by saying "I've always been considered as a good problem solver. Dur
ing my stay in the previous company (Or in my college - for freshers) I got few
opportunity to prove my worth and I managed all of them successfully... I'm a go
od learner and my focused work can really produce good results. This position/co
mpany will only motivate me to try and do even better."

Then you can move on to the work environment the company can provide for you. Wi
thout a conducive working environment no company can draw best out of its employ
ees and certainly won't be a favourite among the professionals. In the worst cas
e if you think that the company is not that good in that area then also you got
to respect the company and term it at least 'decent' in your interview :-)

You can probably then move on to the other specific benefits, the position can o
ffer you, like on-site opportunities, client interaction, trainings, etc.

Finally, if you're getting a good pay hike then you may like to be little honest
and mention that also as one of the reasons, but saying that in the last part o
f your answer is preferable. It'll not be good idea to start your answer straigh
taway mentioning that point. Be honest, but do avoid being brutally honest :-)

Share/Save/Bookmark

Posted by Geek at 10:04 PM 0 comments


Labels: HR
General HR Interview Questions - Set #1

What concerns do you have about the job?

I don't think it's a good idea to mention any concerns. If it's so serious just
don't go for that job otherwise it would be quite light to be avoided. Agreed?

So, you may confidently say "I don't have any concerns at all. I believe I've th
e right skills and abilities required to be successful in the position. I'm look
ing forward to the challenge and I believe I'll stay focused to prove my worth..
. blah blah :-)"

What concerns do you have about the company?

Again, no concerns for the same reasons. You may say "I don't have any concerns
about the company. I've researched about the company and found it quite good in
terms of work, environment, performance based appraisals & promotions, etc. So,
no concerns at all. Just looking forward to have a long association with it"

How soon will you start contributing to the company?

You may say "Well... I don't have enough idea of the complete set of responsibil
ities, the trainings I need, etc. associated with the position. So, I don't thin
k I'm a good position to comment on it as of now. But, I can assure that my lear
ning curve and time taken to start working on the projects will be as per what t
he company expects out of an new recruit, if not better."
Share/Save/Bookmark

Posted by Geek at 9:57 PM 0 comments


Labels: HR
Archives from the Category Java - 8

Archived Articles from the Category Java


* Synchronization of static methods/fields in Java
* Why synchronization of constructors is not allowed?
* What is Reentrant Synchronization in Java?
* Thread.State in Java? BLOCKED vs WAITING/TIMED_WAITING
* Alternatives of stop, suspend, resume of a Thread in Java
* Why stop, suspend, resume of a Thread are deprecated?
* Conditional Compilation & Conditional Initialization/loading
* Assertions in Java? Assertions vs Exception, Usage, etc.
* Do Interfaces really inherit the Object class in Java?
* Error/Exception Handling in JSP - using JSPs and Servlets for errors
* Field Hiding in Java - fields are only hidden not overridden in Java
* How to automate user input events for GUI programs in Java?
* How can you detect the shutdown of JVM programmatically?
* Common questions and their answers on Shutdown Hooks
* Overruling uncaught checked/unchecked exceptions in Java
<<Older Atricles ------- Newer Articles>>
Share/Save/Bookmark

Posted by Geek at 7:58 PM 0 comments


Labels: Archives
Sunday, May 18, 2008
Array vs Linked List. Intro, Pros & Cons, Usage, etc.

Array

Possibly the most common data structure used to store data. One memory block is
allocated for the entire array which holds all the initialized (and rest of the
uninitialized) elements of the array. Indexing is 0-based and the elements can b
e accessed in a constant time by using the index of the particular element a as
the subscript.

Why constant time for accessing array elements? - The address of an element is c
omputed as an offset from the base address of the array and one multiplication i
s needed to compute what is supposed to be added to the base address to get the
memory address of the element. Since memory requirements for every data type is
different, so first the size of an element of that data type is computed and the
n it's multiplied with the index of the element to get the value to be added to
the base address. So, the process requires just one multiplication and one addit
ion and this is required for every element irrespective of its position in the a
rray. Hence access is faster and requires a constant time.

Advantages of using arrays:


* Easier to use and access
* Faster access to the elements

Disadvantages of using arrays:


* Fixed size - the size of the array is static
* One block allocation - if you don't have enough memory to provide a single
block (but you have sufficient scattered memory blocks) to allocate the space f
or the array then you'll need to defragment and other similar stuff to first cre
ate a free block of that size. So you may like to term it as improper utilizatio
n of memory :-)
* Complex position-based insertion - if you want to insert an element at a p
osition already covered by some other element then you got to shift right by one
position all the elements to the right of that position. This will vacate the p
osition for you to insert the new element at the desired position. The more elem
ents you have to the right of the desired position, the more expensive the proce
ss will be :-)

Linked List

Elements are not stored in contiguous memory locations, not at least guaranteed
to be stored like that :-) Every node contains an element and a link to the next
element. The allocation is not static instead it's dynamic. Whenever a need ari
ses, you got to first allocate memory for the node (Using malloc() in C/C++. In
Java it'll be like any other object creation) and then use it to store the new e
lement and link either as 'null' (in case it's the last element) or the link wil
l store the address of the element, which is supposed to be next to the element
being added. Since the memory is allocated dynamically, so it'll continue to exi
st unless you will need to explicitly kill it in the languages not having automa
tic memory management (Using free() in C/C++. Java enjoys the facilities of the
garbage collector).

Node definition in C/C++: we assume that elements are of type 'int'


struct node {
int element;
struct node * link;
};
In Java it is even simpler, so I'm skipping that here.
Advantages of using Linked Lists:
* Flexibility - insert at (or delete from) any position in contant time
* No single allocation of memory needed - fragmented memory can be put to a
better use
* Dynamic allocation - the size is not required to be known in advance

Disadvantages of using Linked Lists:


* Complex to use and access - relatively complex as compared to arrays
* No constant time access to the elements - simply because it doesn't involv
e the simple arithmetic used by arrays to compute the memory address, so relativ
ely inefficient as compared to arrays

When to use what?

The interesting fact about Linked List is that it's normally used as a complimen
tary solution to handle the disadvantages of arrays. Arrays certainly have their
own advantages and they're still used more widely, but Linked Lists has provide
d an efficient and effective alternative to arrays in the cases where you're bot
hered by the limitations of the arrays. So, you may see both arrays and linked l
ists as complimentary to each other and not as rivals. Choice is based mainly on
the context you're planning to use any of the two data structures.

Share/Save/Bookmark

Posted by Geek at 12:01 PM 0 comments


Labels: Data Structures
Adding new node to a Linked List at head/tail

Algorithm for adding a new node at head


* Allocate memory for the new node
* Assign the element of the new node with the required value
* Assign the link of the new node with the current head of the list
* Set the current head to the new node

Algorithm for adding a new node at tail


* Allocate memory for the new node
* Set the element of the new node to the required value
* Set the link of the new node to 'null' (as it'll be the last node)
* Check if the list is empty or not
* If the list is empty, simply assign the new node as the head
* Else if the list is non-empty, iterate to the current tail of the list
* Set the link of the current tail to the new node

Share/Save/Bookmark

Posted by Geek at 11:53 AM 1 comments


Labels: Algorithms, Data Structures
Algorithm of copying a Linked List

Algorithm of copying a Linked List:


* Check if the list is non-empty and then only proceed otherwise return
* Iterate through the source list
* Create a new node for the destination list
* Set the element of this node to that of the current node of the source lis
t
* If it's the first node then assign the tail of the new list to this node
* Else set the tail to the link of current tail
* Set the link of the tail to 'null'
* Continue with the rest of the elements of the source list
* Return the head of the new list

Share/Save/Bookmark
=================================================================
What is a Relational Database? What're Integrity Rules?

Relational Database
It's a database which stores and manages the information in tables, which are co
mposed of rows and columns. The name 'Relational' came from that fact that the t
ables in such a database are nothing but a collection of similar type of informa
tion stored in form of rows. This is the reason why a table is also referred to
as a relation in such a DB.
Integrity Rules
These are the rules which a relational database follows in order to stay accurat
e and accessible. These rules govern which operations can be performed on the da
ta and on the structure of the database. There are three integrity rules defined
for a relational databse,which are:-
* Distinct Rows in a Table - this rule says that all the rows of a table sho
uld be distinct to avoid in ambiguity while accessing the rows of that table. Mo
st of the modern database management systems can be configured to avoid duplicat
e rows.
* Entity Integrity (A Primary Key or part of it can not be null) - this rule
says that 'null' is special value in a relational database and it doesn't mean
blank or zero. It means the unavailability of data and hence a 'null' primary ke
y would not be a complete identifier. This integrity rule is also termed as enti
ty integirty.
* Referential Integrity - this rule says that if a foreign key is defined on
a table then a value matching that foreign key value must exist as th e primary
key of a row in some other table.
=================================================================
What is Cloning? How clone() method works in Java?

What is the role of the clone() method in Java?


protected Object clone() throws CloneNotSupportedException - this method is used
to create a copy of an object of a class which implements Cloneable interface.
By default it does field-by-field copy as the Object class doesn't have any idea
in advance about the members of the particular class whose objects call this me
thod. So, if the class has only primitive data type members then a completely ne
w copy of the object will be created and the reference to the new object copy wi
ll be returned. But, if the class contains members of any class type then only t
he object references to those members are copied and hence the member references
in both the original object as well as the cloned object refer to the same obje
ct.
Cloneable interface
We get CloneNotSupportedException if we try to call the clone() method on an obj
ect of a class which doesn't implement the Cloneable interface. This interface i
s a marker interface and the implementation of this interface simply indicates t
hat the Object.clone() method can be called on the objects of the implementing c
lass.
Example: how cloning works in Java?
Class A {
...
}
A objA = new A();
A objACloned = (A) objA.clone();
Now, objA != objACloned - this boolean expression will always be true as in any
case a new object reference will be created for the cloned copy.
objA.getClass() == objACloned.getClass() - this boolean expression will also be
always true as both the original object and the cloned object are instances of t
he same class (A in this case).
Initially, objA.equals(objACloned) will return true, but any changes to any prim
itive data type member of any of the objects will cause the expression to return
false. It's interesting to note here that any changes to the members of the obj
ect referenced by a member of these objects will not cause the expression to ret
urn false. Reason being, both the copies are referring to same object as only th
e object references get copied and not the object themselves. This type of copy
is called Shallow Copy (Read Next - Deep Copy vs Shallow Copy >> You may browse
the links given in that article to go through various aspects of Cloning in Java
). This can be understood easily by looking at the following memory diagram:-
=================================================================
WSDL - Web Services Description Language

WSDL - Web Services Description Language

You may like to refresh your understanding of the Web Services by going through
this article - Web Services - What, Why, Usage, & Shortcomings>>

The WSDL (Web Services Description Language) is a grammar which uses XML for des
cribing all the details of a Web Service which a consumer may like to have for u
sing that Web Service. These details are:-
* Message Exchanges - this is used to define the input and out message excha
nges between the Web Service and the Consumer. Why to use a new language for it?
Can't we use XML Schema to define such message exchanges? No... the XML Schema
is not capable of describing it. Take one example to understand it - suppose you
have two XML elements RequestMessage and ResponseMessage and if you want to spe
cify that if the Consumer sends the RequestMessage then it will get the Response
Message. Now in this case XML Schema can't be used as it's not capable of descri
bing the relation between the XML Elements. WSDL uses the concept of 'operations
' to describe such a situation.
* Grouping of similar operations into interfaces - WSDL helps grouping simil
ar operations into interfaces which can be mapped to the programmatic interfaces
in object-oriented languages.
* Binding Specification - binding is actually a combination of an interface
and the communication protocol and it's used to specify the concrete details of
what actually travels on the wire. In addition to the interfaces and communicati
on protocol, the binding is influenced by the Style of the Service (which can ei
ther be 'document' or 'RPC') and by the Encoding Mechanism (which can either be
'literal' or 'encoded'). For one interface we may have multiple binding for the
simple reason that a binding is a combination of the interface and the communica
tion protocol. So for the same interface we may have different bindings for TCP,
HTTP, SMTP, etc. communication protocols. For every binding there will be a dis
tinct URI each of which can be used to consume the Web Service.

In a nutshell we can say that WSDL uplifts the capabilities of XML Schema by pro
viding a way of describing the message exchanges in form of operations and by pr
oviding a way of grouping similar operations into interfaces. It also facilitate
s the specification of the particular communication protocol, style, and encodin
g mechanism used by the Web Service. Every combination of the interface and comm
unication protocol is represented by a binding and every binding will have a dis
tinct URI. That means the same service may be consumed by using different commun
ication protocols by simply using the corresponding URIs.

There are other techniques for describing the Web Services, but WS-I Basic Profi
le v1.0 makes it mandatory to use the WSDL and XML Schema for describing any Web
Service. This ensures the interoprability at the service description layer.

A WSDL document is simply an XML document and hence it's quite easier for the de
veloper to read, interpret and generated the code to consume the Web Service. We
have many tools available by reputed vendors which can be directly used to cons
ume any Web Service.

WSDL 1.1 is was being used as a de-facto standard until mid of the year 2007 whe
n W3C came up with WSDL 1.2 which is more commonly known as WSDL 2.0 and the too
ls and infrastructure developers have already started following this version.
The entire WSDL Schema can be found here - WSDL Schema.
WSDL Elements

Find below the elements of a typical WSDL document:-

* types - this element is used to define an abstract type which will be used
by the XML Schema.
* message - this element is used to define an abstract message and it may co
nsist of multiple parts where each part may be of different type - either a buil
t-in type or an abstract type defined by the 'types' element.
* portType - this element is used to define the interface by grouping simila
r operations together. As discussed above, one interface may be combined with mu
ltiple communication protocols to form different end-points (URIs) of the same s
ervice.
* binding - this element is used to specify the details of the communication
protocol, style of service, and encoding mechanism for the particular URI (end-
point) of a particulat portType element. One binding element is used to complete
ly describe one URI for a particular portType element and hence one portType ele
ment may have multiple binding elements to have as many different end-points.
* service - this element is used to represent a collection of ports. A port
is given a name and a binding is assigned to it which this port will expose. Now
every port is given an URL which is used to access the service. Now if we have
more than one binding element for the same portType element then we can simply h
ave as many port elements in the serive element and assign all these port elemen
ts a distinct URL. The associated binding element for any URL will determine whi
ch communication protocol to consume the service will be used in that case.
Now that you know what all elements a WSDL doc may have and what these elements
actually mean, check this Sample WSDL Document and try to identify and co-relate
all the elements of it.
=================================================================
Difference between Shallow Copy and Deep Copy

Shallow Copy
This is a result of the default cloning functionality provided by the Object.clo
ne() method if the class has non-primitive data type members as well. Shallow Co
py concept is not applicable to the classes having only primitive data type memb
ers as in that case the default cloning will also result into a Deep Copy only.
In case of Shallow Copy, the cloned object also refers to the same object to whi
ch the original object refers as only the object references gets copied and not
the referred objects themselves. That's why the name Shallow Copy. Read more abo
ut Cloning and see the memory diagram to understand it better - Cloning in Java
>>
Deep Copy
We need to override the clone() method for the classes having non-primitive type
members to achieve Deep Copy as Deep Copy requires the member objects to be clo
ned as well, which is not done by the default cloning mechanism. Why is it not d
one by the default cloning? Because clone() is a method of the Object class and
at that level it's not known what a typical class can have as its members and he
nce only a field-by-field copy approach has been provided as the default cloning
mechanism.
Implementing Deep Copy in Java
For Deep Copy, we need to ensure that the member classes also implement the Clon
eable interface otherwise calling the clone() method on the objects of those cla
sses will result into CloneNotSupportedException. So, to implement Deep Copy, we
first need to ensure that all the member classes (at all the levels - like if t
he member class itself has a member of some class type then that class as well..
. and so on) are implementing the Cloneable interface. After that we override th
e clone() method in all those classes (even in the classes where we have only pr
imitive type members otherwise we would not be able to call the protected clone(
)method of Object class on the instances of those classes inside some other clas
s ... a typical restriction of the protected access. We'll cover this in a separ
ate article) and finally calling clone() method on the object members in the ove
rriden clone() method definition. See the Java source Code (for a sample impleme
ntation by overriding clone() method) here - Deep Copy Implementation in Java >>
=================================================================
How to tune SQL Queries for better performance?

Performance tuning of SQL Queries


Note: One of our visitors, Amit asked this question by posting a comment. Thanks
Amit for your contribution. Keep visiting/posting!
Performance of the SQL queries of an application often play a big role in the ov
erall performance of the underlying application. The response time may at times
be really irritating for the end users if the application doesn't have fine-tune
d SQL queries. There are sevaral ways of tuning SQl statements, few of which are
:-
* Understanding of the Data, Business, and Application - it's almost impossi
ble to fine-tune the SQl statements without having a proper understanding of the
data managed by the application and the business handled by the application. Th
e understanding of the application is of course of utmost importance. By knowing
these things better, we may identify several instances where the data retrieval
/modification by many SQL queries can simply be avoided as the same data might b
e available somewhere else, may be in the session of some other integrating appl
ication, and we can simply use that data in such cases. The better understanding
will help you identify the queries which could be written better either by chan
ging the tables involved or by establishing relationships among available tables
.
* Using realistic test data - if the application is not being tested in the
development/testing environments with the volume and type of data, which the app
lication will eventually face in the production environment, then we can't be ve
ry sure about how the SQL queries of the application will really perform in actu
al business scenarios. Therefore, it's important to have the realistic data for
development/testing purposes as well.
* Using Bind Variables, Stored Procs, and Packages - Using identical SQL sta
tements (of course wherever applicable) will greatly improve the performance as
the parsing step will get eliminated in such cases. So, we should use bind varia
bles, stored procedures, and packages wherever possible to re-use the same parse
d SQL statements.
* Using the indexes carefully - Having indexes on columns is the most common
method of enhancing performance, but having too many of them may degrade the pe
rformance as well. So, it's very critical to decide wisely about which all colum
ns of a table we should create indexes on. Few common guidelines are:- creating
indexes on the columns which are frequently used either in WHERE clause or to jo
in tables, avoid creating indexes on columns which are used only by functions or
operators, avoid creating indexes on the columns which are required to changed
quite frequently, etc.
* Making available the access path - the optimizer will not use an access pa
th that uses an index only because we have created that index. We need to explic
itly make that access path available to the optimizer. We may use SQL hints to d
o that.
* Using EXPLAIN PLAN and TKPROF - these tools can be used to fine tune SQL q
ueries to a great extent. EXPLAIN PLAN explains the complete access path which w
ill be used by the particular SQL statement during execution and the second tool
TKPROF displays the actual performance statistics. Both these tools in combinat
ion can be really useful to see, change, and in turn fine-tune the SQL statement
s.
* Optimizing the WHERE clause - there are many cases where index access path
of a column of the WHERE clause is not used even if the index on that column ha
s already been created. Avoid such cases to make best use of the indexes, which
will ultimately improve the performance. Some of these cases are: COLUMN_NAME IS
NOT NULL (ROWID for a null is not stored by an index), COLUMN_NAME NOT IN (valu
e1, value2, value3, ...), COLUMN_NAME != expression, COLUMN_NAME LIKE'%pattern'
(whereas COLUMN_NAME LIKE 'pattern%' uses the index access path), etc. Usage of
expressions or functions on indexed columns will prevent the index access path t
o be used. So, use them wisely!
* Using WHERE instead of HAVING - usage of WHERE clause may take advantage o
f the index defined on the column(s) used in the WHERE clause.
* Using the leading index columns in WHERE clause - the WHERE clause may use
the complex index access path in case we specify the leading index column(s) of
a complex index otherwise the WHERE clause won't use the indexed access path.
* Indexed Scan vs Full Table Scan - Indexed scan is faster only if we are se
lcting only a few rows of a table otherwise full table scan should be preferred.
It's estimated that an indexed scan is slower than a full table scan if the SQL
statement is selecting more than 15% of the rows of the table. So, in all such
cases use the SQL hints to force full table scan and suppress the use of pre-def
ined indexes. Okay... any guesses why full table scan is faster when a large per
centage of rows are accessed? Because an indexed scan causes multiple reads per
row accessed whereas a full table scan can read all rows contained in a block in
a single logical read operation.
* Using ORDER BY for an indexed scan - the optimizer uses the indexed scan i
f the column specified in the ORDER BY clause has an index defined on it. It'll
use indexed scan even if the WHERE doesn't contain that column (or even if the W
HERE clause itself is missing). So, analyze if you really want an indexed scan o
r a full table scan and if the latter is preferred in a particular scenario then
use 'FULL' SQL hint to force the full table scan.
* Minimizing table passes - it normally results in a better performance for
obvious reasons.
* Joining tables in the proper order - the order in which tables are joined
normally affects the number of rows processed by that JOIN operation and hence p
roper ordering of tables in a JOIN operation may result in the processing of few
er rows, which will in turn improve the performance. The key to decide the prope
r order is to have the most restrictive filtering condition in the early phases
of a multiple table JOIN. For example, in case we are using a master table and a
details table then it's better to connect to the master table first to connecti
ng to the details table first may result in more number of rows getting joined.
* Simple is usually faster - yeah... instead of writing a very complex SQL s
tatement, if we break it into multiple simple SQL statements then the chances ar
e quite high that the performance will improve. Make use of the EXPLAIN PLAN and
TKPROF tools to analyze both the conditions and stick to the complex SQL only i
f you're very sure about its performance.
* Using ROWID and ROWNUM wherever possible - these special columns can be us
ed to improve the performance of many SQL queries. The ROWID search is the faste
st for Oracle database and this luxury must be enjoyed wherever possible. ROWNUM
comes really handy in the cases where we want to limit the number of rows retur
ned.
* Usage of explicit cursors is better - explicit cursors perform better as t
he implicit cursors result in an extra fetch operation. Implicit cursosrs are op
ened the Oracle Server for INSERT, UPDATE, DELETE, and SELECT statements whereas
the explicit cursors are opened by the writers of the query by explicitly using
DECLARE, OPEN, FETCH, and CLOSE statements.
* Reducing network traffic - Arrays and PL/SQL blocks can be used effectivel
y to reduce the network traffic especially in the scenarios where a huge amount
of data requires processing. For example, a single INSERT statement can insert t
housands of rows if arrays are used. This will obviously result into fewer DB pa
sses and it'll in turn improve performance by reducing the network traffic. Simi
larly, if we can club multiple SQL statements in a single PL/SQL block then the
entire block can be sent to Oracle Server involving a single network communicati
on only, which will eventually improve performance by reducing the network traff
ic.
* Using Oracle parallel query option - Since Oracle 8, even the queries base
d on indexed range scans can use this parallel query option if the index is part
itioned. This feature can result in an improved performance in certain scenarios
.
=================================================================
Limitations of Java language

GUI: the look and feel of the Graphical User Interfaces written in Java using Sw
ing may not be the same as the widget look and feel of the underlying operating
system. For example, on almost every Windows system, the Swing look & feel diffe
r significantly from the GUI look and feel of the native applications. One possi
ble solution is AWT, but it has its own limitations regarding the support of hig
h-end widgets.

Floating point Arithmetic: Java largely supports IEEE 754 floating point arithme
tic, but certain features are not supported even with the use of the ‘strictfp’ modi
fier in Java. For example, IEEE 754 recommends Exception Flags and Directed Roun
dings, but these features are not supported in Java.

Bytecode: while bytecodes make Java a portable language to a great extent, they
cause the performance to slow down to a certain extent as well. If you use Java
Interpreter while running the bytecodes on a certain JVM, then it’s considerably s
lower than the usual native code execution on that platform as the process adds
an extra phase of translation of the bytecode instruction into the corresponding
native code instruction. If we use JIT compiler to convert entire bytecodes int
o native code during load time or runtime, then also it incurs an initial penalt
y for the completion of the compilation. So, JIT compilation may be inconvenient
especially for those applications which are either short-lived or which contain
large amount of code. In the first case, the penalty will be too frequent while
in the latter case, the penalty will be one time only, but this initial penalty
will be huge :-)

Automatic memory management: Java uses the automatic garbage collector to handle
all the memory management and the programmer has no control on it. Even, the ex
ecution of the garbage collection can not be controlled by the programmer. Syste
m.gc() will only result in a possible increment of the priority of the next garb
age collection execution and that too is dependent on the particular J2EE implem
entation as the specification mandates nothing regarding this. If you deliberate
ly want to free some important system resources like DB Connection, File Handles
, etc. then you’re helpless and you got to rely on the sporadic execution of the g
arbage collection to do that for you. If you have enough system resources then y
ou may not mind this, but in a crunch situation you’ll certainly not appreciate th
is limited/no control on memory management.
Different JVM for different platform: this is what makes Java a portable languag
e, which is undoubtedly one of the major reasons for the popularity of Java, but
it has its own share of limitations as well. Most of the implementations usuall
y follow all the specifications, but they add certain implementation-specific fl
avors as well. If you somehow use any of those features then you compromise with
the portability of your code. Even worse, your implementation may not be up-to-
date with the latest specifications as well and this will cause compatibilities
issues for the code written on an updated implementation. Having an implementati
on lagging in years with other popular implementations is not that bizarre eithe
r :-)
Being too strict may bother you: Java, being a strictly type-safe language, may
pose certain problems to your comfort level with other languages which are compa
ratively generous. Automatic bounds checking for arrays, automatic virtual funct
ion indirection, run-time type checking, etc. may add little more inconvenience
especially when you’re trying to prototype sample applications/modules/programs ju
st to check certain functionality or maybe just to try and find few solution app
roaches to choose the best from. Extensive exception handling (usually a boon fo
r the developers) will require you to write many lines of extra code for the suc
cessful compilation of the program. This may bother you while writing test-code/
prototype.

Read more - Why Java doesn t have Clear Screen functionality? This article tries
to explain why we can t have such functionalities in Java. It covers Java 6 upd
ates as well.
=================================================================
Difference between Shallow Copy and Deep Copy

Shallow Copy
This is a result of the default cloning functionality provided by the Object.clo
ne() method if the class has non-primitive data type members as well. Shallow Co
py concept is not applicable to the classes having only primitive data type memb
ers as in that case the default cloning will also result into a Deep Copy only.
In case of Shallow Copy, the cloned object also refers to the same object to whi
ch the original object refers as only the object references gets copied and not
the referred objects themselves. That s why the name Shallow Copy. Read more abo
ut Cloning and see the memory diagram to understand it better - Cloning in Java
>>
Deep Copy
We need to override the clone() method for the classes having non-primitive type
members to achieve Deep Copy as Deep Copy requires the member objects to be clo
ned as well, which is not done by the default cloning mechanism. Why is it not d
one by the default cloning? Because clone() is a method of the Object class and
at that level it s not known what a typical class can have as its members and he
nce only a field-by-field copy approach has been provided as the default cloning
mechanism.
Implementing Deep Copy in Java
For Deep Copy, we need to ensure that the member classes also implement the Clon
eable interface otherwise calling the clone() method on the objects of those cla
sses will result into CloneNotSupportedException. So, to implement Deep Copy, we
first need to ensure that all the member classes (at all the levels - like if t
he member class itself has a member of some class type then that class as well..
. and so on) are implementing the Cloneable interface. After that we override th
e clone() method in all those classes (even in the classes where we have only pr
imitive type members otherwise we would not be able to call the protected clone(
)method of Object class on the instances of those classes inside some other clas
s ... a typical restriction of the protected access. We ll cover this in a separ
ate article) and finally calling clone() method on the object members in the ove
rriden clone() method definition. See the Java source Code (for a sample impleme
ntation by overriding clone() method) here - Deep Copy Implementation in Java >>
=================================================================
Why Java does not have Clear Screen functionality?

Why Java does not have Clear Screen functionality?

Clear Screen functionality has not been implemented in Java as it s simply not p
ossible without sacrificing Platform Independence. So, how to handle a situation
asking this? Well... Java has not been designed to develop applications requiri
ng a direct console based interaction. You may think of using Swing or AWT based
GUI instead. It s not impossible to have such a functionality in Java, but cert
ainly not portable and hence not preferrable. We do have few platform dependent
workarounds to achieve it in Java and the best among the lot still remains the s
ame - using JNI.

In Java, we don t have the concept of a typical console as we have in C/C++. Ins
tead all I/O in Java is stream-based. I don t think Clear Screen can be implemen
ted for a stream as the steam may point to a file, a printer (it will be a reall
y challenging scenario, isn t it?), or may be to a console on certain platforms.
Since, you never know what this stream would be pointing to at run time, you ca
n t assume it to be a console in all the cases and hence can not have that funct
ionality. Clear Screen will obviously make sense only for clearing the console a
nd not for a file (logs etc.).

System.out.println() is far more easier to implement in all environments maintai


ning platform independence as irrespective of what the stream points to at runti
me, it can always be written on. This holds true for C/C++ as well. And probably
this is the reason why printf() works fine in all environments in case of C/C
++ (Now in Java also ... Java 5.0 onwards) and not clrscr() .

C++ also has the concept of Streams similar to that in Java and I think Clear Sc
reen function is not a part of any class based on streams. It s a separate metho
d altogether and it has a specific implementation only for those environments wh
ich have the concept of Console. For different platforms we may need to look for
different vendor specific extension to have that functionality even in case of
C/C++. For instance, Turbo C/C++ has the function clrscr() in the vendor speci
fic header file conio.h . We don t have that header file available for Linux pl
atform.
Similar explanation can be given for other platform dependent tasks such as acc
epting input without ENTER being pressed - a functionality getch() provides in C
/C++ , applying font color, background color, etc. on the console , and so on.
Such tasks have not been implemented consistently across all platforms even in C
/C++, so forget about Java. The goals of Java will probably never allow such tas
ks to be implemented not at least by using standard library functions. You got t
o use platform-dependent vendor specific packages to achive them unless of cours
e, all the environments start following the same standards for console and other
related stuff.

I thank Lavnish (one of our regular visitors) for raising this point in response
to the post on Limitations of Java Language . He runs a blog and writes freque
ntly on Java. You can find his post on the Clear Screen functionality here. I ho
pe our visitors will continue chipping in with their valuable comments and makin
g this place better and better for us.

Update from Java 6.0

Java 6.0 has gone C/C++ way to facilitate better interaction with character-base
d console devices by using standard library functions. It seems that it wasn t p
ossible for them to have such features for traditional Java Streams and hence th
ey created a new Java Class named java.io.Console. This Class is mainly for read
ing from and writing to the Console and not for clearing it (as of now).

The Sun Java Doc of this class clearly says that the class contains methods to a
ccess the character-based console device, if any, associated with the current JV
M. We can obviously see a compromise with Platform Independence here as the code
written using this Class can never be guaranteed to behave uniformly across all
platforms and hence not portable. System.console() method simply returns null
on the platforms which doesn t have an associated Console with the underlying J
VM.

On the platforms where it finds a Console, it probably uses JNI internally to ge


t the task done. We always have such solutions provided by third party vendors a
nd the only good thing about the addition of this new class is probably that it
s now a part of the standard library and it might be having little more efficien
t code than the code supplied by the third party vendors.

BTW, the center of our discussion Clear Screen functionality is still not ther
e in this class. Let s see if at all they provide that also in the newer release
s of Java.

The bottom line remains the same - we would probably never have any such functio
nality without compromising Platform Independence and in most of the cases the A
PIs would probably be using JNI only. A true Java solution to this problem still
remains a topic of research.
=================================================================
Constant Field Values
Contents
* javax.servlet.*
javax.servlet.*
javax.servlet.http.HttpServletRequest
public static final java.lang.String BASIC_AUTH "BASIC"
public static final java.lang.String CLIENT_CERT_AUTH "CLIENT_CERT"
public static final java.lang.String DIGEST_AUTH "DIGEST"
public static final java.lang.String FORM_AUTH "FORM"
javax.servlet.http.HttpServletResponse
public static final int SC_ACCEPTED 202
public static final int SC_BAD_GATEWAY 502
public static final int SC_BAD_REQUEST 400
public static final int SC_CONFLICT 409
public static final int SC_CONTINUE 100
public static final int SC_CREATED 201
public static final int SC_EXPECTATION_FAILED 417
public static final int SC_FORBIDDEN 403
public static final int SC_GATEWAY_TIMEOUT 504
public static final int SC_GONE 410
public static final int SC_HTTP_VERSION_NOT_SUPPORTED 505
public static final int SC_INTERNAL_SERVER_ERROR 500
public static final int SC_LENGTH_REQUIRED 411
public static final int SC_METHOD_NOT_ALLOWED 405
public static final int SC_MOVED_PERMANENTLY 301
public static final int SC_MOVED_TEMPORARILY 302
public static final int SC_MULTIPLE_CHOICES 300
public static final int SC_NO_CONTENT 204
public static final int SC_NON_AUTHORITATIVE_INFORMATION 203
public static final int SC_NOT_ACCEPTABLE 406
public static final int SC_NOT_FOUND 404
public static final int SC_NOT_IMPLEMENTED 501
public static final int SC_NOT_MODIFIED 304
public static final int SC_OK 200
public static final int SC_PARTIAL_CONTENT 206
public static final int SC_PAYMENT_REQUIRED 402
public static final int SC_PRECONDITION_FAILED 412
public static final int SC_PROXY_AUTHENTICATION_REQUIRED 407
public static final int SC_REQUEST_ENTITY_TOO_LARGE 413
public static final int SC_REQUEST_TIMEOUT 408
public static final int SC_REQUEST_URI_TOO_LONG 414
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE 416
public static final int SC_RESET_CONTENT 205
public static final int SC_SEE_OTHER 303
public static final int SC_SERVICE_UNAVAILABLE 503
public static final int SC_SWITCHING_PROTOCOLS 101
public static final int SC_TEMPORARY_REDIRECT 307
public static final int SC_UNAUTHORIZED 401
public static final int SC_UNSUPPORTED_MEDIA_TYPE 415
public static final int SC_USE_PROXY 305
javax.servlet.jsp.JspWriter
public static final int DEFAULT_BUFFER -1
public static final int NO_BUFFER 0
public static final int UNBOUNDED_BUFFER -2
javax.servlet.jsp.PageContext
public static final java.lang.String APPLICATION "javax.servlet.jsp.jspAp
plication"
public static final int APPLICATION_SCOPE 4
public static final java.lang.String CONFIG "javax.servlet.jsp.jspConfig"
public static final java.lang.String EXCEPTION "javax.servlet.jsp.jspEx
ception"
public static final java.lang.String OUT "javax.servlet.jsp.jspOut"
public static final java.lang.String PAGE "javax.servlet.jsp.jspPage"
public static final int PAGE_SCOPE 1
public static final java.lang.String PAGECONTEXT "javax.servlet.jsp.jspPa
geContext"
public static final java.lang.String REQUEST "javax.servlet.jsp.jspRe
quest"
public static final int REQUEST_SCOPE 2
public static final java.lang.String RESPONSE "javax.servlet.jsp.jspRe
sponse"
public static final java.lang.String SESSION "javax.servlet.jsp.jspSe
ssion"
public static final int SESSION_SCOPE 3
javax.servlet.jsp.tagext.BodyTag
public static final int EVAL_BODY_BUFFERED 2
public static final int EVAL_BODY_TAG 2
javax.servlet.jsp.tagext.IterationTag
public static final int EVAL_BODY_AGAIN 2
javax.servlet.jsp.tagext.Tag
public static final int EVAL_BODY_INCLUDE 1
public static final int EVAL_PAGE 6
public static final int SKIP_BODY 0
public static final int SKIP_PAGE 5
javax.servlet.jsp.tagext.TagAttributeInfo
public static final java.lang.String ID "id"
javax.servlet.jsp.tagext.TagInfo
public static final java.lang.String BODY_CONTENT_EMPTY "EMPTY"
public static final java.lang.String BODY_CONTENT_JSP "JSP"
public static final java.lang.String BODY_CONTENT_TAG_DEPENDENT "TAGDEPE
NDENT"
javax.servlet.jsp.tagext.VariableInfo
public static final int AT_BEGIN 1
public static final int AT_END 2
public static final int NESTED 0
=================================================================
Servlet "how to"
Q: Can I catch an exception and give my own error message?
A: Yes, you can catch servlet errors and give custom error pages for them, b
ut if there are exceptional conditions you can anticipate, it would be better fo
r your application to address these directly and try to avoid them in the first
place.
Premium Content: Follow this link for subscription information More details
available to subscribers:
Can I catch an exception and give my own error message?
Q: How do I include files in my servlet?
A: To achieve an include scheme in a servlet, use javax.servlet.RequestDispa
tcher, which takes the path of the target document in its constructor. A Request
Dispatcher can be obtained from the ServletContext object (via ServletConfig) in
your servlet s init method, or from ServletRequest or HttpServletRequest in doG
et or doPost.
Q: Can I call the doPost() method from a hyperlink?
A: Following a hyperlink in a Web document normally creates an HTTP GET requ
est to the given URL, not a POST request. Post requests are normally produced by
the submission of an HTML form whose method attribute is post. In this case any
values given in the form s input elements are passed as request parameters to t
he URL specified in the form s action attribute.
Premium Content: Follow this link for subscription information More details
available to subscribers:
Can I call the doPost() method from a hyperlink?
Q: How can I display system properties in a servlet?
A: You can obtain the operating system, operating system version and Java ve
rsion for a servlet container through standard Java system properties. There is
a wide range of standard properties that can be obtained from the static System
class method getProperty(String), using the following keys:
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String javaVersion = System.getProperty("java.version");

These system properties are common to all Java runtime systems including ser
vlets.
Q: Should I use a static variable or Hashtable to store a list of strings?
A: The static modifier for a variable is different from the object type of t
he variable. If you want all servlet instances to be able to read and write data
to a field, it should be static. Depending on the nature of the application, it
may also be necessary to synchronize access to the variable.
If you want to store a simple list of strings, a java.util.List type variabl
e would be most appropriate. A Vector is a List type and its implementation is s
ynchronized.
private static final List stringList = new Vector();

Using request information


Q: How can I enable users to upload a file?
A: A file upload servlet should control what type of files are permitted, to
process the byte stream and decide where the content is stored. As you can imag
ine, allowing anybody to upload any file to your Web server is a significant sec
urity hazard, so you must be very careful to ensure that you restrict who has ac
cess, what they upload, and that the public do not have arbitrary access to the
file via the Internet.
The Apache commons file upload package would be a good place to start.
Q: How do I limit the file upload size?
A: This example code is for the Apache commons file upload package.
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);

Q: Can I get the client IP and MAC address?


A: The ServletRequest type has a getRemoteAddr() method that returns the Int
ernet Protocol (IP) address of the client that made the request. The address is
returned as a String, so must be parsed further if you want to extract numeric r
eferences from it. In JSP you can access this method it directly through the req
uest variable, as below.
Premium Content: Follow this link for subscription information More details
available to subscribers:
Can I get the client IP and MAC address?
Q: How do I get the server port number for redirected requests?
A: If your servlet container is listening on port 8080 then the HttpServletR
equest getServerPort() method will return the int 8080.
Process parameters
Q: How can I check what parameters are available in the request?
A: There are two main approaches to checking request parameters: either look
up named parameters you expect to be present, or iterate through all parameters
. It is always possible there is more than one value for each named parameter, s
o look up values using the getParameterValues(String) method, which takes the na
me of the parameter as an argument and returns a string array. You need to decid
e what should happen if there is more than one value, this example takes the fir
st value in the array.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I check what parameters are available in the request?
Q: How do I get parameter values from a form submission?
A: The simple form below invites people to input their name.
<form
action="http://www.codestyle.org/servlets/EchoRequest">
<input
type="text"
name="name" />
<input
type="submit" />
</form>

To handle this submission, extend HttpServlet and provide a doPost(HttpServl


etRequest, HttpServletResponse) method, as below.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How do I get parameter values from a form submission?
Q: The & in the parameter value truncates the string!
A: To pass non-ASCII characters in servlet parameters without them being int
erpreted as part of the URL structure, you must encode the characters as hexadec
imal (base 16) values prefixed by the percent symbol, %. This is known as URL-en
coding and is normally done automatically by Web browsers when you submit a form
. For instance, ampersand is ASCII character number 38, which is %26 expressed a
s a hexadecimal. See the table below for other conversion values.
Premium Content: Follow this link for subscription information More details
available to subscribers:
The & in the parameter value truncates the string!
Q: How can I tell which submit button was activated?
A: In design terms, it is not a good idea for your application to have diffe
rent outcomes from equivalent actions unless the consequences are quite clear to
the person using the form. This is especially important for people with impaire
d vision, or those using screen readers.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I tell which submit button was activated?
Q: Which link was followed to request my servlet?
A: You should not rely upon the HTTP referer (sic) header to be sent to your
servlet because some Web browsers (and other client types) do not send them for
privacy reasons.
Premium Content: Follow this link for subscription information More details
available to subscribers:
Which link was followed to request my servlet?
Integration methods
Q: How can I make the servlet output open in Microsoft Excel?
A: The binary file format of Microsoft Excel documents is extremely complex.
If you want to reproduce this format in detail and with precision you should re
ad OpenOffice.org s Documentation of the Microsoft Excel File Format.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I make the servlet output open in Microsoft Excel?
Q: How can I show my HTML markup as plain text?
A: To display HTML output in plain text format, you must set the HTTP Conten
t-Type header to text/plain, as below:
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I show my HTML markup as plain text?
Q: How can I fix the Javascript in my servlet?
A: It can be very tricky inserting inline Javascript in servlet output becau
se of the level of quoted output escaping that can be necessary. If you miss or
fail to correctly escape a literal quote, your Javascript will not parse correct
ly. For simplicity, it would be preferable to use an external Javascript file.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I fix the Javascript in my servlet?
Q: How do I include CSS in my servlet?
A: It is best to use an external stylesheet reference, so that you can edit
your servlet and CSS rules independently.
Premium Content: Follow this link for subscription information More details
available to subscribers:
How do I include CSS in my servlet?
Q: How can I pass user input through my spelling checker?
A: create an instance of your SpellChecker class in the doGet() or doPost()
method of your servlet and pass the relevant parameter to it as a string, as in
the code sample below ...
Premium Content: Follow this link for subscription information More details
available to subscribers:
How can I pass user input through my spelling checker?
Q: How do I send data from an applet to a servlet?
A: The applet sandbox security environment only permits connections with the
host from which the applet was loaded. If you attempt a connection with a diffe
rent host, the applet will throw a SecurityException and fail. This can also cau
se problems when you are testing an applet loaded from the local file system, wh
ich has no host.
=================================================================
What s JSP? Life Cycle of JSP (JavaServer Pages)
JSP (JavaServer Pages) - what is it?
JSP is a technology which enables the generation of dynamic web contents for a t
ypical web application by separating the user interface generation from the actu
al content generation. This separation helps the page designers and content deve
lopers to do their respective tasks without interfering with each other. JSP can
also be extended by adding Custom Tag Libraries to it.
A JSP page is just like a HTML web page that contains (strictly speaking we shou
ld say that may contain as a plain static HTML page can also be saved as with
a .jsp extension to make it a JSP page, but that s seldom used) additional piece
s of code responsible for dynamic content generation. This additional code can u
tilize many Java APIs including JavaBeans, JDBC, EJB, and RMI for building the d
ynamic content. HTML part of the JSP page provides the layout in which the dynam
ically generated content is displayed.
Life Cycle of JSP (JavaServer Pages)
A JSP page is first converted into a Servlet and then that Servlet gets compiled
and executed like any other Servlet. The translation of a JSP page into the cor
responding Servlet is done by the JSP Engine of the underlying Web Container. Th
e entire life cycle of a typical JSP page can be summarized as the following pha
ses:-
* Translation - In this phase the JSP page is translated into the correspond
ing Servlet. This translated Servlet is different from a normal Servlet only in
the sense that it implements the interface javax.servlet.jsp.HttpJspPage. Well..
. if you look at this interface closely, you ll easily notice that a translated
JSP page implements this interface just to have the JSP specific features. This
HttpJspPage is just a wrapper of the Servlet interface as HttpJspPage interface
extends the JspPage interafce and the JspPage interface extends the javax.servle
t.Servlet interface. Thus, we see that the translated Servlet also internally im
plements the javax.servlet.Servlet interface (otherwise we would not have called
it a servlet). In addition it implements few more interfaces to support the JSP
technology.
* Compilation - Once the JSP page has been translated into the corresponding
Servlet, the next obvious step is to compile that Servlet.
* Loading & Instantiation - As is the case with any compiled class (.class f
ile), this servlet class also needs to be loaded into the memory before being us
ed. The default classloader of the Web Conatiner will loads this class. Once the
class is loaded, an instance of this class gets created. JspPage interaface con
tains the jspInit() method, which is used by the JSP Engine to initialize the ne
wly created instance. This jspInit() method is just like the init() method of th
e Servlet and it s called only once during the entire life cycle of a JSP/Servle
t.
* Servicing Requests - _jspService() is the method which is called every tim
e the JSP is requested to serve a request. This method normally executes in a se
parate thread of execution (provided we have selected Single Thread Model for th
e JSP) and the main JSP thread keeps waiting for other incoming requests. Every
time a request arrives, the main JSP thread spawns a new thread and passes the r
equest (incoming request) and response (new) objects to the _jspService() method
which gets executed in the newly spawned thread.
* Unloading - jspDestroy() method is called (almost always by the Web Contai
ner... Read a related article on why a JSP/Servlet writer shouln t call this met
hod explicitly - Calling destroy() from init() in a Servlet >>) before the Web C
ontainer unloads the JSP instance. We normally keep code responsible for resourc
e-reclaimation or clean-up activities in this method. After the execution of the
jspDestroy() method, the JSP instance is marked for the garbage collection and
the occupied memory is eventually reclaimed.
=================================================================
Modular Response-Writers - how can we have them in Servlets?

Question: Modular Response-Writers - how can we have them in Servlets?

Answer: Before discussing how can we achieve this in a Servlet, let s discuss th
e need of such a thing. An example scenario - suppose someone wants to build the
header, body, side-bar, and footer components of his site in four separate serv
lets. In such a case he will need to have a mechanism of combining the responses
created by all the four servlets to build the final response, which will ultima
tely be sent to the client browser. The concept of modular response-writers come
s as a rescue in such situations.

Forming a response object by using multiple servlets require a servlet writer to


pick one of the two pissible alternatives:-
* Using JavaBeans or Java methods - we may use multiple JavaBeans or call mu
ltiple Java methods to build the final HTML response.
* Using RequestDispatcher.include() - Unlike forward() method, include() met
hod just brings the output of the included servlet and the output is simply appe
nded to the current response object of the calling servlet (also called the mast
er servlet). So, we can include() as many servlets as we want and have the outpu
ts appended to the response of the calling servlet to build the final response.
This final response will ultimately be sent to the client by the master servlet.

Servlets 2.3 came up with a new concept called Filters. This may also be used as
an alternative to build response from multiple servlets, but it s generally not
used for this purpose as Filters haven been introduced to the Servlet Specifica
tion for a different purpose and using them as an alternative in such a scenario
makes the implementation quite complex and at times little ambiguous as well.
=================================================================
How many ways of creating objects in Java?

Well... there aren t many different ways I suppose. But from an application prog
rammer perspective here are the different possible ways of creating objects in J
ava:-
* Using new operator - the most commonly used way by far. new is an operat
or and the only operand it requires is a constructor which will be used for init
ializting the newly created instance. new operator allocates the memory space
and initializes the fields with their default values. Then it executes the code
inside the specified constrcutor which normally re-writes the default values of
some (or all) fields with the particular values mentioned in the constructor def
inition.
* Using clone() method - Cloning (Shallow or Deep) makes a new copy of the s
pecified object. It doesn t call the new operator internally. Object.clone() i
s a native method which translates into instructions for allocating the memory a
nd copying the data. Remember that even if we override the clone() method either
to implement Deep Cloning or to make the clone() method as public but then al
so we keep the line super.clone() inside the overriden definition which ultimate
ly calls Object.clone() method only. You might wonder about what the new opera
tor actually translates into and how this approach is different from that. Okay.
.. we all know that new does three tasks - allocating the memory, initializing
the fields with default values, and calling the specified constructor. Now the
first task is same in both the approaches and there would probably be the same n
ative allocator being used in both the cases. But in case of Cloning, the alloca
ted memory is not initialized with default values and also no constructor is cal
led in this case. Only a datacopy instruction will be executed which copies the
data from the original object to the cloned object. Read more about Cloing in th
is article - Cloning in Java >>
* Using De-Serialization - this can be thought of another different way of c
reating an object in Java. Again you might wonder that this internally uses new
operator only so why to consider this as a new way. Yeah... you re right. It d
oes uses the new operator internally and always calls the default constructor.
But two noticeable differences between the two approaches are:- In case of an e
xplict new call we may specify any constructor which is not the case here. It
ll always invoke the default constructor. Another difference is that in this cas
e the newly created object is initialized (or better to say re-written as the im
plicit new call with default constructor would have already initialized the ob
ject first with the default value and then with the specified value in the defau
lt constructor) with the data from the Input Stream fetched usually from a persi
stent medium. This step is obviously not involved in an explicit new call.
* Using Class.forName() and newInstance() - A calss can be dynamically loade
d using the Class.formName() method. This method has two variants - one which ac
cepts only a String type parameter which is the qualifies name of the class to b
e loaded and the other variant expects three parameters - the String type qualif
ies class name, boolean type flag to specify if the class should be initialized,
and the ClassLoader name which should be used to load the class. The former var
iant also internally calls the three-parameter variant only by assuming the bool
ean flag as true and the ClassLoader as returned by the getClassLoader() metho
d. That means Class.forName("qualified.ClassName") is internally translated in
to Class.forName("qualifies.ClassName", true, this.getClass().getClassLoader())
. Once the class has been loaded then a call of the method newInstance() on the
loaded Class object will first check if the Class object is initialized or not
and if not then it will initialize the Class object and create a new object as i
f the new operator has been called with the default constructor of the class u
nder consideration. Again you may argue how is this different from an explicit
new call and it won t take much of an effort to identify the most obvious diffe
rence between the two as the inability of this approach to call any other constr
uctor except the default constructor. Another difference is that the newInstance
() call may throw a SecurityException as well because it checks if a Security Ma
nager is installed or not and if it finds a security manager then it checks for
access to the class as wellas to the package (if any package specified in the qu
alified name). Either of two checks may throw a SecurityException. This step is
obviously not involved with an explicit new call. Another slightly different w
ay of object creation is by using the loadClass() method of the ClassLoader clas
s which returns a Class object of the specified class and then on the returned C
lass object we may call newInstance() method to create a new object. I ve not pu
t this as a completely separate way because I think Class.forName() method also
internally calls this method only - either for the explcitly supplied ClassLoade
r or for the implcitily obtained ClassLoader as discussed above. What s the diff
erence between the two approaches then? The only difference which I can see is t
hat the former checks for the access to the class (and package) and hence it may
throw SecurityException if a Security Manager is installed. But the latter does
n t do these checks and hence doesn t throw SecurityException. It s normally adv
ised not to call the loadClass() method directly as almost always you can call C
lass.forName() by supplying the particular ClassLoader reference.
Is there any other different way of creating objects in Java? I don t think that
there is any other way. Using JNI may pop up as another possible way, but I don
t think that JNI offers any different way of object creation due to the fact th
at JNI is not meant for object creation instead it s used for interacting with n
ative methods written in some other languages (mainly in C/C++) and hence a Java
class using JNI code is same as any other Java from object creation perspective
. Therefore, I think it uses any one of the above mentioned approaches only - mo
st commnonly the explicit new calls. I personally don t have much exposure to
JNI and I sincerely welcome comments from the JNI experts if they think otherwis
e.
=================================================================
Can we access an unreachable object in Java?

Yeah... we can. Sounds strange? But, it s true. We can access an unreachable obj
ect in Java.

This can be done by overriding the finalize() method and inside the method we ca
n assign the reference this to some other active reference and this way the un
reachable object becomes reachable again which can be accessed like any other ob
ject. However this is not a good practice and it s seldom used (if at all).

What s finalization in Java and what s it used for?

In Java it s mainly used for doing the postmortem cleanup activities particularl
y used for reclaiming native resources or any other non-memory resources which c
an t directly be recollected by the Garbage Collector.

How the finalization of an object happens internally?

protected void finalize() throws Throwable is the signature of the finalize() me


thod in the Object class and whenever any class overrides this method then an ob
ject of that class is internally marked by the JVM as finalizable. If such an ob
ject becomes unreachable then the Garbage Collector adds it to the JVM s finaliz
ation queue. It also makes sure that all the objects reachable from that object
are also retained as it can t be sure what all objects may be accessed from insi
de the finalize() method. Now the object is dequeued from the finalization queue
and the finalize() method is executed on that object. Once the control exits fr
om the finalize() method then the object is considered to be finalized which is
again tested by the Garbage Collector and if the GC finds that the finalilzed ob
ject is unreachable then it reclaims the memory space occupied by that object an
d also the spaces occupied by other unreachable objects which were retained simp
ly because they were reachable from the finalizable object.

You can easily deduce that such a lengthy process obviously takes time and conse
quently slows down the performance. Hence it s always advisable to use (override
) the finalize() judiciously.

What if the super class is finalizable but not the sub class?

This is not possible as the sub class will automatically become finalizable by i
nheriting the finalize() method from the super class. Do consider the consequenc
es thoroughly before making any class finalizable otherwise you may end up with
memory renetion problems. For example: if a super class is finalizable and sub c
lass which is not explicitly finalizable is having fields occupying huge memory
chunks then reclamation of memory occupied by a sub class instance will be delay
ed till the associated super class instance gets finalized. How to deal with suc
h a situation? Well... you can use composition in stead of inheritance to avoid
this problem. This will make sure that reclaimation of only the field of the fin
alizable class type gets delayed and not the entire object. You can easily have
a method disposing the other fields which otherwise would have kept occupying th
e precious memory for no real purpose. This approach is quite useful in case you
are using a third-party finalizable class.

In case you are writing the class yourself then you may break the class into two
class - one having the code which really require finalization (i.e., the code w
hich uses native or other non-memory resources) and the other class which simply
uses the former class as a member and other non-finalizable members. Now you on
ly need to make the former class finalizable and not the latter.

The bottom line is that don t make any class finalizable unless you have a very
good reason behind it and in case you need to make then also make sure that the
finalization process doesn t really cause unnecessary memory-renetion.

Is finalization guaranteed? What s the actual contract?

No... it s not guaranteed that the finalization of all the finalizable objects w
ill happen before they are reclaimed so it obviously doesn t make sense to put a
ny other code except the clean-up code inside the finalize() method. In fact fin
alizer is mainly used for having clean-up code for non-memory and native resourc
es only.

The JVM doesn t guarantee the actual order in which the finalization of the fina
lizable objects will take place. All the finalizers either from the application
or from the libraries are treated equally with no exception.
The JVM doesn t guarantee which thread will invoke the finalize() method of a pa
rticular object and only guarantees that the thread which will invoke the method
will not have any user-visible synchronization lock at the time of finalize() i
nvocation.

Grrr... so much of non-determinism involved. Yeah... unfortunately it s like thi


s only. So think twice before making any class finalizable.

What if the finalize() method throws any Exception?

If an uncaught exception is thrown from within the finalize() method then it s s


imply ignored and the finalization of that object terminates immediately.

Any alternative to Finalization in Java?

One possible alternative is to use weak references instead of finalization. This


will ensure that the programmer has a complete control over how to reclaim the
resources, how to prioritize the reclaimation process (may be based on the avail
ability of a particular native or non-memory resource), etc. We ll discuss about
the weak references and about this approach in some other article.
=================================================================
Can we access an unreachable object in Java?

Yeah... we can. Sounds strange? But, it s true. We can access an unreachable obj
ect in Java.

This can be done by overriding the finalize() method and inside the method we ca
n assign the reference this to some other active reference and this way the un
reachable object becomes reachable again which can be accessed like any other ob
ject. However this is not a good practice and it s seldom used (if at all).

What s finalization in Java and what s it used for?

In Java it s mainly used for doing the postmortem cleanup activities particularl
y used for reclaiming native resources or any other non-memory resources which c
an t directly be recollected by the Garbage Collector.

How the finalization of an object happens internally?

protected void finalize() throws Throwable is the signature of the finalize() me


thod in the Object class and whenever any class overrides this method then an ob
ject of that class is internally marked by the JVM as finalizable. If such an ob
ject becomes unreachable then the Garbage Collector adds it to the JVM s finaliz
ation queue. It also makes sure that all the objects reachable from that object
are also retained as it can t be sure what all objects may be accessed from insi
de the finalize() method. Now the object is dequeued from the finalization queue
and the finalize() method is executed on that object. Once the control exits fr
om the finalize() method then the object is considered to be finalized which is
again tested by the Garbage Collector and if the GC finds that the finalilzed ob
ject is unreachable then it reclaims the memory space occupied by that object an
d also the spaces occupied by other unreachable objects which were retained simp
ly because they were reachable from the finalizable object.

You can easily deduce that such a lengthy process obviously takes time and conse
quently slows down the performance. Hence it s always advisable to use (override
) the finalize() judiciously.

What if the super class is finalizable but not the sub class?

This is not possible as the sub class will automatically become finalizable by i
nheriting the finalize() method from the super class. Do consider the consequenc
es thoroughly before making any class finalizable otherwise you may end up with
memory renetion problems. For example: if a super class is finalizable and sub c
lass which is not explicitly finalizable is having fields occupying huge memory
chunks then reclamation of memory occupied by a sub class instance will be delay
ed till the associated super class instance gets finalized. How to deal with suc
h a situation? Well... you can use composition in stead of inheritance to avoid
this problem. This will make sure that reclaimation of only the field of the fin
alizable class type gets delayed and not the entire object. You can easily have
a method disposing the other fields which otherwise would have kept occupying th
e precious memory for no real purpose. This approach is quite useful in case you
are using a third-party finalizable class.

In case you are writing the class yourself then you may break the class into two
class - one having the code which really require finalization (i.e., the code w
hich uses native or other non-memory resources) and the other class which simply
uses the former class as a member and other non-finalizable members. Now you on
ly need to make the former class finalizable and not the latter.

The bottom line is that don t make any class finalizable unless you have a very
good reason behind it and in case you need to make then also make sure that the
finalization process doesn t really cause unnecessary memory-renetion.

Is finalization guaranteed? What s the actual contract?

No... it s not guaranteed that the finalization of all the finalizable objects w
ill happen before they are reclaimed so it obviously doesn t make sense to put a
ny other code except the clean-up code inside the finalize() method. In fact fin
alizer is mainly used for having clean-up code for non-memory and native resourc
es only.

The JVM doesn t guarantee the actual order in which the finalization of the fina
lizable objects will take place. All the finalizers either from the application
or from the libraries are treated equally with no exception.

The JVM doesn t guarantee which thread will invoke the finalize() method of a pa
rticular object and only guarantees that the thread which will invoke the method
will not have any user-visible synchronization lock at the time of finalize() i
nvocation.

Grrr... so much of non-determinism involved. Yeah... unfortunately it s like thi


s only. So think twice before making any class finalizable.

What if the finalize() method throws any Exception?

If an uncaught exception is thrown from within the finalize() method then it s s


imply ignored and the finalization of that object terminates immediately.

Any alternative to Finalization in Java?

One possible alternative is to use weak references instead of finalization. This


will ensure that the programmer has a complete control over how to reclaim the
resources, how to prioritize the reclaimation process (may be based on the avail
ability of a particular native or non-memory resource), etc. We ll discuss about
the weak references and about this approach in some other article.
=================================================================
Java architecture, JRE, Java Platform, JVM, JDK

Java Architecture

Java is much more than just a popular programming language instead it s a comple
te architecture. The entire Java archirecture can be broadly categorized into th
ree technologies which work together to make Java a powerful software developmen
t architecture. The components of the Java architecture are:-
* The Java Programming Language - JLS (Java Langauge Specifications) provide
the syntax, constructs, grammar, etc. of the Java language.
* The Java APIs - Java Application Programming Interfaces (APIs) make availa
ble plethora of functionalities to the application developers so that they can f
ocus on their core business functionality without bothering about the common tas
ks including those from the areas - I/O, Network, Language Constructs, Multithre
ading, Serialization, etc. Many vendors have implemented these APIs including th
e standard implementation given by Sun Microsystems which is normally used as a
benchmark. The Java APIs are simply a collection of Java .class files. A .class
file is the bytecode representation of a valid Java program. Bytecodes are a col
lection operator-operand tuples which are converted into the native machine leve
l instructions by the underlying JVM.
* The Java Virtual Machine - The JVM is the abstract machine which runs all
the bytecodes on a particular machine. JVM converts the bytecodes into native in
structions which are executed by the underlying Operating System.

JVM - Java Virtual Machine

This software component is the key to achieve Platform Independence feature of J


ava. Most of the popular platforms have their own JVM implementations and hence
a Java program written and compiled on a Java-compliant platform can be run on a
ny other Java-compliant platform.
JVM is mainly composed of two components - Classloader and Execution Engine. The
first component loads the .class files after converting them into the implement
ation dependent internal data structures. The Execution Engine uses these data s
tructures are converts the bytecode instructions into machine-level instructions
for the underlying Operating System which are subsequently executed by the OS.

Java Runtime Environment (JRE) / Java Platform

Both the terms JRE and Java Platform represent the same thing. Java Platform sta
rted with the verion 1.2, and it was called The Java 2 Platform. JRE is nothing
but a combination of JVM and Java APIs - Java SE APIs as well as Java Web (Deplo
yment) which consists of Java Web App Development/Deployment, Java Web Start, an
d Applet (plug-in).

Java Development Kit (JDK)

As the name suggest it s a Kit and it contains all the software components used
for compiling, documenting, and executing Java programs. It s basically a logica
l collection of the The Java Programming Language, JRE (JVM + Java APIs), and To
ols & Tool APIs, which include java, javac, javadoc, apt, jar, javap, Deploy, Mo
nitoring, Java VisualVM, Scripting, etc.
=================================================================
When & how does a JVM Shutdown? What s JVM Shutdown Sequence?
The JVM may shut down either normally or it may also be terminated abnormally:-
* Normal Shutdown - this occurs either when the last non-daemon thread exits
OR when Runtime.exit() method (or its equivalent System.exit() method) is invok
ed. In a normal shutdown the JVM shutdown sequence is invoked. The shutdown sequ
ence of a JVM is consists of two phases - One, execution of all registered shutd
own hooks (read more about them in this article - Shutdown Hooks in Java >>) and
Two, execution of all uninvoked finalizers (if finalization-on-exit is enabled)
and then halting the JVM process.
* Abnormal Shutdown - this occurs when the JVM is terminated using an user i
nterrupt such as typing Ctrl + C or by logging off or shutting down the machine.
In such a case, the underlying operating system may allow the JVM to complete i
ts shutdown within a fixed time frame OR it may halt the JVM process immediately
and abriptly using the Runtime.halt() method. If the JVM has only a few quick-r
unning shut down hooks (and only a few uninvoked finalizers if the finalization-
on-exit is enabled) then an abnormal shut down may also have the same effect in
case the OS gives adequate time for the JVM to complete these tasks. Once the sh
utdown sequence is already in progress and the OS finds that the allowed time ha
s expired then it may call the Runtime.halt() to abruptly terminate the JVM proc
ess.
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================

Is this answer useful? Yes | No


November 02, 2007 12:09:26
Dusan B
RE: how to identify strong aggregation (composition) r...
Difference between association and aggregation (while programming implementation
for both):
the main difference is conceptual - Aggregation says that an object is made up o
f other objects and association says that they have a relationship they know of
each other or they use each other in some way.
As far as programming the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here but the child making up
the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships going from 1-1 all the way up to *-*.
To clarify when implementing aggregation Car and Tire the Car has an aggregation
to Tire and the car has between 4-5 Tire (as an example one is spare in the tru
nk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car you have to check that it has at least 4 and no mor
e than 5 tires and when implementing the Tire you have to at all times have a re
ference to the Car (which means passing the Car reference in the constructor). F
urthermore when the Car reference is set to null you have to pro grammatically m
ake sure that the Tire references are also set to null in case of Aggregation bu
t if u model your system as Car just having an association to Tire this might no
t necessarily be true.
Is this answer useful? Yes | No Answer is useful 1 Answer is not useful 0
Overall Rating: +1
September 30, 2008 21:28:56
jherna Member Since: September 2008 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
First let me say that aggregation is not composition or viseversa. The OOD conce
pt is "Association" and there are two types. Both are "Has a" relationships. One
is "Aggregation" (a strong "Has a") and the other is "Composition" (a weak "Has
a").
AGGREGATION EXAMPLE:
A Person class is an the "aggregating" class and the Person object "has a" heart
from the Heart class which is the "component" class. When the Person class obje
ct is collected by garbage collection so does the Heart class object associated
with that Person class object.
COMPOSITION EXAMPLE:
An Engine class is an the "aggregating" class and the Engine object "has a" carb
uator from the Carbuator class which is the "component" class. When the Engine c
lass object is collected by garbage collection the Carbuator class object associ
ated with that Engine class object does not go to the salvage yard. It can go to
another Engine object.
Is this answer useful? Yes | No Answer is useful 0 Answer is not useful 2
Overall Rating: -2
November 10, 2009 10:19:40
Neo_TCS Member Since: November 2009 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
Composition is the strongest form of association - not a Weak has a as said abov
e...
================================================================================
===========
Q:
What are the callback methods in Entity beans?
A:
The bean class defines create methods that match methods in the home interface a
nd business methods that match methods in the remote interface. The bean class a
lso implements a set of callback methods that allow the container to notify the
bean of events in its life cycle. The callback methods are defined in the javax.
ejb.EntityBean interface that is implemented by all entity beans.The EntityBean
interface has the following definition. Notice that the bean class implements th
ese methods.
public interface javax.ejb.EntityBean {
public void setEntityContext();
public void unsetEntityContext();
public void ejbLoad();
public void ejbStore();
public void ejbActivate();
public void ejbPassivate();
public void ejbRemove();
}
The setEntityContext() method provides the bean with an interface to the contain
er called the EntityContext. The EntityContext interface contains methods for ob
taining information about the context under which the bean is operating at any p
articular moment. The EntityContext interface is used to access security informa
tion about the caller; to determine the status of the current transaction or to
force a transaction rollback; or to get a reference to the bean itself, its home
, or its primary key. The EntityContext is set only once in the life of an entit
y bean instance, so its reference should be put into one of the bean instance's
fields if it will be needed later.
The unsetEntityContext() method is used at the end of the bean's life cycle befo
re the instance is evicted from memory to dereference the EntityContext and perf
orm any last-minute clean-up.
The ejbLoad() and ejbStore() methods in CMP entities are invoked when the entity
bean's state is being synchronized with the database. The ejbLoad() is invoked
just after the container has refreshed the bean container-managed fields with it
s state from the database. The ejbStore() method is invoked just before the cont
ainer is about to write the bean container-managed fields to the database. These
methods are used to modify data as it's being synchronized. This is common when
the data stored in the database is different than the data used in the bean fie
lds.
The ejbPassivate() and ejbActivate() methods are invoked on the bean by the cont
ainer just before the bean is passivated and just after the bean is activated, r
espectively. Passivation in entity beans means that the bean instance is disasso
ciated with its remote reference so that the container can evict it from memory
or reuse it. It's a resource conservation measure the container employs to reduc
e the number of instances in memory. A bean might be passivated if it hasn't bee
n used for a while or as a normal operation performed by the container to maximi
ze reuse of resources. Some containers will evict beans from memory, while other
s will reuse instances for other more active remote references. The ejbPassivate
() and ejbActivate() methods provide the bean with a notification as to when it'
s about to be passivated (disassociated with the remote reference) or activated
(associated with a remote reference).
================================================================================
===========
Q:
Can Entity Beans have no create() methods?
A:
Yes. In some cases the data is inserted NOT using Java application, so you may o
nly need to retrieve the information, perform its processing, but not create you
r own information of this kind.
================================================================================
===========
:
What are transaction attributes?
A:
The transaction attribute specifies how the Container must manage transactions f
or a method when a client invokes the method via the enterprise bean’s home or com
ponent interface or when the method is invoked as the result of the arrival of a
JMS message. (Sun s EJB Specification) Below is a list of transactional attribu
tes:
1. NotSupported - transaction context is unspecified.
2. Required - bean s method invocation is made within a transactional context. I
f a client is not associated with a transaction, a new transaction is invoked au
tomatically.
3. Supports - if a transactional context exists, a Container acts like the trans
action attribute is Required, else - like NotSupported.
4. RequiresNew - a method is invoked in a new transaction context.
5. Mandatory - if a transactional context exists, a Container acts like the tran
saction attribute is Required, else it throws a javax.ejb.TransactionRequiredExc
eption.
6. Never - a method executes only if no transaction context is specified.
================================================================================
===========
What are transaction isolation levels in EJB?
A:
1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a
DB(fast but not wise).
2. Transaction_read_committed- Guarantees that the data you are getting has been
committed.
3. Transaction_repeatable_read - Guarantees that all reads of the database will
be the same during the transaction (good for read and update operations).
4. Transaction_serializable- All the transactions for resource are performed ser
ial.
================================================================================
===========
what is the difference b/w EJB2.1 and EJB3.0?
EJB3.0
1. No need of Home Interface (EJBHome) but it is needed in EJB2.0
2. No more confusions to make an EJB remote or local it s the client which wo
uld decide and cast to appropriate.
3. Just write SINGLE simple Java class and annotate it to be Stateless/Statef
ul/Entity/MessageDriven.Container
4. No Deployment Descriptors MetaData Annotations are explored which is intro
duced in J2SE5.0
5. Forget all EJB life cycles.For example Entity bean life cycle in 3.0 is ne
w managed detached removed.
Ready to develop complex query inner/outer join with EJB3.0.
The main difference lies in the persistence In case of EJB 3.0 there is JPA J
ava persistence API which makes the mapping of EntityBeans with the database eas
y with the help of a service called as EntityManager.
Mapping is done with the help of annotations unlike in EJB2.0.
Home interfaces are eliminated.
Deployment descriptors are an option in EJB 3.0.
EJB3.0 also supports webservice client through SOAP and WSDl.
================================================================================
===========
What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
*
The spring container finds the bean’s definition from the XML file and insta
ntiates the bean.
*
Using the dependency injection, spring populates all of the properties as
specified in the bean definition
*
If the bean implements the BeanNameAware interface, the factory calls setB
eanName() passing the bean’s ID.
*
If the bean implements the BeanFactoryAware interface, the factory calls s
etBeanFactory(), passing an instance of itself.
*
If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
*
If an init-method is specified for the bean, it will be called.
*
Finally, if there are any BeanPostProcessors associated with the bean, the
ir postProcessAfterInitialization() methods will be called.
================================================================================
===========
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
* Configure Spring to manage your Actions as beans, using the ContextLoaderP
lugin, and set their dependencies in a Spring context file.
* Subclass Spring s ActionSupport classes and grab your Spring-managed beans
explicitly using a getWebApplicationContext() method.
================================================================================
===========
Package java.util.concurrent Description
Utility classes commonly useful in concurrent programming. This package includes
a few small standardized extensible frameworks, as well as some classes that pr
ovide useful functionality and are otherwise tedious or difficult to implement.
Here are brief descriptions of the main components. See also the locks and atomi
c packages.
Executors
Interfaces. Executor is a simple standardized interface for defining custom thre
ad-like subsystems, including thread pools, asynchronous IO, and lightweight tas
k frameworks. Depending on which concrete Executor class is being used, tasks ma
y execute in a newly created thread, an existing task-execution thread, or the t
hread calling execute(), and may execute sequentially or concurrently. ExecutorS
ervice provides a more complete asynchronous task execution framework. An Execut
orService manages queuing and scheduling of tasks, and allows controlled shutdow
n. The ScheduledExecutorService subinterface and associated interfaces add suppo
rt for delayed and periodic task execution. ExecutorServices provide methods arr
anging asynchronous execution of any function expressed as Callable, the result-
bearing analog of Runnable. A Future returns the results of a function, allows d
etermination of whether execution has completed, and provides a means to cancel
execution. A RunnableFuture is a Future that possesses a run method that upon ex
ecution, sets its results.
Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor prov
ide tunable, flexible thread pools. The Executors class provides factory methods
for the most common kinds and configurations of Executors, as well as a few uti
lity methods for using them. Other utilities based on Executors include the conc
rete class FutureTask providing a common extensible implementation of Futures, a
nd ExecutorCompletionService, that assists in coordinating the processing of gro
ups of asynchronous tasks.
Queues
The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scala
ble thread-safe non-blocking FIFO queue. Five implementations in java.util.concu
rrent support the extended BlockingQueue interface, that defines blocking versio
ns of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, P
riorityBlockingQueue, and DelayQueue. The different classes cover the most commo
n usage contexts for producer-consumer, messaging, parallel tasking, and related
concurrent designs. The BlockingDeque interface extends BlockingQueue to suppor
t both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provide
s an implementation.
Timing
The TimeUnit class provides multiple granularities (including nanoseconds) for s
pecifying and controlling time-out based operations. Most classes in the package
contain operations based on time-outs in addition to indefinite waits. In all c
ases that time-outs are used, the time-out specifies the minimum time that the m
ethod should wait before indicating that it timed-out. Implementations make a "b
est effort" to detect time-outs as soon as possible after they occur. However, a
n indefinite amount of time may elapse between a time-out being detected and a t
hread actually executing again after that time-out. All methods that accept time
out parameters treat values less than or equal to zero to mean not to wait at al
l. To wait "forever", you can use a value of Long.MAX_VALUE.
Synchronizers
Four classes aid common special-purpose synchronization idioms. Semaphore is a c
lassic concurrency tool. CountDownLatch is a very simple yet very common utility
for blocking until a given number of signals, events, or conditions hold. A Cyc
licBarrier is a resettable multiway synchronization point useful in some styles
of parallel programming. An Exchanger allows two threads to exchange objects at
a rendezvous point, and is useful in several pipeline designs.
Concurrent Collections
Besides Queues, this package supplies Collection implementations designed for us
e in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, Concurren
tSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads a
re expected to access a given collection, a ConcurrentHashMap is normally prefer
able to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferab
le to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchron
ized ArrayList when the expected number of reads and traversals greatly outnumbe
r the number of updates to a list.
The "Concurrent" prefix used with some classes in this package is a shorthand in
dicating several differences from similar "synchronized" classes. For example ja
va.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronize
d. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe
, but not governed by a single exclusion lock. In the particular case of Concurr
entHashMap, it safely permits any number of concurrent reads as well as a tunabl
e number of concurrent writes. "Synchronized" classes can be useful when you nee
d to prevent all access to a collection via a single lock, at the expense of poo
rer scalability. In other cases in which multiple threads are expected to access
a common collection, "concurrent" versions are normally preferable. And unsynch
ronized collections are preferable when either collections are unshared, or are
accessible only when holding other locks.
Most concurrent Collection implementations (including most Queues) also differ f
rom the usual java.util conventions in that their Iterators provide weakly consi
stent rather than fast-fail traversal. A weakly consistent iterator is thread-sa
fe, but does not necessarily freeze the collection while iterating, so it may (o
r may not) reflect any updates since the iterator was created.
Memory Consistency Properties
Chapter 17 of the Java Language Specification defines the happens-before relatio
n on memory operations such as reads and writes of shared variables. The results
of a write by one thread are guaranteed to be visible to a read by another thre
ad only if the write operation happens-before the read operation. The synchroniz
ed and volatile constructs, as well as the Thread.start() and Thread.join() meth
ods, can form happens-before relationships. In particular:
* Each action in a thread happens-before every action in that thread that co
mes later in the program s order.
* An unlock (synchronized block or method exit) of a monitor happens-before
every subsequent lock (synchronized block or method entry) of that same monitor.
And because the happens-before relation is transitive, all actions of a thread
prior to unlocking happen-before all actions subsequent to any thread locking th
at monitor.
* A write to a volatile field happens-before every subsequent read of that s
ame field. Writes and reads of volatile fields have similar memory consistency e
ffects as entering and exiting monitors, but do not entail mutual exclusion lock
ing.
* A call to start on a thread happens-before any action in the started threa
d.
* All actions in a thread happen-before any other thread successfully return
s from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend th
ese guarantees to higher-level synchronization. In particular:
* Actions in a thread prior to placing an object into any concurrent collect
ion happen-before actions subsequent to the access or removal of that element fr
om the collection in another thread.
* Actions in a thread prior to the submission of a Runnable to an Executor h
appen-before its execution begins. Similarly for Callables submitted to an Execu
torService.
* Actions taken by the asynchronous computation represented by a Future happ
en-before actions subsequent to the retrieval of the result via Future.get() in
another thread.
* Actions prior to "releasing" synchronizer methods such as Lock.unlock, Sem
aphore.release, and CountDownLatch.countDown happen-before actions subsequent to
a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition
.await, and CountDownLatch.await on the same synchronizer object in another thre
ad.
* For each pair of threads that successfully exchange objects via an Exchang
er, actions prior to the exchange() in each thread happen-before those subsequen
t to the corresponding exchange() in another thread.
* Actions prior to calling CyclicBarrier.await happen-before actions perform
ed by the barrier action, and actions performed by the barrier action happen-bef
ore actions subsequent to a successful return from the corresponding await in ot
her threads.
================================================================================
===========
What are the config files used for connecting Java and Flex?
Ans:
data-management-config.xml,
messaging-config.xml,
proxy-config.xml,
remoting-config.xml,
services-config.xml
================================================================================
===========
Lets have a look on Javadoc tags
Tag Description
@version Shows the version number of a class or method.
@author Shows the Developer
name
@return Documents the return value. This tag should not be used for con
structors or methods defined with a void return type.
@deprecated Marks a method as deprecated. Some IDEs will issue a compilatio
n warning if the method is called.
@see Documents an association to another method or class.
@param Defines a method parameter. Required for each parameter.
@throws Documents an exception thrown by a method. A synonym for @excep
tion introduced in Javadoc 1.2.
@since Documents when a method was added to a class.
@exception Documents an exception thrown by a method — also see @throws.
private Displays all classes and members
use It creates class and package usage pages
Windowtitle It shows the window title of the document
Header It includes for header text of the page
Footer It includes footer text for the page
Bottom It includes bottom text for the page
Package Shows package classes and members
Protected shows protected classes and members
Classpath Helps to find user class files
noindex doesn t provide the index
nohelp doesn t provide the help link
notree doesn t provide class hierarchy
================================================================================
===========
. Final class can not be a base or a child class of any other class.
================================================================================
===========
<generator> element
The <generator> method is used to generate the primary key for the new record. H
ere is some of the commonly used generators :
* Increment - This is used to generate primary keys of type long, short or int t
hat are unique only. It should not be used in the clustered deployment environme
nt.
* Sequence - Hibernate can also use the sequences to generate the primary key.
It can be used with DB2
, PostgreSQL, Oracle, SAP DB databases.
* Assigned - Assigned method is used when application code generates the primary
key.

================================================================================
===========
to specify to show the sql statement
<property name="show_sql">true</property>
================================================================================
===========
FLEX
======================
<mx:Application backgroundColor="#FFFFFF">
<mx:HTTPService id="srv" url="catalog.jsp"/>
<mx:DataGrid dataProvider="{srv.lastResult.catalog.product}" width="100%" height
="100%"/>
<mx:Button label="Get Data" click="srv.send()"/>
</mx:Application>
================================================================================
===========
<mx:Application backgroundColor="#FFFFFF">
<mx:WebService id="srv" wsdl="http://coenraets.org/services/ProductWS?wsdl" show
BusyCursor="true"/>
?
<mx:DataGrid dataProvider="{srv.getProducts.lastResult}" width="100%" height="10
0%">
?
<mx:columns>
<mx:DataGridColumn dataField="productId" headerText="Product Id"/>
<mx:DataGridColumn dataField="name" headerText="Name"/>
<mx:DataGridColumn dataField="price" headerText="Price"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="Get Data" click="srv.getProducts()"/>
</mx:Application>
================================================================================
===========
<mx:Application backgroundColor="#FFFFFF">
<mx:RemoteObject id="srv" destination="product"/>
<mx:DataGrid dataProvider="{srv.getProducts.lastResult}" width="100%" height="10
0%"/>
<mx:Button label="Get Data" click="srv.getProducts()"/>
</mx:Application>
================================================================================
===========
What is the Web service protocol stack?
The Web service protocol stack is an evolving set of protocols used to define, d
iscover, and implement Web services. The core protocol stack consists of four la
yers:
Service Transport: This layer is responsible for transporting messages between a
pplications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such
as Blocks Extensible Exchange Protocol (BEEP).
XML Messaging: This layer is responsible for encoding messages in a common XML f
ormat so that messages can be understood at either end. Currently, this includes
XML-RPC and SOAP.
Service Description: This layer is responsible for describing the public interfa
ce to a specific Web service. Currently, service description is handled via the
WSDL.
Service Discovery: This layer is responsible for centralizing services into a co
mmon registry, and providing easy publish/find functionality. Currently, service
discovery is handled via the UDDI.
Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol
stack includes a whole zoo of newer, evolving protocols. These include WSFL (We
b Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signatur
e), and USML (UDDI Search Markup Language). For an overview of these protocols,
check out Pavel Kulchenko s article, Web Services Acronyms, Demystified, on XML.
com.
Fortunately, you do not need to understand the full protocol stack to get starte
d with Web services. Assuming you already know the basics of HTTP, it is best to
start at the XML Messaging layer and work your way up.
================================================================================
===========
What is WSDL?
The Web Services Description Language (WSDL) currently represents the service de
scription layer within the Web service protocol stack.
In a nutshell, WSDL is an XML grammar for specifying a public interface for a We
b service. This public interface can include the following:
Information on all publicly available functions.
Data type information for all XML messages.
Binding information about the specific transport protocol to be used.
Address information for locating the specified service.
WSDL is not necessarily tied to a specific XML messaging system, but it does inc
lude built-in extensions for describing SOAP services.
Below is a sample WSDL file. This file describes the public interface for the we
ather service used in the SOAP example above. Obviously, there are many details
to understanding the example. For now, just consider two points.
First, the <message> elements specify the individual XML messages that are trans
ferred between computers. In this case, we have a getWeatherRequest and a getWea
therResponse. Second, the element specifies that the service is available via SO
AP and is available at a specific URL.
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="WeatherService"
targetNamespace="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="getWeatherRequest">
<part name="zipcode" type="xsd:string"/>
</message>
<message name="getWeatherResponse">
<part name="temperature" type="xsd:int"/>
</message>
<portType name="Weather_PortType">
<operation name="getWeather">
<input message="tns:getWeatherRequest"/>
<output message="tns:getWeatherResponse"/>
</operation>
</portType>
<binding name="Weather_Binding" type="tns:Weather_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="getWeather">
<soap:operation soapAction=""/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>
</output>
</operation>
</binding>
<service name="Weather_Service">
<documentation>WSDL File for Weather Service</documentation>
<port binding="tns:Weather_Binding" name="Weather_Port">
<soap:address
location="http://localhost:8080/soap/servlet/rpcrouter"/>
</port>
</service>
</definitions>
Using WSDL, a client can locate a Web service, and invoke any of the publicly av
ailable functions. With WSDL-aware tools, this process can be entirely automated
, enabling applications to easily integrate new services with little or no manua
l code. For example, check out the GLUE platform from the Mind Electric.
WSDL has been submitted to the W3C, but it currently has no official status with
in the W3C. See this W3C page for the latest draft.
================================================================================
===========
public class DoubleCheckedSingleton {
private static DoubleCheckedSingleton instance;
private final Vector v;
private final boolean inUse;
private DoubleCheckedSingleton() {
v = new Vector();
v.addElement(new Object());
inUse = true;
}
public static DoubleCheckedSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckedSingleton.class) { // 1
if (instance == null) // 2
instance = new DoubleCheckedSingleton();
// 3
}
}
return instance;
}
}
================================================================================
===========
Collection Difficult Points
============================
. If you add same key multiple times it takes last one only. even same for null
as key also. Duplicate checking will be happens before you inserting, so if t
here is any duplication in key, it overrites the value .
================================================================================
===========
A static method can be synchronized. If you do so the JVM will obtain a lock on
the java.lang.Class instance associated with the object. It is similar to saying
:
synchronized(XYZ.class)
{
}
================================================================================
===========
Threads and Concurency
======================
wo overloaded versions of sleep are provided: one that specifies the sleep time
to the millisecond and one that specifies the sleep time to the nanosecond. Howe
ver, these sleep times are not guaranteed to be precise, because they are limite
d by the facilities provided by the underlying OS. Also, the sleep period can be
terminated by interrupts, as we ll see in a later section. In any case, you can
not assume that invoking sleep will suspend the thread for precisely the time pe
riod specified.

If t is a Thread object whose thread is currently executing,


t.join();
causes the current thread to pause execution until t s thread terminates. That s
meaning is i am(current thread) going to waining state(sleep, but not, after co
mpletion of my execution.) and i come back once t thread terminated. And i am
giving lock to t Overloads of join allow the programmer to specify a waiting p
eriod. However, as with sleep, join is dependent on the OS for timing, so you sh
ould not assume that join will wait exactly as long as you specify.
================================================================================
===========
An atomic operation is an operation which is performed as a single unit of work
without the possibility of interference from other operations.
In Java the language specification guarantees that that reading or writing a var
iable is atomic (unless the variable is of type long or double). Long and double
are only atomic if they declared as volatile.
The operation i++ it not atomic in Java for the standard variables (int, long, e
tc). It first reads the value which is currently stored in i (atomic operations)
and then it adds one to it (atomic operation). But between the read and the wri
te the value of i might have changed. Java
Since Java 1.5 the java language provides atomic variables, e.g. AtomicInteger o
r AtomicLong which provide methods like getAndDecrement(), getAndIncrement() and
getAndSet() which are atomic.
================================================================================
===========
Final
=====
. Final class you can change the state or reinitialize but you can not extend an
y where. ie. it is concrete class.
. But, for final classified or variable you can initialize only once only, but y
ou can chage the state.
. If you want to create a complete immutable, you should make every class field
as final. and if the any of the class field haveing objects thier class fields a
lso sould be final. Ex: EmployeeVO hava one AddressVO variable as class field, t
hen if you want to create complete immutable.
public final class FinalClassDemo {
public static void main(String[] args) {
FinalClassDemo demo = new FinalClassDemo();
System.out.println(demo.hashCode());
demo.print();
demo = new FinalClassDemo();
System.out.println(demo.hashCode());
demo.print();
}
String name = "India";
void print() {
System.out.println(name);
}
}

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

10. How does hibernate code looks like?


Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();
The Session and Transaction are the interfaces provided by hibernate. There are
many other interfaces besides this.
11. What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information i
s provided in an xml document. This document is called as xml mapping document.
The document defines, among other things, how properties of the user defined per
sistence classes’ map to the columns of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourc
eforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main ta
g for an xml mapping document.
The yield( ) Method So what does the static Thread.yield() have to
do with all this? Not that much, in practice. What yield() is supposed to do is
make the currently running thread head back to runnable to allow other threads o
f
the same priority to get their turn. So the intention is to use yield() to promo
te
graceful turn-taking among equal-priority threads. In reality, though, the yield
()
method isn t guaranteed to do what it claims, and even if yield() does cause a
thread to step out of running and back to runnable, there s no guarantee the yie
lding
thread won t just be chosen again over all the others! So while yield() might—and
often does—make a running thread give up its slot to another runnable thread of th
e
same priority, there s no guarantee.
A yield() won t ever cause a thread to go to the waiting/sleeping/ blocking
state. At most, a yield() will cause a thread to go from running to runnable, bu
t
again, it might have no effect at all.
The join( ) Method
The non-static join() method of class Thread lets one thread "join onto the end"
of another thread. If you have a thread B that can t do its work until another t
hread
A has completed its work, then you want thread B to "join" thread A. This means
that
thread B will not become runnable until A has finished (and entered the dead sta
te).
Thread t = new Thread();
t.start();
t.join();
The preceding code takes the currently running thread (if this were in the
main() method, then that would be the main thread) and joins it to the end of th
e
thread referenced by t. This blocks the current thread from becoming runnable
until after the thread referenced by t is no longer alive. In other words, the
code t.join() means "Join me (the current thread) to the end of t, so that t
must finish before I (the current thread) can run again." You can also call one
of the overloaded versions of join() that takes a timeout duration, so that
you re saying, "wait until thread t is done, but if it takes longer than 5,000
milliseconds, then stop waiting and become runnable anyway." Figure 9-3 shows
the effect of the join() method.

Wind
: Copying Defensive Immutable Mutable good safety thread
to defensive copying.
Programming defensively is an essential skill to learn if you want to produce a
robust API. By implementing defensive copying you can avoid unwanted and unexpec
ted behaviour that can compromise security and confuse your API clients.
The key to understanding defensive copying is understanding the difference betwe
en a mutable and an immutable class.
An immutable class is a class whose instances cannot be modified, for example th
e java.lang.String class.
A mutable class is a class whose instances can be modified, for example the java
.util.Date class.
Whilst immutable objects are inherently thread safe, mutable objects are not, an
d this is when we need to consider making defensive copies.
Take the following example:
public final class Person { private final String name; private final Date dateOf
Birth; public Person(final String name, final Date dateOfBirth) { this.dateOfBir
th = dateOfBirth; this.name = name; } public String getName() { return name; } p
ublic Date getDateOfBirth() { return dateOfBirth; } }
This class is immutable, right? Wrong.
Whilst it appears we cannot change the internal state of a Person Object after i
t has been instantiated this is actually not the case since dateOfBirth is a mut
able parameter.
final Date dob = new Date(455531800421l); final Person p = new Person("John Smit
h", dob); System.out.println(p.getName() + " dob: " + p.getDateOfBirth()); dob.s
etTime(555531800421l); // could also get dob via p.getDateOfBirth(); here System
.out.println(p.getName() + " dob: " + p.getDateOfBirth());
Result:
John Smith dob: Fri Jun 08 09:36:40 BST 1984 John Smith dob: Sun Aug 09 19:23:20
BST 1987
We have changed John Smith s DOB.
To avoid this we can defensively copy dateOfBirth: (notice we do this when we se
t dateOfBirth and when we expose it)
public final class Person { private final String name; private final Date dateOf
Birth; public Person(final String name, final Date dateOfBirth) { this.dateOfBir
th = new Date(dateOfBirth.getTime()); this.name = name; } public String getName(
) { return name; } public Date getDateOfBirth() { return (Date) dateOfBirth.clon
e(); } }
Now it is not possible to modify the internal state of a Person Object after it
has been instantiated and it is truly immutable (assuming we have an appropriate
SecurityManager in place).
Defensive copying isn t just for immutable classes, whenever you are dealing wit
h a client provided Object consider if that Object is mutable and what the side
effects could be if the client modifies that Object.
: Copying Defensive Immutable Mutable good safety thread
to defensive copying.
Programming defensively is an essential skill to learn if you want to produce a
robust API. By implementing defensive copying you can avoid unwanted and unexpec
ted behaviour that can compromise security and confuse your API clients.
The key to understanding defensive copying is understanding the difference betwe
en a mutable and an immutable class.
An immutable class is a class whose instances cannot be modified, for example th
e java.lang.String class.
A mutable class is a class whose instances can be modified, for example the java
.util.Date class.
Whilst immutable objects are inherently thread safe, mutable objects are not, an
d this is when we need to consider making defensive copies.
Take the following example:
public final class Person { private final String name; private final Date dateOf
Birth; public Person(final String name, final Date dateOfBirth) { this.dateOfBir
th = dateOfBirth; this.name = name; } public String getName() { return name; } p
ublic Date getDateOfBirth() { return dateOfBirth; } }
This class is immutable, right? Wrong.
Whilst it appears we cannot change the internal state of a Person Object after i
t has been instantiated this is actually not the case since dateOfBirth is a mut
able parameter.
final Date dob = new Date(455531800421l); final Person p = new Person("John Smit
h", dob); System.out.println(p.getName() + " dob: " + p.getDateOfBirth()); dob.s
etTime(555531800421l); // could also get dob via p.getDateOfBirth(); here System
.out.println(p.getName() + " dob: " + p.getDateOfBirth());
Result:
John Smith dob: Fri Jun 08 09:36:40 BST 1984 John Smith dob: Sun Aug 09 19:23:20
BST 1987
We have changed John Smith s DOB.
To avoid this we can defensively copy dateOfBirth: (notice we do this when we se
t dateOfBirth and when we expose it)
public final class Person { private final String name; private final Date dateOf
Birth; public Person(final String name, final Date dateOfBirth) { this.dateOfBir
th = new Date(dateOfBirth.getTime()); this.name = name; } public String getName(
) { return name; } public Date getDateOfBirth() { return (Date) dateOfBirth.clon
e(); } }
Now it is not possible to modify the internal state of a Person Object after it
has been instantiated and it is truly immutable (assuming we have an appropriate
SecurityManager in place).
Defensive copying isn t just for immutable classes, whenever you are dealing wit
h a client provided Object consider if that Object is mutable and what the side
effects could be if the client modifies that Object.

===================
Making a Collection Read-Only
Making a collection read-only involves wrapping the collection in another object
whose mutation methods all throw UnsupportedOperationException.
List stuff = Arrays.asList(new String[]{"a", "b"});
// Make a list read-only
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
try {
// Try modifying the list
list.set(0, "new value");
} catch (UnsupportedOperationException e) {
// Can t modify
}
// Make a set read-only
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
// Make a map read-only
Map map = new HashMap();
// Add key/value pairs ...
map = Collections.unmodifiableMap(map);

/*
Java Comparable example.
This Java Comparable example describes how java.util.Comparable interface is imp
lemented to compare user defined classe s objects.
*/
import java.util.*;
/*
Comparable interface is used to make user defined class s objects comparable.
This interface declares one method compareTo(Object object) and determines how o
jbects can be compared to each other.
*/
/*
Implement java.util.Comparable interface to make class objects comparable.
*/
class Employee implements Comparable{
private int age;
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
/*
Signature of compareTo method is.
public int compareTo(Object object).
compareTo method should return 0 if both objects are equal, 1 if first grater th
an other and -1 if first less than the other object of the same class.
*/
public int compareTo(Object otherEmployee){
/*
If passed object is of type other than Employee, throw ClassCastException.
*/
if( ! ( otherEmployee instanceof Employee ) ){
throw new ClassCastException("Invalid object");
}
int age = ( (Employee) otherEmployee ).getAge();
if( this.getAge() > age )
return 1;
else if ( this.getAge() < age )
return -1;
else
return 0;
}
}
public class JavaComparableExample{
public static void main(String args[]){
/*
Create two different Employee objects, so that we can compare both.
*/
Employee one = new Employee();
one.setAge(40);
Employee two = new Employee();
one.setAge(30);
/*
Use compareTo method to determine which employee is younger
*/
if( one.compareTo(two) > 0 ) {
System.out.println("Employee one is elder than employee two !");
} else if( one.compareTo(two) < 0 ) {
System.out.println("Employee one is younger than employee two !");
} else( one.compareTo(two) == 0 ) {
System.out.println("Both employees are same !");
}
}
}
/*
OUTPUT of the above given Java Comparable Example would be :
Employee one is elder than employee two !
*/
Catching all Errors and Exceptions
All errors and exceptions extend from Throwable. By catching Throwable, it is po
ssible to handle all unexpected conditions.
There are several scenarios where it is good practice to catch Throwable. For ex
ample, in a server application, the threads that handle requests should catch Th
rowable and relay any errors or exceptions to the client. Another scenario is a
long-running thread that performs some background activity. Such threads should
catch Throwable, log any errors or exceptions, and then continue functioning.
It is rarely good practice for a method in a library to catch Throwable. In gene
ral, errors and exceptions should not be masked from the caller.
This example demonstrates a long-running thread that catches Throwable and logs
the exception.
class BgThread extends Thread {
// Create a logger. For more information on the logging api s,
// see e385 The Quintessential Logging Program
Logger logger = Logger.getLogger("com.mycompany.mypackage");
BgThread() {
// As a daemon thread, this thread won t prevent the application fro
m exiting
setDaemon(true);
}
// Set to true to shut down this thread
boolean stop = false;
public void run() {
while (!stop) {
try {
// Perform work here
} catch (Throwable t) {
// Log the exception and continue
logger.log(Level.SEVERE, "Unexception exception", t);
}
}
}
}
Copying a Directory
// Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]));
}
} else {
// This method is implemented in e1071 Copying a File
copyFile(srcDir, dstDir);
}
}
GET and POST Requests
Question:
How does a servlet handle GET and POST requests?
Answer:
The HttpServlet abstract class, defined in the javax.servlet.http package, conta
ins several methods that simplify interacting with HTTP requests. Two of the met
hods take care of handling GET and POST requests. When you write a servlet, you
should subclass HttpServlet and implement the doGet() method to handle GET reque
sts. Similarly, to handle POST requests, you would implement the doPost() method
.
Both methods take an HttpServletRequest instance and an HttpServletResponse inst
ance as arguments. The HttpServletRequest instance contains all the information
pertaining to the request, including any request parameters. The HttpServletResp
onse is used to generate a response to the request.
Lazy Versus Eager Instantiation
There are techniques for creation of objects (read allocation of memory) widely
known as lazy Instantiation and Eager Instantiation.
Lazy instantiation is a memory conservation technique, by which, a program delay
s the creation of objects until those objects are needed. In Java, there are two
categories of lazy instantiation:
1. Lazy class loading
The Java runtime loads classes into memory only when they re first referenced. T
his may happen due to a first call to a static method of a class as in:
aClass.someStaticMethod();
or a first call to the "new" operator to create an instatnce of a class as in:
AClass aClass = new AClass();
This is a very important feature of the Java runtime. Memory usage can be signif
icantly reduced. For example, if a part of a program is never run, classes that
are only referenced by that part of the program will never be loaded.
2. Lazy object creation
This is tightly coupled to lazy class loading. It refers to when you delay the c
reation of an instance of a class until you really need it in the code.
Eager Instantiation, on the other hand, refers to technique that instances of ob
jects are created before any part of the code actually asks for them. This may c
onsiderably improve runtime performance since live objects are sitting in runtim
e memory waiting to be called. An example of eager instantiation is creation of
resource pools, e.g. a pool of database connections waiting for client calls.
Suppose you have to load images on request based corresponding image file names.
You can write code like:
public class AnImageFile
{
private String m_filename;
private Image m_image;
public AnImageFile(String filename)
{
m_filename=filename;
//Now load the image in constructor
}
public String getName(){ m_return filename;}
public Image getImage(){return m_image;}
}
This is an eager approach that guarantees the availability of an image right aft
er creation of an instance of AnImageFile class. This will boost performance whe
n a call to getImage(...) is made. But if you have many images, and create AnIma
geFile instances of them, you may use up a lot of memory unnecessarily. You can
trade performance benefits to memory uasage via lazy instantiation, as in:
public class ImageFile
{
private String m_filename;
private Image m_image=null;
public ImageFile(String filename)
{
//Here we just store the filename
m_filename=filename;
}
public String getName(){ return m_filename;}
public Image getImage()
{
if(m_image==null)
{
//load the image
}
return m_image;
}
}
Here, the actual image is loaded only on the first call to getImage().
So, you can reduce memory usage and startup time by using lazy instantiation and
paying the price for performance hit when you create an object when it is actua
lly need. Or, you can increase the startup time, and use up more memory upfront
to eagerly instantiate objects in order to boost performance.
Servlets vs. Applets
Question:
We currently use applets to allow users to access a database, but are looking fo
r ways to improve performance. Is a servlet-based solution faster than an applet
-based solution?
Answer:
This will depend on the application, the number of concurrent clients, the avera
ge network latency and bandwidth between a client and the server, and other fact
ors. In general, if you want your application to scale to large numbers of users
, you will want to forego the applet-centric solution. If each client applet has
to create a separate connection to the database, transfer data, and process it
locally, you face several potential bottlenecks.
First, you could overload your database with too many connections. Second, you m
ay have to transfer a lot of data over the network, which may take a long time.
Third, the client may not have enough processing power or memory to process all
of the data in a timely manner, if at all. Other problems also exist, such as th
e inability to centralize business logic, leading to software maintenance diffic
ulties.
The preferred design for such a system is a three-tier architecture. A three-tie
r system consists of a client, a middle layer that performs transaction processi
ng, and a back-end server. The client is usually lightweight, only able to issue
queries and receive final results. An example of this would be a simple HTML fo
rm. The middle layer s job is to mediate access to server resources and possibly
perform processing on the client s behalf. The server, of course, stores the da
tabase or other service that the client ultimately wants to access. Additional d
ata processing can happen on the server and extra tiers can be added if multiple
resources need to be accessed.
Multi-tier architectures offer several advantages. The primary advantage is the
ability to scale to larger numbers of clients. The transaction processing layer
makes this possible. It can keep a pool of open connections to the server, using
them as appropriate to serve client requests, saving the overhead of opening a
new connection for every client. Rather than overloading the server with queries
, the transaction processor can throttle back the load on the server by serializ
ing requests. Data processing can also be removed from the client and pushed clo
ser to the data. The second major advantage is the ability to cleanly subdivide
software development. Each layer performs a well-specified task that can be deve
loped without overly impacting the other layers.
Making Better Use of Garbage Collector
Imagine you have an enormous object serialized on disk that you are using in mem
ory, or that object is loaded in memory. You want to allow the garbage collector
(GC) clean memory when it needs it, right?. Imagine you are about to run out of
memory; do we really need to wait until no reference is made to our object?
Here´s a solution to allow the GC to clean memory: It is based on the Reference cl
ass placed into java.lang.ref.* packet. Actually, it is a subclass of Reference
called SoftReference. Here s how it works:
Object myObj = new myClass();---> legacy reference , everyday ref.
Now comes the trick :
SoftReference sref = new SoftReference(myObj);
At this point, we do have a soft reference pointing to the object and also a leg
acy ref pointing to the same object. We MUST erase this soft reference, because
there are between one and 1,000 refs that could make this technique unworlable:
myObj = null;
myObj = sref.get(); // we recover the soft reference.
The get method should be implemented to return the object, or a null if it was p
laced to disk, and we can do it as follows:
import java.land.ref.*;
We need an abstract to allow subclasses implements methods:
public abstract class SolutionBehaviour{
private SoftReference ref = new SoftReference(null);
public Object get()throws Exception{
This method implements the "get" way of saying if all was right or there was any
kind of error:
Object obj = ref.get();
if (obj = null) {
// If null get the object from disk
obj = getFromStorage();
ref=new SoftReference(obj);
}
return obj;
}
protected abstract Object getFromStorage() throws Exception;
}
Jose Antonio Alvarez Bermejo

Execute an External Program Without Using JNI


The secret lies in the Runtime class. Runtime contains the method exec, which ta
kes the basic form of:
Process exec(String command) or
Process exec(String[] comdarray) or
Process exec(String[] cmdarray, String[] envp, File dir)
Where command is the name of the executable, comdarray contains the exe name and
arguments, envp contains the environment variables, and File contains the file
name. exec returns the abstract object Process, whose getInputStream() and getOu
tputStream() can be used to collect I/O information on the running process.

Determine Whether a User Session Has Expired or Been Removed


Define a class, say SessionTimeoutIndicator, which implements the interface java
x.servlet.http.HttpSessionBindingListener. Next create a SessionTimeoutIndicator
object and add it to the user session. When the session is removed, the Session
TimeoutIndicator.valueUnbound() method will be called by the Servlet engine. You
can then implement valueUnbound() to do the required operation

Initializing Fields in Interfaces


Fields defined in interfaces are automatically public, static, and final. Being
final, they cannot be “blank”, but need to be initialized with constant or non-const
ant expressions. For example:
// Initializing interface fields with non-constant expressions
import java.util.*;
public interface RandomValues {
int rint = (int)(Math.random() * 10);
long rlong = (long)(Math.random() * 10);
float rfloat = (float)(Math.random() * 10);
double rdouble = Math.random() * 10;
}
Since the fields are static, they are initialized when the class is first loaded
. Here’s a simple test:
public class TestRandomValues {
public static void main(String[] args) {
System.out.println(RandomValues.rint);
System.out.println(RandomValues.rlong);
System.out.println(RandomValues.rfloat);
System.out.println(RandomValues.rdouble);
}
}
Note: The fields, as expected, are not part of the interface, but are stored in
the static storage area for that interface.
Weaving Threads
Java provides two ways to create and run a thread. You can implement the Runnabl
e interface or extend the Thread class. The Runnable interface defines a single
method run(). Consider the following example of a class that extends the Runnabl
e interface:
1. Class RunnableClass implements Runnable {
2. // Class attributes and methods
3.
4. public void run() {
5. // Code for the run() method
6. }
7. }
This thread can be started from another section of the program as follows:
8. RunnableClass rc = new RunnableClass();
9. Thread t = new Thread(rc);
10. rc.start();
11. // Other code
The start() method calls the run() method on Line 4. Program control returns to
Line 11 and simultaneously to Line 5. At this point two threads are executing.
The Thread class can also be extended directly, making the derived class a Runna
ble (Thread extends Runnable):
1. public class ThreadClass extends Thread {
2. public void run() {
3. // Code here
4. }
5. }
In this case, the thread may be started directly with a single call:
6. ThreadClass tc = new ThreadClass();
7. tc.start();
The Thread class has a lot more overhead (in terms of methods and attributes) an
d most of the time the developers only need to use the run() method. As a result
, implementing Runnable is the preferred way to use threads.

Using Proxy Classes in Java


The Proxy is one of the most common design patterns in circulation. Gamma et. al
. define the intent of the Proxy as: "Provide a surrogate or a placeholder for a
nother object to control access to it." The basic idea is that a class substitut
es for another class. In other words, a Proxy class provides an interface that r
eflects the interface of the class that it is substituting. In Java, a Proxy cla
ss must implement the same interface as the class that it is substituting.
A Proxy is usually associated with a client-server paradigm. The Server and the
Client classes implement the same interface. However, the Client only implements
stubs of methods where as the Server provides the actual implementations for th
e methods specified in the interface. For example:
1. public interface SomeIfc {
2. public void aMethod();
3. }
4.
5. public class Client implements SomeIfc {
6. Server s = new Server();
7. // Other attributes
8.
9. public void aMethod () {
10. s.aMethod();
11. }
12.
13. // Other methods
14.
15. }
16.
17. public class Server implements SomeIfc {
18.
19. // Class attributes
20. public aMethod () {
21. // Actual method implementation.
22. }
23.
24. // Other methods
25. }
Lines 1-3 define an interface called SomeIfc. It defines a single method called
aMethod(). Both the Client class (Lines 5-15) as well as the Server class (Lines
17-25) implement the interface SomeIfc. This ensures that aMethod() is availabl
e to the application that uses the Client class. On Line 6, the Client instantia
tes a new object of the type Server. In a real application, the code on Line 6 w
ould be replaced by code that gets the Client a reference to the Server across s
ome transport mechanism (like CORBA, sockets, RMI, etc.).
Any call made to aMethod() on the Client is "delegated" to the Server. An applic
ation using the Client class is shielded from the knowledge that there is a Serv
er in the picture. The Client acts as a Proxy to the Server. All access to the S
erver is only available via the Client.

===============================================================================
the main difference is conceptual - Aggregation says that an object is made up o
f other objects, and association says that they have a relationship, they know o
f each other, or they use each other in some way.
As far as programming, the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here, but the child making u
p the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships, going from 1-1, all the way up to *-*.
To clarify, when implementing aggregation Car and Tire, the Car has an aggregati
on to Tire, and the car has between 4-5 Tire (as an example, one is spare in the
trunk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car, you have to check that it has at least 4 and no mo
re than 5 tires, and when implementing the Tire, you have to at all times have a
reference to the Car (which means passing the Car reference in the constructor)
. Furthermore, when the Car reference is set to null, you have to pro grammatica
lly make sure that the Tire references are also set to null in case of Aggregati
on but if u model your system as Car just having an association to Tire, this mi
ght not necessarily be true.
Above answer was rated as good by the following members:
dasarishiva
April 20, 2007 07:09:29 \tab
rashmitambe \tab\tab Member Since: April 2007 Contribution: 3
RE: how to identify strong aggregation (composition) r...
In strong aggregation or composition a part entity cannot exist without the cont
aining whole entity in whole-part relationship.
For example. an university has multiple department. This a composition relations
hip between university and department entity. A department cannot exist on its o
wn with out the university.

Is this answer useful? Yes | No\tab\tab


November 02, 2007 12:09:26 \tab
Dusan B \tab\tab
RE: how to identify strong aggregation (composition) r...
Difference between association and aggregation (while programming implementation
for both):
the main difference is conceptual - Aggregation says that an object is made up o
f other objects and association says that they have a relationship they know of
each other or they use each other in some way.
As far as programming the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here but the child making up
the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships going from 1-1 all the way up to *-*.
To clarify when implementing aggregation Car and Tire the Car has an aggregation
to Tire and the car has between 4-5 Tire (as an example one is spare in the tru
nk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car you have to check that it has at least 4 and no mor
e than 5 tires and when implementing the Tire you have to at all times have a re
ference to the Car (which means passing the Car reference in the constructor). F
urthermore when the Car reference is set to null you have to pro grammatically m
ake sure that the Tire references are also set to null in case of Aggregation bu
t if u model your system as Car just having an association to Tire this might no
t necessarily be true.
Is this answer useful? Yes | No\tab Answer is useful 1 Answer is not useful 0\
tab Overall Rating: +1
September 30, 2008 21:28:56 \tab
jherna \tab\tab Member Since: September 2008 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
First let me say that aggregation is not composition or viseversa. The OOD conce
pt is "Association" and there are two types. Both are "Has a" relationships. One
is "Aggregation" (a strong "Has a") and the other is "Composition" (a weak "Has
a").
AGGREGATION EXAMPLE:
A Person class is an the "aggregating" class and the Person object "has a" heart
from the Heart class which is the "component" class. When the Person class obje
ct is collected by garbage collection so does the Heart class object associated
with that Person class object.
COMPOSITION EXAMPLE:
An Engine class is an the "aggregating" class and the Engine object "has a" carb
uator from the Carbuator class which is the "component" class. When the Engine c
lass object is collected by garbage collection the Carbuator class object associ
ated with that Engine class object does not go to the salvage yard. It can go to
another Engine object.
Is this answer useful? Yes | No\tab Answer is useful 0 Answer is not useful 2\
tab Overall Rating: -2
November 10, 2009 10:19:40 \tab
Neo_TCS \tab\tab Member Since: November 2009 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
Composition is the strongest form of association - not a Weak has a as said abov
e...
================================================================================
===========
Q: \tab
What are the callback methods in Entity beans?
A: \tab
The bean class defines create methods that match methods in the home interface a
nd business methods that match methods in the remote interface. The bean class a
lso implements a set of callback methods that allow the container to notify the
bean of events in its life cycle. The callback methods are defined in the javax.
ejb.EntityBean interface that is implemented by all entity beans.The EntityBean
interface has the following definition. Notice that the bean class implements th
ese methods.
public interface javax.ejb.EntityBean \{
\tab public void setEntityContext();
public void unsetEntityContext();
public void ejbLoad();
public void ejbStore();
public void ejbActivate();
public void ejbPassivate();
public void ejbRemove();
\} \tab
The setEntityContext() method provides the bean with an interface to the contain
er called the EntityContext. The EntityContext interface contains methods for ob
taining information about the context under which the bean is operating at any p
articular moment. The EntityContext interface is used to access security informa
tion about the caller; to determine the status of the current transaction or to
force a transaction rollback; or to get a reference to the bean itself, its home
, or its primary key. The EntityContext is set only once in the life of an entit
y bean instance, so its reference should be put into one of the bean instance's
fields if it will be needed later.
The unsetEntityContext() method is used at the end of the bean's life cycle befo
re the instance is evicted from memory to dereference the EntityContext and perf
orm any last-minute clean-up.
The ejbLoad() and ejbStore() methods in CMP entities are invoked when the entity
bean's state is being synchronized with the database. The ejbLoad() is invoked
just after the container has refreshed the bean container-managed fields with it
s state from the database. The ejbStore() method is invoked just before the cont
ainer is about to write the bean container-managed fields to the database. These
methods are used to modify data as it's being synchronized. This is common when
the data stored in the database is different than the data used in the bean fie
lds.
The ejbPassivate() and ejbActivate() methods are invoked on the bean by the cont
ainer just before the bean is passivated and just after the bean is activated, r
espectively. Passivation in entity beans means that the bean instance is disasso
ciated with its remote reference so that the container can evict it from memory
or reuse it. It's a resource conservation measure the container employs to reduc
e the number of instances in memory. A bean might be passivated if it hasn't bee
n used for a while or as a normal operation performed by the container to maximi
ze reuse of resources. Some containers will evict beans from memory, while other
s will reuse instances for other more active remote references. The ejbPassivate
() and ejbActivate() methods provide the bean with a notification as to when it'
s about to be passivated (disassociated with the remote reference) or activated
(associated with a remote reference).
================================================================================
===========
Q: \tab
Can Entity Beans have no create() methods?
A: \tab
Yes. In some cases the data is inserted NOT using Java application, so you may o
nly need to retrieve the information, perform its processing, but not create you
r own information of this kind.
================================================================================
===========
: \tab
What are transaction attributes?
A: \tab
The transaction attribute specifies how the Container must manage transactions f
or a method when a client invokes the method via the enterprise bean\rquote s ho
me or component interface or when the method is invoked as the result of the arr
ival of a JMS message. (Sun's EJB Specification) Below is a list of transactiona
l attributes:
1. NotSupported - transaction context is unspecified.
2. Required - bean's method invocation is made within a transactional context. I
f a client is not associated with a transaction, a new transaction is invoked au
tomatically.
3. Supports - if a transactional context exists, a Container acts like the trans
action attribute is Required, else - like NotSupported.
4. RequiresNew - a method is invoked in a new transaction context.
5. Mandatory - if a transactional context exists, a Container acts like the tran
saction attribute is Required, else it throws a javax.ejb.TransactionRequiredExc
eption.
6. Never - a method executes only if no transaction context is specified.
================================================================================
===========
What are transaction isolation levels in EJB?
A: \tab
1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a
DB(fast but not wise).
2. Transaction_read_committed- Guarantees that the data you are getting has been
committed.
3. Transaction_repeatable_read - Guarantees that all reads of the database will
be the same during the transaction (good for read and update operations).
4. Transaction_serializable- All the transactions for resource are performed ser
ial.
================================================================================
===========
what is the difference b/w EJB2.1 and EJB3.0?
EJB3.0
1. No need of Home Interface (EJBHome) but it is needed in EJB2.0
2. No more confusions to make an EJB remote or local it's the client which wo
uld decide and cast to appropriate.
3. Just write SINGLE simple Java class and annotate it to be Stateless/Statef
ul/Entity/MessageDriven.Container
4. No Deployment Descriptors MetaData Annotations are explored which is intro
duced in J2SE5.0
5. Forget all EJB life cycles.For example Entity bean life cycle in 3.0 is ne
w managed detached removed.
Ready to develop complex query inner/outer join with EJB3.0.
The main difference lies in the persistence In case of EJB 3.0 there is JPA J
ava persistence API which makes the mapping of EntityBeans with the database eas
y with the help of a service called as EntityManager.
Mapping is done with the help of annotations unlike in EJB2.0.
Home interfaces are eliminated.
Deployment descriptors are an option in EJB 3.0.
EJB3.0 also supports webservice client through SOAP and WSDl.
================================================================================
===========
What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
*
The spring container finds the bean\rquote s definition from the XML file
and instantiates the bean.
*
Using the dependency injection, spring populates all of the properties as
specified in the bean definition
*
If the bean implements the BeanNameAware interface, the factory calls setB
eanName() passing the bean\rquote s ID.
*
If the bean implements the BeanFactoryAware interface, the factory calls s
etBeanFactory(), passing an instance of itself.
*
If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
*
If an init-method is specified for the bean, it will be called.
*
Finally, if there are any BeanPostProcessors associated with the bean, the
ir postProcessAfterInitialization() methods will be called.
================================================================================
===========
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
* Configure Spring to manage your Actions as beans, using the ContextLoaderP
lugin, and set their dependencies in a Spring context file.
* Subclass Spring's ActionSupport classes and grab your Spring-managed beans
explicitly using a getWebApplicationContext() method.
================================================================================
===========
Package java.util.concurrent Description
Utility classes commonly useful in concurrent programming. This package includes
a few small standardized extensible frameworks, as well as some classes that pr
ovide useful functionality and are otherwise tedious or difficult to implement.
Here are brief descriptions of the main components. See also the locks and atomi
c packages.
Executors
Interfaces. Executor is a simple standardized interface for defining custom thre
ad-like subsystems, including thread pools, asynchronous IO, and lightweight tas
k frameworks. Depending on which concrete Executor class is being used, tasks ma
y execute in a newly created thread, an existing task-execution thread, or the t
hread calling execute(), and may execute sequentially or concurrently. ExecutorS
ervice provides a more complete asynchronous task execution framework. An Execut
orService manages queuing and scheduling of tasks, and allows controlled shutdow
n. The ScheduledExecutorService subinterface and associated interfaces add suppo
rt for delayed and periodic task execution. ExecutorServices provide methods arr
anging asynchronous execution of any function expressed as Callable, the result-
bearing analog of Runnable. A Future returns the results of a function, allows d
etermination of whether execution has completed, and provides a means to cancel
execution. A RunnableFuture is a Future that possesses a run method that upon ex
ecution, sets its results.
Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor prov
ide tunable, flexible thread pools. The Executors class provides factory methods
for the most common kinds and configurations of Executors, as well as a few uti
lity methods for using them. Other utilities based on Executors include the conc
rete class FutureTask providing a common extensible implementation of Futures, a
nd ExecutorCompletionService, that assists in coordinating the processing of gro
ups of asynchronous tasks.
Queues
The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scala
ble thread-safe non-blocking FIFO queue. Five implementations in java.util.concu
rrent support the extended BlockingQueue interface, that defines blocking versio
ns of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, P
riorityBlockingQueue, and DelayQueue. The different classes cover the most commo
n usage contexts for producer-consumer, messaging, parallel tasking, and related
concurrent designs. The BlockingDeque interface extends BlockingQueue to suppor
t both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provide
s an implementation.
Timing
The TimeUnit class provides multiple granularities (including nanoseconds) for s
pecifying and controlling time-out based operations. Most classes in the package
contain operations based on time-outs in addition to indefinite waits. In all c
ases that time-outs are used, the time-out specifies the minimum time that the m
ethod should wait before indicating that it timed-out. Implementations make a "b
est effort" to detect time-outs as soon as possible after they occur. However, a
n indefinite amount of time may elapse between a time-out being detected and a t
hread actually executing again after that time-out. All methods that accept time
out parameters treat values less than or equal to zero to mean not to wait at al
l. To wait "forever", you can use a value of Long.MAX_VALUE.
Synchronizers
Four classes aid common special-purpose synchronization idioms. Semaphore is a c
lassic concurrency tool. CountDownLatch is a very simple yet very common utility
for blocking until a given number of signals, events, or conditions hold. A Cyc
licBarrier is a resettable multiway synchronization point useful in some styles
of parallel programming. An Exchanger allows two threads to exchange objects at
a rendezvous point, and is useful in several pipeline designs.
Concurrent Collections
Besides Queues, this package supplies Collection implementations designed for us
e in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, Concurren
tSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads a
re expected to access a given collection, a ConcurrentHashMap is normally prefer
able to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferab
le to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchron
ized ArrayList when the expected number of reads and traversals greatly outnumbe
r the number of updates to a list.
The "Concurrent" prefix used with some classes in this package is a shorthand in
dicating several differences from similar "synchronized" classes. For example ja
va.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronize
d. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe
, but not governed by a single exclusion lock. In the particular case of Concurr
entHashMap, it safely permits any number of concurrent reads as well as a tunabl
e number of concurrent writes. "Synchronized" classes can be useful when you nee
d to prevent all access to a collection via a single lock, at the expense of poo
rer scalability. In other cases in which multiple threads are expected to access
a common collection, "concurrent" versions are normally preferable. And unsynch
ronized collections are preferable when either collections are unshared, or are
accessible only when holding other locks.
Most concurrent Collection implementations (including most Queues) also differ f
rom the usual java.util conventions in that their Iterators provide weakly consi
stent rather than fast-fail traversal. A weakly consistent iterator is thread-sa
fe, but does not necessarily freeze the collection while iterating, so it may (o
r may not) reflect any updates since the iterator was created.
Memory Consistency Properties
Chapter 17 of the Java Language Specification defines the happens-before relatio
n on memory operations such as reads and writes of shared variables. The results
of a write by one thread are guaranteed to be visible to a read by another thre
ad only if the write operation happens-before the read operation. The synchroniz
ed and volatile constructs, as well as the Thread.start() and Thread.join() meth
ods, can form happens-before relationships. In particular:
* Each action in a thread happens-before every action in that thread that co
mes later in the program's order.
* An unlock (synchronized block or method exit) of a monitor happens-before
every subsequent lock (synchronized block or method entry) of that same monitor.
And because the happens-before relation is transitive, all actions of a thread
prior to unlocking happen-before all actions subsequent to any thread locking th
at monitor.
* A write to a volatile field happens-before every subsequent read of that s
ame field. Writes and reads of volatile fields have similar memory consistency e
ffects as entering and exiting monitors, but do not entail mutual exclusion lock
ing.
* A call to start on a thread happens-before any action in the started threa
d.
* All actions in a thread happen-before any other thread successfully return
s from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend th
ese guarantees to higher-level synchronization. In particular:
* Actions in a thread prior to placing an object into any concurrent collect
ion happen-before actions subsequent to the access or removal of that element fr
om the collection in another thread.
* Actions in a thread prior to the submission of a Runnable to an Executor h
appen-before its execution begins. Similarly for Callables submitted to an Execu
torService.
* Actions taken by the asynchronous computation represented by a Future happ
en-before actions subsequent to the retrieval of the result via Future.get() in
another thread.
* Actions prior to "releasing" synchronizer methods such as Lock.unlock, Sem
aphore.release, and CountDownLatch.countDown happen-before actions subsequent to
a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition
.await, and CountDownLatch.await on the same synchronizer object in another thre
ad.
* For each pair of threads that successfully exchange objects via an Exchang
er, actions prior to the exchange() in each thread happen-before those subsequen
t to the corresponding exchange() in another thread.
* Actions prior to calling CyclicBarrier.await happen-before actions perform
ed by the barrier action, and actions performed by the barrier action happen-bef
ore actions subsequent to a successful return from the corresponding await in ot
her threads.
================================================================================
===========
d\sa200\sl276\slmult1\cf1\f1\fs28 What are the config files used for connecting
Java and Flex?\line\b Ans: \b0\line data-management-config.xml,\line messaging-c
onfig.xml,\line proxy-config.xml,\line remoting-config.xml,\line services-config
.xml\lined\cf0\f0\fs20
================================================================================
===========
Lets have a look on Javadoc tags
Tag \tab Description
@version \tab Shows the version number of a class or method.
@author \tab Shows the Developer
name
@return \tab Documents the return value. This tag should not be used for cons
tructors or methods defined with a void return type.
@deprecated \tab Marks a method as deprecated. Some IDEs will issue a compilat
ion warning if the method is called.
@see \tab Documents an association to another method or class.
@param \tab Defines a method parameter. Required for each parameter.
@throws \tab Documents an exception thrown by a method. A synonym for @except
ion introduced in Javadoc 1.2.
@since \tab Documents when a method was added to a class.
@exception \tab Documents an exception thrown by a method \emdash also see @
throws.
private \tab Displays all classes and members
use \tab It creates class and package usage pages
Windowtitle \tab It shows the window title of the document
Header \tab It includes for header text of the page
Footer \tab It includes footer text for the page
Bottom \tab It includes bottom text for the page
Package \tab Shows package classes and members
Protected \tab shows protected classes and members
Classpath \tab Helps to find user class files
noindex \tab doesn't provide the index
nohelp \tab doesn't provide the help link
notree \tab doesn't provide class hierarchy
================================================================================
===========
//Create Select Clause HQL
String SQL_QUERY ="Select insurance.
lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,insurance.
investementDate from Insurance insurance";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();)\{
Object[] row = (Object[]) it.next();
System.out.println("ID: " + row[0]);
System.out.println("Name: " + row[1]);
System.out.println("Amount: " + row[2]);
\}

================================================================================
===========
//Using from Clause
String SQL_QUERY ="from Insurance insurance";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();)\{
Insurance insurance=(Insurance)it.next();
System.out.println("ID: " +
insurance.getLngInsuranceId());
System.out.println("First
Name: " + insurance.getInsuranceName());
\}
================================================================================
===========
String SQL_QUERY = "select
count(*)from Insurance insurance group by
insurance.lngInsuranceId";
Query query =
sess.createQuery(SQL_QUERY);
for (Iterator it
= query.iterate(); it.hasNext();) \{
it.next();
count++;
\}
System.out.println("
Total rows: " + count);
sess.close();
================================================================================
===========
String SQL_QUERY = "select avg
(investementAmount) from Insurance insurance";
Query query = sess.createQuery(SQL_QUERY);
List list = query.list();
System.out.println("Average of
Invested Amount: " + list.get(0));
\}
================================================================================
===========
Criteria crit =
session.createCriteria(Insurance.class);
crit.add(Restrictions.like("
insuranceName", "%a%")); //Like condition
crit.setMaxResults(5); //
Restricts the max rows to 5
List insurances = crit.list();
for(Iterator it =
insurances.iterator();it.hasNext();)\{
Insurance insurance =
(Insurance) it.next();
System.out.println("
ID: " + insurance.getLngInsuranceId());
System.out.println("
Name: " + insurance.getInsuranceName());
\}
================================================================================
===========
Apache Axis2 Client code
In this section we will develop client code example to access the Hello World We
b service developed in the last section. In the last section we developed and de
ployed the Hello World Web service. In this section we will write the Web servic
e client code and call the web service.
Setting up the environment
In our first section of downloading and installing Axis 2 engine, we instructed
you to download the binary version of Apache Axis2. Now extract the binary versi
on(axis2-1.5.1-bin.zip) using any zip tool. After extracting the file into E:\
Axis2Tutorial (assuming your tutorial directory is E:\Axis2Tutorial), you will g
et a directory "E:\Axis2Tutorial\axis2-1.5.1-bin\axis2-1.5.1" which contains the
binary version of the Apache Axis2 engine. Now set the following environment va
riables:
a) AXIS2_HOME=E:\Axis2Tutorial\axis2-1.5.1-bin\axis2-1.5.1
b) Add E:\Axis2Tutorial\axis2-1.5.1-bin\axis2-1.5.1\bin into path
c) Add E:\Axis2Tutorial\axis2-1.5.1-bin\axis2-1.5.1\lib\* into CLASS_PATH
After making the above changes the wsdl2java.bat is available for generating the
client code calling Web service.
Generating the client code using wsdl2java.bat tool
Now create a new directory E:\Axis2Tutorial\Examples\HelloWorld\client and then
open dos prompt and go to same directory. Now generate the client code using fol
lowing command:
WSDL2Java.bat -uri http://localhost:8080/axis2/services/HelloWorldService?wsdl -
o client
Here is the output of above command.
E:\>cd E:\Axis2Tutorial\Examples\HelloWorld\client
E:\Axis2Tutorial\Examples\HelloWorld\client>WSDL2Java.bat -uri http://localhost:
8080/axis2/services/HelloWorldService?wsdl -o client
Using AXIS2_HOME: E:\Axis2Tutorial\axis2-1.5.1-bin\axis2-1.5.1
Using JAVA_HOME: E:\JDK\jdk1.6.0_03
Retrieving document at 'http://localhost:8080/axis2/services/HelloWorldService?w
sdl'.
The above command will generate a) HelloWorldServiceStub.java and b) HelloWorldS
erviceCallbackHandler.java into E:\Axis2Tutorial\Examples\HelloWorld\client\clie
nt\src\net\roseindia directory.
Now run cd to client/src directory.
cd client/src
Developing the code to call the service
Create the file Test.java into E:\Axis2Tutorial\Examples\HelloWorld\client\clien
t\src\net\roseindia directory. The code of Test.java file is as below:
package net.roseindia;
import net.roseindia.*;
import net.roseindia.HelloWorldServiceStub.SayHello;
public class Test {
public static void main(String[] args) throws Exception {
HelloWorldServiceStub stub = new HelloWorldServiceStub();
//Create the request
net.roseindia.HelloWorldServiceStub.SayHello request = new
net.roseindia.HelloWorldServiceStub.SayHello();
request.setArgs0("Deepak Kumar");
//Invoke the service
net.roseindia.HelloWorldServiceStub.SayHelloResponse response
= stub.sayHello(request);
System.out.println("Response : " + response.get_return());
}
}
Compiling and testing the Web service
Now go to E:\Axis2Tutorial\Examples\HelloWorld\client\client\src directory and w
ith the help of javac command compile the code.
E:\Axis2Tutorial\Examples\HelloWorld\client\client\src>javac net/roseindia/*.jav
a
Note: net\roseindia\HelloWorldServiceStub.java uses unchecked or unsafe operatio
ns.
Note: Recompile with -Xlint:unchecked for details.
To run the client type following command:
java net/roseindia/Test
Here is the output:
E:\Axis2Tutorial\Examples\HelloWorld\client\client\src>javac net/roseindia/*.jav
a
Note: net\roseindia\HelloWorldServiceStub.java uses unchecked or unsafe operatio
ns.
Note: Recompile with -Xlint:unchecked for details.
E:\Axis2Tutorial\Examples\HelloWorld\client\client\src>java net/roseindia/Test
log4j:WARN No appenders could be found for logger (org.apache.axis2.description.
AxisService).
log4j:WARN Please initialize the log4j system properly.
Response : Hello : Deepak Kumar
E:\Axis2Tutorial\Examples\HelloWorld\client\client\src>
The client appliction makes a call to Web service and in response Web services r
eturns the Hello : Deepak Kumar message
You have successfully tested your Web Service.
================================================================================
===========
Difference between association and aggregation (while programming implementation
for both):
the main difference is conceptual - Aggregation says that an object is made up o
f other objects, and association says that they have a relationship, they know o
f each other, or they use each other in some way.
As far as programming, the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here, but the child making u
p the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships, going from 1-1, all the way up to *-*.
To clarify, when implementing aggregation Car and Tire, the Car has an aggregati
on to Tire, and the car has between 4-5 Tire (as an example, one is spare in the
trunk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car, you have to check that it has at least 4 and no mo
re than 5 tires, and when implementing the Tire, you have to at all times have a
reference to the Car (which means passing the Car reference in the constructor)
. Furthermore, when the Car reference is set to null, you have to pro grammatica
lly make sure that the Tire references are also set to null in case of Aggregati
on but if u model your system as Car just having an association to Tire, this mi
ght not necessarily be true.
Above answer was rated as good by the following members:
dasarishiva
April 20, 2007 07:09:29
rashmitambe Member Since: April 2007 Contribution: 3
RE: how to identify strong aggregation (composition) r...
In strong aggregation or composition a part entity cannot exist without the cont
aining whole entity in 'whole-part' relationship.
For example. an university has multiple department. This a composition relations
hip between university and department entity. A department cannot exist on its o
wn with out the university.

Is this answer useful? Yes | No


November 02, 2007 12:09:26
Dusan B
RE: how to identify strong aggregation (composition) r...
Difference between association and aggregation (while programming implementation
for both):
the main difference is conceptual - Aggregation says that an object is made up o
f other objects and association says that they have a relationship they know of
each other or they use each other in some way.
As far as programming the main difference is in the multiplicities. Aggregation
parent can have * and any subset of multiplicities here but the child making up
the aggregation can only have one parent.
This is different from association where you can have any number of possible rel
ationships going from 1-1 all the way up to *-*.
To clarify when implementing aggregation Car and Tire the Car has an aggregation
to Tire and the car has between 4-5 Tire (as an example one is spare in the tru
nk) but in no case can a tire belong to two cars at the same time.
So when implementing the Car you have to check that it has at least 4 and no mor
e than 5 tires and when implementing the Tire you have to at all times have a re
ference to the Car (which means passing the Car reference in the constructor). F
urthermore when the Car reference is set to null you have to pro grammatically m
ake sure that the Tire references are also set to null in case of Aggregation bu
t if u model your system as Car just having an association to Tire this might no
t necessarily be true.
Is this answer useful? Yes | No Answer is useful 1 Answer is not useful 0
Overall Rating: +1
September 30, 2008 21:28:56
jherna Member Since: September 2008 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
First let me say that aggregation is not composition or viseversa. The OOD conce
pt is "Association" and there are two types. Both are "Has a" relationships. One
is "Aggregation" (a strong "Has a") and the other is "Composition" (a weak "Has
a").
AGGREGATION EXAMPLE:
A Person class is an the "aggregating" class and the Person object "has a" heart
from the Heart class which is the "component" class. When the Person class obje
ct is collected by garbage collection so does the Heart class object associated
with that Person class object.
COMPOSITION EXAMPLE:
An Engine class is an the "aggregating" class and the Engine object "has a" carb
uator from the Carbuator class which is the "component" class. When the Engine c
lass object is collected by garbage collection the Carbuator class object associ
ated with that Engine class object does not go to the salvage yard. It can go to
another Engine object.
Is this answer useful? Yes | No Answer is useful 0 Answer is not useful 2
Overall Rating: -2
November 10, 2009 10:19:40
Neo_TCS Member Since: November 2009 Contribution: 1
RE: how to identify strong aggregation (composition) relationship between classe
s and what is difference between association and aggregation(while programming i
mplementation of them)?
Composition is the strongest form of association - not a Weak has a as said abov
e...
================================================================================
===========
Q:
What are the callback methods in Entity beans?
A:
The bean class defines create methods that match methods in the home interface a
nd business methods that match methods in the remote interface. The bean class a
lso implements a set of callback methods that allow the container to notify the
bean of events in its life cycle. The callback methods are defined in the javax.
ejb.EntityBean interface that is implemented by all entity beans.The EntityBean
interface has the following definition. Notice that the bean class implements th
ese methods.
public interface javax.ejb.EntityBean {
public void setEntityContext();
public void unsetEntityContext();
public void ejbLoad();
public void ejbStore();
public void ejbActivate();
public void ejbPassivate();
public void ejbRemove();
}
The setEntityContext() method provides the bean with an interface to the contain
er called the EntityContext. The EntityContext interface contains methods for ob
taining information about the context under which the bean is operating at any p
articular moment. The EntityContext interface is used to access security informa
tion about the caller; to determine the status of the current transaction or to
force a transaction rollback; or to get a reference to the bean itself, its home
, or its primary key. The EntityContext is set only once in the life of an entit
y bean instance, so its reference should be put into one of the bean instance's
fields if it will be needed later.
The unsetEntityContext() method is used at the end of the bean's life cycle befo
re the instance is evicted from memory to dereference the EntityContext and perf
orm any last-minute clean-up.
The ejbLoad() and ejbStore() methods in CMP entities are invoked when the entity
bean's state is being synchronized with the database. The ejbLoad() is invoked
just after the container has refreshed the bean container-managed fields with it
s state from the database. The ejbStore() method is invoked just before the cont
ainer is about to write the bean container-managed fields to the database. These
methods are used to modify data as it's being synchronized. This is common when
the data stored in the database is different than the data used in the bean fie
lds.
The ejbPassivate() and ejbActivate() methods are invoked on the bean by the cont
ainer just before the bean is passivated and just after the bean is activated, r
espectively. Passivation in entity beans means that the bean instance is disasso
ciated with its remote reference so that the container can evict it from memory
or reuse it. It's a resource conservation measure the container employs to reduc
e the number of instances in memory. A bean might be passivated if it hasn't bee
n used for a while or as a normal operation performed by the container to maximi
ze reuse of resources. Some containers will evict beans from memory, while other
s will reuse instances for other more active remote references. The ejbPassivate
() and ejbActivate() methods provide the bean with a notification as to when it'
s about to be passivated (disassociated with the remote reference) or activated
(associated with a remote reference).
================================================================================
===========
Q:
Can Entity Beans have no create() methods?
A:
Yes. In some cases the data is inserted NOT using Java application, so you may o
nly need to retrieve the information, perform its processing, but not create you
r own information of this kind.
================================================================================
===========
:
What are transaction attributes?
A:
The transaction attribute specifies how the Container must manage transactions f
or a method when a client invokes the method via the enterprise bean’s home or com
ponent interface or when the method is invoked as the result of the arrival of a
JMS message. (Sun s EJB Specification) Below is a list of transactional attribu
tes:
1. NotSupported - transaction context is unspecified.
2. Required - bean s method invocation is made within a transactional context. I
f a client is not associated with a transaction, a new transaction is invoked au
tomatically.
3. Supports - if a transactional context exists, a Container acts like the trans
action attribute is Required, else - like NotSupported.
4. RequiresNew - a method is invoked in a new transaction context.
5. Mandatory - if a transactional context exists, a Container acts like the tran
saction attribute is Required, else it throws a javax.ejb.TransactionRequiredExc
eption.
6. Never - a method executes only if no transaction context is specified.
================================================================================
===========
What are transaction isolation levels in EJB?
A:
1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a
DB(fast but not wise).
2. Transaction_read_committed- Guarantees that the data you are getting has been
committed.
3. Transaction_repeatable_read - Guarantees that all reads of the database will
be the same during the transaction (good for read and update operations).
4. Transaction_serializable- All the transactions for resource are performed ser
ial.
================================================================================
===========
what is the difference b/w EJB2.1 and EJB3.0?
EJB3.0
1. No need of Home Interface (EJBHome) but it is needed in EJB2.0
2. No more confusions to make an EJB remote or local it s the client which wo
uld decide and cast to appropriate.
3. Just write SINGLE simple Java class and annotate it to be Stateless/Statef
ul/Entity/MessageDriven.Container
4. No Deployment Descriptors MetaData Annotations are explored which is intro
duced in J2SE5.0
5. Forget all EJB life cycles.For example Entity bean life cycle in 3.0 is ne
w managed detached removed.
Ready to develop complex query inner/outer join with EJB3.0.
The main difference lies in the persistence In case of EJB 3.0 there is JPA J
ava persistence API which makes the mapping of EntityBeans with the database eas
y with the help of a service called as EntityManager.
Mapping is done with the help of annotations unlike in EJB2.0.
Home interfaces are eliminated.
Deployment descriptors are an option in EJB 3.0.
EJB3.0 also supports webservice client through SOAP and WSDl.
================================================================================
===========
What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
*
The spring container finds the bean’s definition from the XML file and insta
ntiates the bean.
*
Using the dependency injection, spring populates all of the properties as
specified in the bean definition
*
If the bean implements the BeanNameAware interface, the factory calls setB
eanName() passing the bean’s ID.
*
If the bean implements the BeanFactoryAware interface, the factory calls s
etBeanFactory(), passing an instance of itself.
*
If there are any BeanPostProcessors associated with the bean, their post-
ProcessBeforeInitialization() methods will be called.
*
If an init-method is specified for the bean, it will be called.
*
Finally, if there are any BeanPostProcessors associated with the bean, the
ir postProcessAfterInitialization() methods will be called.
================================================================================
===========
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
* Configure Spring to manage your Actions as beans, using the ContextLoaderP
lugin, and set their dependencies in a Spring context file.
* Subclass Spring s ActionSupport classes and grab your Spring-managed beans
explicitly using a getWebApplicationContext() method.
================================================================================
===========
Package java.util.concurrent Description
Utility classes commonly useful in concurrent programming. This package includes
a few small standardized extensible frameworks, as well as some classes that pr
ovide useful functionality and are otherwise tedious or difficult to implement.
Here are brief descriptions of the main components. See also the locks and atomi
c packages.
Executors
Interfaces. Executor is a simple standardized interface for defining custom thre
ad-like subsystems, including thread pools, asynchronous IO, and lightweight tas
k frameworks. Depending on which concrete Executor class is being used, tasks ma
y execute in a newly created thread, an existing task-execution thread, or the t
hread calling execute(), and may execute sequentially or concurrently. ExecutorS
ervice provides a more complete asynchronous task execution framework. An Execut
orService manages queuing and scheduling of tasks, and allows controlled shutdow
n. The ScheduledExecutorService subinterface and associated interfaces add suppo
rt for delayed and periodic task execution. ExecutorServices provide methods arr
anging asynchronous execution of any function expressed as Callable, the result-
bearing analog of Runnable. A Future returns the results of a function, allows d
etermination of whether execution has completed, and provides a means to cancel
execution. A RunnableFuture is a Future that possesses a run method that upon ex
ecution, sets its results.
Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor prov
ide tunable, flexible thread pools. The Executors class provides factory methods
for the most common kinds and configurations of Executors, as well as a few uti
lity methods for using them. Other utilities based on Executors include the conc
rete class FutureTask providing a common extensible implementation of Futures, a
nd ExecutorCompletionService, that assists in coordinating the processing of gro
ups of asynchronous tasks.
Queues
The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scala
ble thread-safe non-blocking FIFO queue. Five implementations in java.util.concu
rrent support the extended BlockingQueue interface, that defines blocking versio
ns of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, P
riorityBlockingQueue, and DelayQueue. The different classes cover the most commo
n usage contexts for producer-consumer, messaging, parallel tasking, and related
concurrent designs. The BlockingDeque interface extends BlockingQueue to suppor
t both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provide
s an implementation.
Timing
The TimeUnit class provides multiple granularities (including nanoseconds) for s
pecifying and controlling time-out based operations. Most classes in the package
contain operations based on time-outs in addition to indefinite waits. In all c
ases that time-outs are used, the time-out specifies the minimum time that the m
ethod should wait before indicating that it timed-out. Implementations make a "b
est effort" to detect time-outs as soon as possible after they occur. However, a
n indefinite amount of time may elapse between a time-out being detected and a t
hread actually executing again after that time-out. All methods that accept time
out parameters treat values less than or equal to zero to mean not to wait at al
l. To wait "forever", you can use a value of Long.MAX_VALUE.
Synchronizers
Four classes aid common special-purpose synchronization idioms. Semaphore is a c
lassic concurrency tool. CountDownLatch is a very simple yet very common utility
for blocking until a given number of signals, events, or conditions hold. A Cyc
licBarrier is a resettable multiway synchronization point useful in some styles
of parallel programming. An Exchanger allows two threads to exchange objects at
a rendezvous point, and is useful in several pipeline designs.
Concurrent Collections
Besides Queues, this package supplies Collection implementations designed for us
e in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, Concurren
tSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads a
re expected to access a given collection, a ConcurrentHashMap is normally prefer
able to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferab
le to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchron
ized ArrayList when the expected number of reads and traversals greatly outnumbe
r the number of updates to a list.
The "Concurrent" prefix used with some classes in this package is a shorthand in
dicating several differences from similar "synchronized" classes. For example ja
va.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronize
d. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe
, but not governed by a single exclusion lock. In the particular case of Concurr
entHashMap, it safely permits any number of concurrent reads as well as a tunabl
e number of concurrent writes. "Synchronized" classes can be useful when you nee
d to prevent all access to a collection via a single lock, at the expense of poo
rer scalability. In other cases in which multiple threads are expected to access
a common collection, "concurrent" versions are normally preferable. And unsynch
ronized collections are preferable when either collections are unshared, or are
accessible only when holding other locks.
Most concurrent Collection implementations (including most Queues) also differ f
rom the usual java.util conventions in that their Iterators provide weakly consi
stent rather than fast-fail traversal. A weakly consistent iterator is thread-sa
fe, but does not necessarily freeze the collection while iterating, so it may (o
r may not) reflect any updates since the iterator was created.
Memory Consistency Properties
Chapter 17 of the Java Language Specification defines the happens-before relatio
n on memory operations such as reads and writes of shared variables. The results
of a write by one thread are guaranteed to be visible to a read by another thre
ad only if the write operation happens-before the read operation. The synchroniz
ed and volatile constructs, as well as the Thread.start() and Thread.join() meth
ods, can form happens-before relationships. In particular:
* Each action in a thread happens-before every action in that thread that co
mes later in the program s order.
* An unlock (synchronized block or method exit) of a monitor happens-before
every subsequent lock (synchronized block or method entry) of that same monitor.
And because the happens-before relation is transitive, all actions of a thread
prior to unlocking happen-before all actions subsequent to any thread locking th
at monitor.
* A write to a volatile field happens-before every subsequent read of that s
ame field. Writes and reads of volatile fields have similar memory consistency e
ffects as entering and exiting monitors, but do not entail mutual exclusion lock
ing.
* A call to start on a thread happens-before any action in the started threa
d.
* All actions in a thread happen-before any other thread successfully return
s from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend th
ese guarantees to higher-level synchronization. In particular:
* Actions in a thread prior to placing an object into any concurrent collect
ion happen-before actions subsequent to the access or removal of that element fr
om the collection in another thread.
* Actions in a thread prior to the submission of a Runnable to an Executor h
appen-before its execution begins. Similarly for Callables submitted to an Execu
torService.
* Actions taken by the asynchronous computation represented by a Future happ
en-before actions subsequent to the retrieval of the result via Future.get() in
another thread.
* Actions prior to "releasing" synchronizer methods such as Lock.unlock, Sem
aphore.release, and CountDownLatch.countDown happen-before actions subsequent to
a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition
.await, and CountDownLatch.await on the same synchronizer object in another thre
ad.
* For each pair of threads that successfully exchange objects via an Exchang
er, actions prior to the exchange() in each thread happen-before those subsequen
t to the corresponding exchange() in another thread.
* Actions prior to calling CyclicBarrier.await happen-before actions perform
ed by the barrier action, and actions performed by the barrier action happen-bef
ore actions subsequent to a successful return from the corresponding await in ot
her threads.
================================================================================
===========
What are the config files used for connecting Java and Flex?
Ans:
data-management-config.xml,
messaging-config.xml,
proxy-config.xml,
remoting-config.xml,
services-config.xml
================================================================================
===========
Lets have a look on Javadoc tags
Tag Description
@version Shows the version number of a class or method.
@author Shows the Developer
name
@return Documents the return value. This tag should not be used for con
structors or methods defined with a void return type.
@deprecated Marks a method as deprecated. Some IDEs will issue a compilatio
n warning if the method is called.
@see Documents an association to another method or class.
@param Defines a method parameter. Required for each parameter.
@throws Documents an exception thrown by a method. A synonym for @excep
tion introduced in Javadoc 1.2.
@since Documents when a method was added to a class.
@exception Documents an exception thrown by a method — also see @throws.
private Displays all classes and members
use It creates class and package usage pages
Windowtitle It shows the window title of the document
Header It includes for header text of the page
Footer It includes footer text for the page
Bottom It includes bottom text for the page
Package Shows package classes and members
Protected shows protected classes and members
Classpath Helps to find user class files
noindex doesn t provide the index
nohelp doesn t provide the help link
notree doesn t provide class hierarchy
================================================================================
===========
. Final class can not be a base or a child class of any other class.
================================================================================
===========
<generator> element
The <generator> method is used to generate the primary key for the new record. H
ere is some of the commonly used generators :
* Increment - This is used to generate primary keys of type long, short or int t
hat are unique only. It should not be used in the clustered deployment environme
nt.
* Sequence - Hibernate can also use the sequences to generate the primary key.
It can be used with DB2
, PostgreSQL, Oracle, SAP DB databases.
* Assigned - Assigned method is used when application code generates the primary
key.

================================================================================
===========
to specify to show the sql statement
<property name="show_sql">true</property>
================================================================================
===========
FLEX
======================
<mx:Application backgroundColor="#FFFFFF">
<mx:HTTPService id="srv" url="catalog.jsp"/>
<mx:DataGrid dataProvider="{srv.lastResult.catalog.product}" width="100%" height
="100%"/>
<mx:Button label="Get Data" click="srv.send()"/>
</mx:Application>
================================================================================
===========
<mx:Application backgroundColor="#FFFFFF">
<mx:WebService id="srv" wsdl="http://coenraets.org/services/ProductWS?wsdl" show
BusyCursor="true"/>

<mx:DataGrid dataProvider="{srv.getProducts.lastResult}" width="100%" height="10
0%">

<mx:columns>
<mx:DataGridColumn dataField="productId" headerText="Product Id"/>
<mx:DataGridColumn dataField="name" headerText="Name"/>
<mx:DataGridColumn dataField="price" headerText="Price"/>
</mx:columns>
</mx:DataGrid>
<mx:Button label="Get Data" click="srv.getProducts()"/>
</mx:Application>
================================================================================
===========
<mx:Application backgroundColor="#FFFFFF">
<mx:RemoteObject id="srv" destination="product"/>
<mx:DataGrid dataProvider="{srv.getProducts.lastResult}" width="100%" height="10
0%"/>
<mx:Button label="Get Data" click="srv.getProducts()"/>
</mx:Application>
================================================================================
===========
How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
* Configure Spring to manage your Actions as beans, using the ContextLoaderP
lugin, and set their dependencies in a Spring context file.
* Subclass Spring's ActionSupport classes and grab your Spring managed beans
explicitly using a getWebApplicationContext() method.

================================================================================
===========
What are the ways to access Hibernate using Spring ?
There are two approaches to Spring’s Hibernate integration:
* Inversion of Control with a HibernateTemplate and Callback
* Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSe
ssionFactory. The integration process is of 3 steps.
* Configure the Hibernate SessionFactory
* Extend your DAO Implementation from HibernateDaoSupport
* Wire in Transaction Support with AOP

25. What are Bean scopes in Spring Framework ?


The Spring Framework supports exactly five scopes (of which three are availab
le only if you are using a web-aware ApplicationContext). The scopes supported a
re listed below:
Scope Description
singleton

Scopes a single bean definition to a single object instance per Spring IoC conta
iner.
prototype

Scopes a single bean definition to any number of object instances.


request

Scopes a single bean definition to the lifecycle of a single HTTP request; that
is each and every HTTP request will have its own instance of a bean created off
the back of a single bean definition. Only valid in the context of a web-aware S
pring ApplicationContext.
session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid i
n the context of a web-aware Spring ApplicationContext.
global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typic
ally only valid when used in a portlet context. Only valid in the context of a w
eb-aware Spring ApplicationContext.
================================================================================
===========
Collwctions difficut points
===========================
ArrayList has no default size while vector has a default size of 10. when you wa
nt programs to run in multithreading environment then use concept of vector beca
use it is synchronized. But ArrayList is not synchronized so, avoid use of it in
a multithreading environment.

================================================================================
===========
Explain the usage of the keyword transient?
Answer: This keyword indicates that the value of this member variable does not h
ave to be serialized with the object. When the class will be de-serialized, this
variable will be initialized with a default value of its data type (i.e. zero f
or integers).
================================================================================
===========
How can you minimize the need of garbage collection and make the memory use more
effective?
Answer: Use object pooling and weak object references.
================================================================================
===========
Question What is the difference between sleep(), wait() and suspend()?
Derived from A question posed by Venkata Reddy Vajrala
Topics Programming:Concepts:Threads
Author Ingo Proetel
Created May 10, 2000 Modified May 17, 2000
Answer
Thread.sleep() sends the current thread into the "Not Runnable" state for some a
mount of time. The thread keeps the monitors it has aquired -- i.e. if the threa
d is currently in a synchronized block or method no other thread can enter this
block or method. If another thread calls t.interrupt() it will wake up the sleep
ing thread.
Note that sleep is a static method, which means that it always affects the curre
nt thread (the one that is executing the sleep method). A common mistake is to c
all t.sleep() where t is a different thread; even then, it is the current thread
that will sleep, not the t thread.
t.suspend() is deprecated. Using it is possible to halt a thread other than the
current thread. A suspended thread keeps all its monitors and since this state i
s not interruptable it is deadlock prone.
object.wait() sends the current thread into the "Not Runnable" state, like sleep
(), but with a twist. Wait is called on a object, not a thread; we call this obj
ect the "lock object." Before lock.wait() is called, the current thread must syn
chronize on the lock object; wait() then releases this lock, and adds the thread
to the "wait list" associated with the lock. Later, another thread can synchron
ize on the same lock object and call lock.notify(). This wakes up the original,
waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the
active thread does not need a direct pointer to the sleeping thread, but only t
o the shared lock object.
[This answer was edited; the original answer was clear but I felt I should expan
d on some points; please blame me, not Ingo, for any errors. -Alex]
Comments and alternative answers

Strange problem of using wait() and sleep() to suspend a single thread.


Carfield Yim, Dec 4, 2001 [replies:2]
I have write a simple mobile agents clients that continuously request a server f
or thousands time to do some testing. For testing propose, I need there is a ran
dom time delay between each request. At first I use the following code to do:
synchronized(this)
{
for(int i=0; i<Integer.MAX_VALUE; i++)
{
String fileName = "file"+(int)(r
andom.nextGaussian()*100);
print("sending message"+fileName
);
proxy.sendAsyncMessage(new Messa
ge("request", fileName));
wait( (long)( Math.abs(random.ne
xtGaussian()*1000) ) );
}
}
However, the mobile agents hing after ~7000 request. If I change wait() to Threa
d.sleep(), seen there is no this problem. (May be I need more testing). Can anyo
ne tell me what is the problem when using wait()? As there is only one thread of
client, no other thread access it and it don t share common resource with other
thread.
Is this item helpful? yes no Previous votes Yes: 1 No: 0
Re[2]: Strange problem of using wait() and sleep() to suspend a single thread.
kishore nerella, Aug 31, 2009
Thread.sleep(long milliseconds): sends the current thread into Non-Runnable stat
e for the specified amount of time. But, this doesn’t cause the thread to loose ow
nership of the acquired monitors. So, if the current thread is into a synchroniz
ed block/method, then no other thread will be able to enter that block/method. T
his method throws ‘InterruptedException’ if another thread interrupts it. There is a
nother variant of the ‘sleep()’ method as well where it accepts two arguments – one, l
ong milliseconds, and second, int nanoseconds. Evidently, it causes the current
thread to sleep for the specified number of milliseconds plus the specified numb
er of nanoseconds. The second argument ‘int nanoseconds’ can acquire a value of the
range 0-999999. Another noticeable difference between the two variants is that s
leep(long milliseconds, int nanoseconds) throws an IllegalArgumentException if e
ither the value of milliseconds is negative or the value of nanoseconds is not i
n the range 0-999999. As is the case with the first variant, it throws Interrupt
edException is another thread interrupts it. Common Error: both these methods ar
e static, so even if you try to call ‘t.sleep(…)’ on a different thread, it’ll be called
on the current thread only and not on the ‘t’ thread. In fact, one should avoid cal
ling any static method on an object reference. wait() method: There are three va
riants of this method in the ‘Object’ class:- public final void wait(long timeout) p
ublic final void wait(long timeout, int nanoseconds) public final void wait() Al
l the three methods throw InterruptedException & IllegalMonitorStateException. T
he first two may also throw IllegalArgumentException. The wait() method also sen
ds the current thread into Non-Runnable state like the sleep() method. But, the
difference between the two is that in case of ‘wait()’ the locks are released before
going into Non-Runnable state. Another apparent difference is that ‘wait()’ is an i
nstance method, while sleep() is a static method. The method ‘wait()’ should be call
ed for an object only when the current thread has already acquired lock for that
object. This causes the current thread to wait either another thread invokes th
e ‘notify()’ method or the ‘notifyAll()’ method for this object, or a specified amount o
f time has elapsed and after that the thread starts participating in thread sche
duling process to acquire the monitor of the object to proceed further. The wait
() method causes the current thread to place itself in the wait set for this obj
ect and then to relinquish any and all synchronization claims on this object. Af
ter the execution of this method invocation, the thread becomes disabled for any
scheduling purposes and lies dormant until one of the following things happen:-
Any other thread invokes ‘notify()’ method this object and the thread under conside
ration is arbitrarily chosen as the thread to be awakened. Any other thread invo
kes ‘notifyAll()’ for this object. Any other thread interrupts the thread under cons
ideration. The specified amount of time has elapsed (in case first two variants
of wait() are used) After any of the four above mentioned events happens, the th
read is removed from the wait set for this object and re-enabled for thread sche
duling. It’ll compete for the rights to synchronize on the object in an usual mann
er and it’ll keep doing this until it acquires control on the object and gains all
the synchronization claims on the object, which it had acquired at the time of ‘w
ait()’ invocation. This means that after the return from wait() method, the synchr
onization state of object and of the thread will be exactly the same as it was b
efore the wait() invocation.

================================================================================
===========
================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========
================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

================================================================================
===========

}


You might also like