Professional Documents
Culture Documents
===============
Race Condition:
Semaphone in
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.
threadA.start();
threadB.start();
}
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?
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.
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
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.
}
class TestThread11 implements Runnable{
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?
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.
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.
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
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.
say if the error JSP page wants to know the name of the captured exception class
, it can use the following scriptlet for that:-
Servlets and custom tags may access the captured exception object by calling the
method PageContext.getError().
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).
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:-
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.
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?
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?
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?
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
Share/Save/Bookmark
Example:
//Connecting to the data source
Connection con = DriverManager.getConnection("url", "userid","password");
//preparing SQL statement
Statement stmt = con.createStatement();
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
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
Share/Save/Bookmark
Share/Save/Bookmark
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
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
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
Share/Save/Bookmark
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
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.
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
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
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
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
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
Share/Save/Bookmark
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
Share/Save/Bookmark
Externalizable in Java
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
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
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
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.
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.
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
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)
4E/T = 4(E+T)/3T
=> E = (E+T)/3
=> 3E = E + T
=> T = 2E
X/Y = 4E/2E
=> X/Y = 2
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
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
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.
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
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.).
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.
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.
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
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.
Share/Save/Bookmark
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
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."
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
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.
Share/Save/Bookmark
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
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
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
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.
Why ESB?
Share/Save/Bookmark
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
Share/Save/Bookmark
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.
Why Services?
* Platform Independence
* Interoperatability
* Faster Development
* Easier to maintain/upgrade with least down-time
* Integration
* Modular Approach
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.)
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
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.
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
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
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 :-)"
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"
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
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.
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).
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
Share/Save/Bookmark
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?
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
* 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?
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?
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.).
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.
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.
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();
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.
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).
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.
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.
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.
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).
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.
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.
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.
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.
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).
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.
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
=================================================================
================================================================================
===========
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.
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
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
===============================================================================
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.
================================================================================
===========
//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.
================================================================================
===========
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
Scopes a single bean definition to a single object instance per Spring IoC conta
iner.
prototype
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
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
================================================================================
===========
}