You are on page 1of 136

ALL IN ONE FAQ

Language:
1) What are the differences between the == operator and the equals() method?
Well, first off, == is a fundamental operator in the language. The result type of the
epression is a boolean. !or comparing boolean types, it compares the operands for the same
truth "alue. !or comparing reference types, it compares the operands for the same reference
"alue (i.e., refer to the same ob#ect or are both null). !or numeric types, it compares the
operands for the same integer "alue or equi"alent floating point "alues.
$n contrast, equals() is an instance method which is fundamentally defined by the
java.lang.Object class. This method, by con"ention, indicates whether the recei"er
ob#ect is %equal to% the passed in ob#ect. The base implementation of this method in the
&b#ect class chec's for reference equality. &ther classes, including those you write,
may o"erride this method to perform more speciali(ed equi"alence testing.
)) *ow can $ force garbage collection to ta'e place?

+trictly, you can,t force it.
-ou can, howe"er, call System.gc(), which is a %hint% to the runtime engine that now
might be a good time to run the ./. +ome implementations ta'e that hint to heart and
some don,t.
0) When should $ use an interface instead of an abstract class?

There are two primary aes of %inheritance% in ob#ect1oriented languages li'e 2a"a.
%$mplementation% inheritance is where the sub1class inherits the actual code implementation
from the parent. %$nterface% inheritance is where the %sub1class% adheres to the public interface
of the %parent%.
3las, 2a"a actually mies the two notions together a bit... 2a"a interfaces are nice and
clean 11 when you %implement% an interface, you are stipulating that your class adheres
to the %contract% of the interface that you specified. 2a"a class inheritance isn,t so clean
11 when you sub1class in 2a"a you are getting both the code inheritance but you are also
stipulating that your sub1class adheres to the %contract% of the interface of the parent
class.
3bstract classes in 2a"a are #ust li'e regular 2a"a classes but with the added constraint
that you cannot instantiate them directly. $n terms of that added constraint, they are
basically classes which don,t actually implement all of the code specified by their
%contract%.
Page 1 of 136
+o, it,s generally considered good && practice to specify the %contract% which you want
to adhere to "ia 2a"a interfaces. Then use normal 2a"a class inheritance primarily for
code reuse purposes. 4se abstract 2a"a classes when you want to pro"ide some
standard base code but want5need to force the user,s of your class to complete the
implementation (i.e., you create a s'eleton implementation and the sub1classes must
flesh it out).
6) What are the differences between instance and class "ariables?

$nstance "ariables ha"e separate "alues for each instance of a class. /lass
"ariables maintain a single shared "alue for all instances of the class, e"en if no
instance ob#ect of that class eists.
-ou would use the static 'eyword to change an instance "ariable into a class
"ariable.
7oth instance and class "ariables are declared at the class le"el, not within
methods8
public class !oo 9
static pri"ate int count: 55 class "ariable
+tring name: 55 instance "ariable
pri"ate "oid 7ar() 9
int half/ount: 55 local "ariable
;
;
<ote also that classes are loaded by classloaders therefore class "ariables are
unique on a per1classloader basis.
=) What is an o"erloaded method?

&"erloaded methods are multiple methods in the same class that share the same
name but ha"e different parameter lists. &"erloaded methods cannot ha"e the
same parameter lists with different return types.
>) What is a final class?

When you declare a class to be final, it can ne"er be subclassed. This is usually
done for security or performance reasons.
public final class ?ath 9
55 ...
;
Page 2 of 136
@) What is a final method?

When you declare a method to be final, it can ne"er be o"erridden in subclasses.
This is usually done for security or performance reasons, pro"iding additional
information to the 2$T compiler or *ot+pot. &ne word of caution 11 ma'ing
methods final restricts later design decisions.
A) Why do $ not ha"e to import the classes in the #a"a.lang pac'age?

The classes in the #a"a.lang pac'age are so important that the compiler implicitly
imports all the classes there. This ensures classes in the unnamed pac'age are
not accidently used instead of the 'ey classes and interfaces.
B) /an $ o"erride a method that doesn,t throw eceptions with one that does?

&"erriding methods cannot change the signature of the o"erridden method. 3ll
eceptions are included in the signature of the method ecept for
CunTimeDception and it,s subclasses. +o, the only eceptions you may add to
an o"erriding method must be a (sub1class of) CunTimeDception.
1E) /an $ restart a stopped thread?

$n short, no. &nce a thread is stopped, it cannot be restarted. Feep in mind
though that the use of the stop() method of Thread is deprecated and should be
a"oided.
11) *ow do $ ha"e one thread wait for another thread to finish before continuing?

-ou can wait for a thread to finish by calling its #oin() method. !or instance, in the
following code, the current thread will wait until thread) finishes before printing
Gone.
thread).start():
55 do more stuff here
thread).#oin():
+ystem.out.println(%Gone%):
1)) What is a method,s signature?

The signature of a method is the combination of the method,s name along with
the number and types of the parameters (and their order).
Page 3 of 136
10) Why does %float f = 0.=:% generate a compile1time error?

The constant "alue 3.5 is recogni(ed by the compiler to be a double rather
than a float. -ou must place an f after the 0.= for it to be recogni(ed as a
floating point constant "alue8
float f = 0.=f:
16) What is the difference between the H and HH operators?

$t depends on the type of the arguments...
!or integer arguments, the single ampersand (%H%)is the %bit1wise 3<G% operator.
The double ampersand (%HH%) is not defined for anything but two boolean
arguments.
!or boolean arguments, the single ampersand constitutes the (unconditional)
%logical 3<G% operator while the double ampersand (%HH%) is the %conditional
logical 3<G% operator. That is to say that the single ampersand always e"aluates
both arguments whereas the double ampersand will only e"aluate the second
argument if the first argument is true.
!or all other argument types and combinations, a compile1time error should
occur.
1=) *ow can $ cast an &b#ect reference to an array reference?

Iretty much #ust li'e any other cast8
?y3rrayCef = (?y3rrayType JK) ob#ectCef:
1>) *ow is 2a"a,s %byte code% different from other codes (li'e source code, nati"e code, etc.)?

2a"a,s byte code is what the typical 2a"a compilers create in the .class files. $t is
a binary language that is defined for the 2a"a Lirtual ?achine (2L?). The 2L? is
the abstract machine which runs the byte codes (analogously to how an $ntel
AE0A> runs .ob# files).
1@) /an an anonymous class ha"e static members?

Page 4 of 136
With one eception, anonymous classes cannot contain static fields, methods, or
classes. The only static things they can contain are static final constants.
1A) When $ create anonymous classes, what access modifier do they get?

3nonymous classes get the default, unnamed access modifier. -ou cannot ma'e
them pri"ate, protected, public, or static.
1B) *ow do $ create a constructor for an anonymous class?

+ince anonymous classes don,t ha"e names, you cannot create a constructor by
#ust using the name of the class. What you can do instead is to use an %instance
initiali(er%. $nstance initiali(ers basically loo' li'e methods with no names or
return "alues8
3ctionMistener listener = new 3ctionMistener 9
9
+ystem.out.println(%$nstance $nitiali(er%):
;
public "oid actionIerformed(3ctionD"ent e"ent) 9
...
;
;:
)E) When should $ use a %pri"ate% constructor?
The most common use that $ see for private (and protected)
constructors is in implementing singletons and some types of ob#ect factories.
7asically, you use a static method to manage the creation of one (or more)
instances of the class.
)1) $,m trying to use an 3WT Mist and the Mist collection in my program. *ow do $ o"ercome the
class name conflict?

$n such a case of name conflict8
$f you need only one definition but your type1import1on1demand (using import
.yyy.N:) causes the conflict, use eplicit import for the reference you need.
import #a"a.awt.N:
import #a"a.util.Mist: 55 if you need this Mist in your program.
$f you need both in the same 2a"a file, you will ha"e to eplicitly refer at least
one.
Page 5 of 136
import #a"a.awt.N:
import #a"a.util.Mist: 55 your can use %Mist% for this one.
....
#a"a.awt.Mist my3wtMist = new #a"a.awt.Mist():
Mist my4tilMist = new Mist():
!or clarity, $ would suggest to eplicitly manage both in that case.
))) *ow can $ do a deep clone of an ob#ect?

The default5con"entional beha"ior of clone() is to do a shallow copy. -ou can
either o"erride clone() to do a deep copy or pro"ide a separate method to do a
deep clone.
The simplest approach to deep cloning is to use 2a"a seriali(ation, where you
seriali(e and deseriali(e the ob#ect and return the deseriali(ed "ersion. This will
be a deep copy5clone, assuming e"erything in the tree is seriali(able. $f
e"erything is not seriali(able, you,ll ha"e to implement the deep cloning beha"ior
yourself.
3ssuming e"erything is seriali(able, the following should create a complete deep
copy of the current class instance8
7yte3rray&utput+tream baos = new 7yte3rray&utput+tream():
&b#ect&utput+tream oos = new &b#ect&utput+tream(baos):
oos.write&b#ect(this):
7yte3rray$nput+tream bais = new 7yte3rray$nput+tream(baos.to7yte3rray()):
&b#ect$nput+tream ois = new &b#ect$nput+tream(bais):
&b#ect deep/opy = ois.read&b#ect():
)0) What are the differences between the built1in, primiti"e types (li'e int) and the equi"alent,
non1primiti"e ob#ect1wrapper classes (li'e $nteger)?

The elemental types (int, long etc.) are fundamental parts of the 2a"a language 1
they,re reser"ed words. They directly represent a quantity, a character, etc.
The #a"a.lang classes (e.g. Loid, $nteger, Mong etc.) ser"e two functions 1 first,
they pro"ide utility methods (generally static to those classes) for doing
commonplace tas's li'e turning an integer into a +tring and "ice "ersa.
The second use for the #a"a.lang classes is as a wrapper for the elemental types
1 this is needed because 2a"a represents all collections (other than arrays) in
terms of #a"a.lang.&b#ect 1 so e.g., a Lector can only contain ob#ects, not
elemental types. $f you wanted a Lector or *ashtable of ints, you,d ha"e to wrap
Page 6 of 136
each int in a #a"a.lang.$nteger, and then unwrap the int when you retrie"ed "alues
from the collection.
Dqually, if you wanted to define a method that returned either a +tring or an int,
you would define the function as returning a #a"a.lang.&b#ect: and then in
practice you,d return either a #a"a.lang.+tring or a #a"a.lang.$nteger, as
appropriate.
)6) $n the main method of a class (or any static method), how can $ find out what class $ am in?

To get the Class ob#ect associated with that class, you ha"e to reference the
name of the class directly and use the .class 'eyword. $.e., if your class is
named Foo use Foo.class to get the Class ob#ect for Foo.
)=) *ow do $ get a list of the files in a .(ip file from 2a"a?

-ou can get a java.util.Enumeration of java.util.ip.!ipEntry
ob#ects by using the java.util.ip.!ipFile.entries() method.
)>) What is a 2$T compiler?

3 Just-In-Time compiler is one way to implement the 2a"a Lirtual ?achine.
Cather than the typical, pure interpreter, a 2$T compiler will, on demand, compile
the platform independent 2a"a byte codes into platform specific eecutable code,
in real1time. The first time through, the byte codes are compiled before being
eecuted. !uture passes will use a cached "ersion of the compiled code. This
tends to result in a performance increase of 1E11EE times, depending upon the
tas' at hand, o"er purely interpreted byte codes.
)@) What,s a .#ar file?

3 23C file or 2a"a 3Cchi"e is a way of bundling multiple files together as a single
file. Mi'e a O$I file, they support compression and retain the directory structure of
the files. They can be used for deli"ering things li'e 2a"a7eans and 3pplets, and
usually include support files li'e image and sound files, in addition to the actual
2a"a classes. $n addition, they can be digitally signed so a user can grant
pri"ileges to allow the software to perform operations not normally permitted from
untrusted software.
To create a 23C file, use the jar tool that comes with the 2GF.
)A) What are the differences between casting to +tring, using the to+tring() method, and using
the +tring."alue&f() method?

Page 7 of 136
/asting only transforms the reference to the ob#ect from one type to another.
/asting does nothing to the underlying ob#ect itself. The compiler and5or the
runtime engine will "erify the fact that the reference that you,re casting to a
reference to a +tring is, in fact, referring to an ob#ect which is (type compatible
with) a +tring.
The +tring."alue() method allows for the creation of a +tring representation of the
built1in, primiti"e data types such as int, boolean, float, etc.
The .toString() method is a method which all 2a"a classes inherit from the
java.lang.Object root class (and which many classes o"erride). The
.toString() method of each class is supposed to create an appropriate
String representation of ob#ects of that class.
)B) What is the difference between a 2a"a compiler and a 2a"a interpreter?

Typically, when used in that generic manner, the term Java compiler refers to a
program which translates 2a"a language source code into the 2a"a Lirtual
?achine (2L?) bytecodes. The term Java interpreter refers to a program which
implements the 2L? specification and actually eecutes the bytecodes (and
thereby running your program).
0E) Why are the methods wait() and notify() defined in the &b#ect class when they are used
with Threads?

The wait() and notify() methods are ob#ect1specific. The wait() method suspends
the current thread of eecution, and tells the ob#ect to 'eep trac' of the
suspended thread. The notify() method tells the ob#ect to wa'e up the suspended
threads that it is currently 'eeping trac' of. +ince wait() and notify() are ob#ect
specific, they must be used within code that is synchroni(ed on the ob#ect in
question.
$t is also important to use state "ariables when using "ait() and notify(), as
threads can be wo'en up by conditions other than notify().
suspend() is similar to "ait() but does not add the thread to an ob#ect,s wait
list.
01) *ow to run a batch file5nati"e application from 2a"a?

4se Cuntime.eec(+tring pathTo7atch!ile).
0)) What are the differences between %2L?% and %2CD%?

Page 8 of 136
Technically, the term %2L?% specifies the Java Virtual Machine. $.e., the %2L?% is
the definition of the abstract, stac'1based computational engine used to eecute
2a"a bytecodes. The term %2CD% stands for the Java Runtime Environment (if
you follow +un,s nomeclature) or, interchangeably, Java Runtime Engine. $.e., a
2CD is a specific implementation of the the 2L?, including the core libaries.
3las, in practice, many people use %2L?% for both cases. +o, be careful to
understand the contet that people are tal'ing about when using the term %2L?%
to distinguish between the abstract definition and a specific implementation.
00) What,s the difference between %2GF% and %2CD%?

The %2GF% is the Java Development Kit. $.e., the 2GF is bundle of software that
you can use to de"elop 2a"a based software. The %2CD% is the Java Runtime
Environment. $.e., the 2CD is an implementation of the 2a"a Lirtual ?achine
which actually eecutes 2a"a programs.
Typically, each 2GF contains one (or more) 2CD,s along with the "arious
de"elopment tools li'e the 2a"a source compilers, bundling and deployment
tools, debuggers, de"elopment libraries, etc.
06) What are the differences between checed and uncheced eceptions?

3 chec'ed eception is any subclass of Dception (or Dception itself), ecluding
class CuntimeDception and its subclasses.
?a'ing an eception chec'ed forces client programmers to deal with the
possibility that the eception will be thrown. eg, $&Dception thrown by
#a"a.io.!ile$nput+tream,s read() method
4nchec'ed eceptions are CuntimeDception and any of its subclasses. /lass
Drror and its subclasses also are unchec'ed.
With an unchec'ed eception, howe"er, the compiler doesn,t force client
programmers either to catch the eception or declare it in a throws clause. $n
fact, client programmers may not e"en 'now that the eception could be thrown.
eg, +tring$nde&ut&f7oundsDception thrown by +tring,s char3t() method.
/hec'ed eceptions must be caught at compile time. Cuntime eceptions do not
need to be. Drrors often cannot be, as they tend to be unreco"erable.
0=) What are mutable and immutable ob#ects in 2a"a?

3s per the dictionary, mutable ob#ects are ob#ects which can change their "alues
and immutable ob#ects are ob#ects which cannot ha"e their "alues changed.
Page 9 of 136
0>) $s it possible to start an application (from command line) from a method other than main?

<o, it is not possible to start an application from a method other than main, as the
runtime system will loo' for a method i.e., public static void main. $f the
method is not found we get an error by name #a"a.lang.<o+uch?ethodDrror.
0@) Why can,t $ declare a static method in an interface?

7ecause all methods declared in an inter!ace are (implicitly) also %abstract%
methods since, by definition, they do not define the (implementation of) the
method.
0A) What,s the difference between 2a"a+cript and 2a"a?

2a"a+cript is an ob#ect1oriented scripting language that allows you to create
dynamic *T?M pages, allowing you to process5"alidate input data and maintain
data, usually within the browser. &riginally created by <etscape for use with their
<a"igator browser, ?icrosoft re"erse engineered the technology, added their
own "arients and defined 2+cript.
&n the other hand, %2a"a% is a programming language, core set of libraries, and
"irtual machine platform that allows you to create compiled programs that run on
nearly e"ery platform, without distribution of source code in its raw form or
recompilation. While the two share part of their names in common, they are really
two completely different programming languages5models5platforms. -es, they
can communicate with each other through technologies li'e Mi"e+cript. *owe"er,
you should really consider them as two completely separate technologies.
0B) *ow can $ determine if a file is a 2a"a class file?

$f the first four bytes of a file are not $%C&FE'&'E then you do not ha"e a 2a"a
class file. This testing is done as part of the first pass of the 2a"a "erifier.
6E) What are the differences between I3T* and /M3++I3T* en"ironment "ariables?

The I3T* en"ironment "ariable is typically something that the operating system
uses to find eecutable files. +ee the system manuals for your platform for more
information.
The /M3++I3T* en"ironment "ariable is typically something that
implementations of the 2a"a Lirtual ?achine (2L?) use to find 2a"a class files.
Page 10 of 136
61) /an a 2a"a class be static?

-es and no. The static modifier is only applicable to so1called member classes 11
i.e., classes which are directly enclosed within another class.
6)) What does it mean to o"erride a method?

$f a subclass shares a method name with identical arguments and return type, it
o"errides the method of its superclass. &"erridden methods may differ in
eceptions thrown by throwing a more specific eception type or none at all.
60) *ow do $ find out how much system memory is a"ailable in my system?

The Cuntime class has two methods to help you determine memory resources8
free?emory() and total?emory(). The free?emory() method reports the free
bytes in 2a"a,s memory space. The total?emory() reports the total bytes in
2a"a,s memory space.
66) What is the difference between the stream to'eni(er and string to'eni(er?
-ou can thin' of the +tringTo'eni(er as a speciali(ed form of +treamTo'eni(er, where
each to'en that is returned is a +tring. Gepending upon what you want to do with the
resultant to'ens and5or how comple of a parse #ob you want to deal with lets you
decide which to use.
The +tringTo'eni(er parses a string into a series of to'ens. $t is then your responsibility
to figure out what each to'en returned is, beyond the definition of a to'en separated by
delimiters. 4sually, you #ust treat things as words when using +tringTo'eni(er.
&n the other hand, a Stream(o)enier allows you to as' is the net to'en a number,
word, quoted string, end1of1file, end1of1line, comment, or whitespace. $n this case, the
Stream(o)enier is smarter, though can be considerably harder to use.
6=) /an $ o"erride the equals() method to ta'e a parameter other than &b#ect?

$f you are trying to o"erride a method with a different argument list, that isn,t o"erriding,
but o"erloading. $n order for the method to be properly o"erridden, and thus called
appropriately, the subclass method signature must eplicitly match that of the
superclass. $n the case of equals() that means the return type must be boolean and the
argument must be &b#ect.
Page 11 of 136
6>) +hould $ declare the constants in my interface as public final static, and my methods as
public abstract?

The use of the these modifiers in interfaces is completely optional. The following
point out the rele"ant sections of the 2a"a Manguage +pecification8
3ccording to the section B.1.=8 "ll inter!ace members are implicitly public#
3ccording to section B.08 Every !ield declaration in the body o! an inter!ace is
implicitly public$ static$ and !inal
3ccording to section B.68 Every method declaration in the body o! an inter!ace is
implicitly public and Every method declaration in the body o! an inter!ace is
implicitly abstract
6@) Why doesn,t the 2a"a runtime complain if the main() method isn,t declared public?

With +un,s reference implementation, they introduced this bug into the 1.)
implementation and ha"en,t fied it through the 1.0 release. The main() method is
supposed to be public static "oid but it seems any access modifier wor's fine.
6A) Why are there so many different programming languages?

3s is the case with most things in life, $ belie"e there are multiple reasons for why
we ha"e so many programming languages. *ere are what $ belie"e to be the
more significant reasons8
Irogramming languages "ary with respect to the speed with which programs
written in them can be eecuted. +o if you ha"e a real1time application, you,d
choose a language that would be capable of deli"ering results under the
applicable time constraints. +o for a problem in dynamic control, you might
choose, say, / o"er /PP or 2a"a.
/ertain application domains require programming languages that are specifically
targeted for those applications. /obol, for eample, represents a language that
was de"eloped specifically for business applications. $t is easy to learn by people
without ad"anced degrees in computer science and it is efficient for what it was
designed to do.
?uch early programming dealt with sol"ing numerically intensi"e problems, such
as problems encountered in scientific calculations. !ortran emerged as a fa"orite
of many for such applications. $ belie"e it continues to be a widely used language
for sol"ing numerically intensi"e problems on supercomputers.
?any programming languages that ha"e emerged from academic laboratories
are a result of researchers trying mimic certain aspects of human cognition.
Manguages li'e Misp and Irolog fall in this category.
3nother reason for why we ha"e so many programming languages is purely
e"olutionary. /onsider, for eample, the e"olution from / to /PP and then on to
Page 12 of 136
2a"a. 3s it began to be reali(ed that we needed richer representations for our
concepts and as we sought ways to ma'e large programs more easily etensible
and maintainable, the concepts of ob#ect1oriented programming came into
eistence. Then as we better understood what was meant by ob#ect1oriented
programming through pioneering languages li'e +malltal', / led to the
de"elopment of /PP. 3nd then as it dawned on us that the wide generality of /P
P (with regard to inheritance, operator o"erloading, and other issues) could
become a liability in some cases, 2a"a emerged.
3s the role of computers as %information presentation de"ices% proliferated in the
society, there emerged a concomitant need for languages designed specifically
for formatting the "isual display of information. Manguages such as *T?M, Q?M,
and their "ariants are fulfilling those needs.
$ suppose what it all means is that as we continue to deploy computers for
sol"ing pre"iously unaddressed problems, we will try to use the languages we
already 'now. 7ut should they fall short of our needs for whate"er reason, we as
a society of programmers will in"ent new languages.
6B) *ow can $ prohibit methods from being o"erloaded?

The only relati"ely surefire way that $ 'now of is to ma'e the entire class final.
$.e., since there,s no way to subclass that class then nobody can o"erload that
method.
=E) *ow can $ determine the "ersion of the 2CD at runtime?

/hec' the system properties8
+ystem.getIroperties().getIroperty(%#a"a."ersion%):
=1) What is a %mar'er% interface?

3 so1called mar'er interface is a 2a"a interface which doesn,t actually define any fields.
$t is #ust used to %mar'% 2a"a classes which support a certain capability 11 the class
mar's itself as implementing the interface. !or eample, the #a"a.lang./loneable
interface.
=)) What is a static bloc' and how should $ use it?

7asically, static bloc's are bloc's defined within the body of a class using the
static 'eyword but which are not inside any other bloc's. $.e.,
public class shme
9
static int foo = 1)06=:
Page 13 of 136
static
9
foo = BBAA@@:
;
;
The primary use of static initiali(ers bloc's are to do "arious bits of initiali(ation
that may not be appropriate inside a constructor such that ta'en together the
constructor and initiali(ers put the newly created ob#ect into a state that is
completely consistent for use.
$n contrast to constructors, for eample, static initiali(ers aren,t inherited and are
only eecuted once when the class is loaded and initiali(ed by the 2CD. $n the
eample abo"e, the class "ariable !oo will ha"e the "alue BBAA@@ once
initiali(ation is complete.
<ote also that static initiali(ers are eecuted in the order in which they appear
tetually in the source file. 3lso, there are a number of restrictions on what you
can,t do inside one of these bloc's such as no use of chec'ed eceptions, no use
of the return statement or the this and super 'eywords.
Iersonally, $ thin' this is yet another odd little wart in the 2a"a language that is
due to the fact that 2a"a doesn,t ha"e first1class classes. +igh.
=0) 3re classes that implement +eriali(able required to ha"e no1argument constructors?

<o. This is a common misconception. The deseriali(ation process does not use
the ob#ect,s constructor 1 the ob#ect is instantiated without a constructor and
initiali(ed using the seriali(ed instance data. The only requirement on the
constructor for a class that implements Serialiable is that the first non1
seriali(able superclass in its inheritence hierarchy must ha"e a no1argument
constructor. (+ee http855www.#guru.com5#guru5faq5"iew.#sp?D$G=06AE) for a more
complete eplanation). This ma'es sense8 deseriali(ation needs to reconstruct
the entire ob#ect state, which includes the state of any superclasses. $f the
superclass is not itself seriali(able, then deseriali(ation needs to instantiate that
superclass from scratch 1 thus the requirement. !or eample, with the following
class8
public class ?y+eriali(able/lass implements +eriali(able 9
...
;
you do not need a no1argument constructor. *ySerialiableClass meets all
requirements because its first non1seriali(able superclass, Object, has a no1
argument constructor. $n the following eample8
Page 14 of 136
public class ?y!irst/lass 9
;
public class ?y+econd/lass etends ?y!irst/lass implements +eriali(able 9
...
;
?y!irst/lass has the default, no1argument constructor, so no other constructor is
needed. $f, howe"er, ?y!irst/lass defined constructors which accepted
arguments without also eplicitly declaring a no1argument constructor, then you
would get a <ot+eriali(ableDceptin when trying to seriali(e ?y+econd/lass.
3ll the requirements for an ob#ect that implements Serialiable are listed at
http855www.#guru.com5#guru5faq5"iew.#sp?D$G=01606.
=6) What is the purpose of using a static method?

3 static method is simply a method that does not need an instance of a class to
eecute.
+tatic methods are most useful as utility methods in classes that don,t require
state. !or eample, the #a"a.lang.?ath class has se"eral static methods that you
can call for calculations. <o state is needed, so you don,t need an instance of the
?ath class to perform the methods.
-ou call static methods using the class name rather than an instance name. !or
eample
int = ?ath.ma(,y):
+tatic methods are often used to access class "ariables. /lass "ariables are
"ariables in the class that are declared static. There is only one instance of the
class "ariables on the system, so they ma'e a great place to store constant
"alues, %global% counts, and singleton instances.
&ften, de"elopers will define "ariables li'e
pri"ate static int count = E:
and define a methods to access it, li'e
public static int get/ount() 9
return count:
;
public static "oid increment/ount() 9
Page 15 of 136
countPP:
;
This allows reading and modification of the class "ariables while retaining control
of the "alues. <oone can directly access pri"ate class "ariables other than this
class, so you can restrict the types of updates (for eample, only incrementing
the count).
<ote that static methods cannot access any instance "ariables defined in the
ob#ect. Why? 7ecause you don,t have an instance of the ob#ect to 'now %hich
instance "ariables you want to access.
==) What are the differences between +ystem.gc() and Cuntime.gc()?

The methods are basically equi"alent. 7oth suggest to the 2CD that it might be a
good idea if the garbage collector actually does some wor' now.
+pecifically, System.gc () is a static method so it,s a wee bit more con"enient
to use rather than ha"ing to do e.g., +untime.get+untime ().gc ().
=>) *ow do $ con"ert a #a"a.sql.Timestamp to a #a"a.util.Gate?

While Timesteamp etends Gate, it stores the fractional part of the time within
itself instead of within the Gate superclass. $f you need the partial seconds, you
ha"e to add them bac' in.
Gate date = new Gate(ts.getTime() P (ts.get<anos() 5 1EEEEEE )):
=@) What,s the difference between an interface and an abstract interface?

<othing. 3ll interface,s are, by definition, abstract. $n fact, the 2M+ says that
use of the abstract modifier is obsolete and therefore should not be used in
new programs.
=A) Why is method in"ocation in 2a"a polymorphic but field access isn,t?

The designers of the 2a"a programming language feel that the lac' of dynamic
loo'up on field accesses pro"ides greater run1time efficiency. $n addition, if
people want dynamic loo'up on fields then they can easily use an accessor (a'a
%getter%) instance method instead of direct field access. $.e., they lea"e the
tradeoff up to the programmer.
Page 16 of 136
=B) What is a pac'age in 2a"a?

2a"a programs are organi(ed as sets of pac'ages. 3 pac'age comprises one or
more compilation units. The naming of pac'ages is hierachical and may
comprise classes, interfaces, and sub1pac'ages. Dach pac'age defines a
namespace.
>E) What is meant by compatible equals() and hash/ode() methods?

$n order for the 2a"a /ollections to wor' properly (and e"erything else in 2a"a),
the equals() and hash/ode() methods must be compatible. *ere, compatible
means that if equals() reports that two instances are the same, then the
hash/ode() of both instances must be the same "alue.
>1) $f an ob#ect is an array, how do $ find out its type?

4se the get/omponentType() method of the class of the ob#ect that is the array.
public class 3rrayCeflection 9
public static "oid main (+tring argsJK) 9
printType(args):
;
pri"ate static "oid printType (&b#ect ob#ect) 9
/lass type = ob#ect.get/lass():
if (type.is3rray()) 9
/lass elementType = type.get/omponentType():
+ystem.out.println(%3rray of8 % P elementType):
;
;
;
>)) Goes 2a"a use pass by value or pass by re!erence semantics when passing parameters to
methods?

2a"a passes parameters to methods using pass by value semantics. That is, a
copy of the "alue of each of the specified arguments to the method call is passed
to the method as its parameters.
<ote "ery clearly that a lot of people confuse the %reference% terminology with
respect to 2a"a,s re!erences to ob&ects and pass by re!erence calling semantics.
The fact is, in dealing with 2a"a,s re!erences to ob#ects, a copy of the re!erence,s
"alue is what is passed to the method 11 it,s passed by value. This is, for
eample, why you cannot mutate the (original, caller,s) reference to the ob#ect
from inside the called method.
Page 17 of 136
>0) What is the difference between an 3I$ and a framewor'?

*ere is a less formal definition8
3 framewor' is a set of classes which handles the flow necessary to perform a
comple tas', but which requires plug1in classes specific to your application
(database, app ser"er), and which allows for additional plug1in classes to etend
the functionality. !or eample, you could ha"e a framewor' which handles the
general flow of an online store. This framewor' would handle tas's such as %put
item in shopping cart%, %generate order on chec'out%, etc. &n the other hand, you
would need to pro"ide the classes which enable the framewor' to persist the
shopping cart to the database of your choice, to connect to a credit1card
processor, to send orders to a warehouse, among other things. !urther, if you
wanted to decided that you wanted to offer monogramming, you would need to
pro"ide classes to do so, and the framewor' should ma'e it easy to plug these
in.
3n 3I$ is really no more than a set of method signatures and other information
necessary to use a class or set of classes. The 3I$ is totally distinct from the
implementation. !or eample, a number of "endors ha"e implemented the ser"let
3I$, each in a different way. The 3I$ by itself has no implementation.
3 class library would ha"e an 3I$, as would a framewor'.
>6) What are differences between type1casting and Gata /on"ersion?
Type/asting is a feature of the language whereby you are telling the compiler
(and readers of your source code 81) that you eplicitly want it to treat the ob#ect
as if it were really of the type that you specified rather than it,s actual type.
Gata con"ersion is physically changing one chun' of data into another, often with
interpretation.
The difference can be illustrated thus8
Typecasting8
&b#ect o = new +tring(%1)06%):
+tring my+tring = (+tring)o:
This allows you to cast the type of o to it,s proper type, +tring.
Gata con"ersion8
+tring o = new +tring(%1)06%):
Page 18 of 136
$nteger i = $nteger.parse$nt(o):
This con"erts the String %1)06% into the $nteger which represents the "alue
1)06 (one thousand two hundred twenty four).
>=) Why does 2a"a not support function5method pointers5references ala /5/PP?

7ecause 2a"a is a more pure ob#ect1oriented language than /5/PP. !unction
pointers and method references are ways of pulling apart the functionality of
ob#ects.
The 2a"a, && way of doing the equi"alent is pass around an ob#ect reference
where that ob#ect adheres to a particular interface and so you can in"o'e the
appropriate methods.
/ollections
1) *ow do $ use an $terator to go through a /ollection?
/ollection collection = ...:
$terator iterator = collection.iterator ():
while (iterator.has<et()) 9
&b#ect element = iterator.net ():
55 Go something with element
;
;
)) *ow do $ use a Mist$terator to go through a Mist bac'wards?
Mist list = ...:
Mist$terator iterator = list.list$terator(list.si(e()):
while (iterator.hasIre"ious()) 9
&b#ect element = iterator.pre"ious():
55 Irocess element
;
0) *ow do $ use Dnumeration to iterate through a collection?
Dnumeration enum = ...:
while (enum.has?oreDlements()) 9
&b#ect element = iterator.netDlement():
55 process element
;
6) *ow do $ ma'e an array larger?
-ou cannot directly ma'e an array larger. -ou must ma'e a new (larger) array and copy the
original elements into it, usually with +ystem.arraycopy(). $f you find yourself frequently doing
this, the Lector class does this automatically for you, as long as your arrays are not of primiti"e
data types.
Page 19 of 136
=) *ow do you store a primiti"e data type within a Lector or other collections class?
-ou need to wrap the primiti"e data type into one of the wrapper classes found in the #a"a.lang
pac'age, li'e $nteger, !loat, or Gouble, as in8
$nteger in = new $nteger (=):
>) *ow do $ use an array with the /ollections !ramewor'?
The 3rrays.asMist () method pro"ides a fied1length Mist "iew of an array, where changes to the
Mist are stored in the original array. The 3rrays class also pro"ides additional support methods
for sorting and searching an array.
@) Which is faster, synchroni(ing a *ash?ap or using a *ashtable for thread1safe access?
7ecause a synchroni(ed *ash?ap requires an etra method call, a *ashtable is faster for
synchroni(ed access.
A) Which is the preferred collection class to use for storing database result sets?
When retrie"ing database results, the best collection implementation to use is the Min'edMist.
The benefits include8
Cetains the original retrie"al order
*as quic' insertion at the head5tail
Goesn,t ha"e an internal si(e limitation li'e a Lector where when the si(e is eceeded a new
internal structure is created (or you ha"e to find out si(e beforehand to si(e properly)
Iermits user1controlled synchroni(ation unli'e the pre1/ollections Lector which is always
synchroni(ed
7asically8
Cesult+et result = stmt.eecuteRuery(%...%):
Mist list = new Min'edMist():
while(result.net()) 9
list.add(result.get+tring(%col%)):
;
$f there are multiple columns in the result set, you,ll ha"e to combine them into their own data
structure for each row. 3rrays wor' well for that as you 'now the si(e, though a custom class
might be best so you can con"ert the contents to the proper type when etracting from
databse, instead of later.
Why doesn,t the $terator interface etend the Dnumeration interface?
$f the $terator interface etended the Dnumeration interface, the $terator interface would end up
with fi"e methods where two methods #ust called other methods in the interface. The designers
of the framewor' wanted to get rid of the cumbersome Dnumeration method names so had the
$terator interface stand on its own with new shorter method names.
B) *ow do $ print a /ollection?
The /ollection !ramewor' implementation classes o"erride the to+tring() method to print out
all the elements of the collection. $f you create your own custom implementation, as long as
your class is a subclass of 3bstract?ap or 3bstract/ollection you,ll inherit this beha"ior. (Feep
in mind that 3bstractMist and 3bstract+et subclass 3bstract/ollection.)
Page 20 of 136
1E) *ow do $ synchroni(e a collection?
With the /ollections !ramewor', the new implementations are all unsynchroni(ed by default. $f
you need synchroni(ed access, you must synchroni(e things yourself. The /ollections class
offers a wrapper method for each of the si core collection interfaces that add synchroni(ation
to an arbitrary collections implementation. To ensure thread1safety, direct access to the
original bac'ing collection must be a"oided.
!or eample, the following will synchroni(e an arbitrary Mist and lose the original reference so
you can,t access it directly8
Mist list = ...:
list = /ollections.synchroni(edMist(list):
11) *ow do $ get the length of an array?
To a"oid getting an 3rray$nde&ut&f7oundsDception, you can chec' for the array length from
either the length instance "ariable or using reflection and calling
#a"a.lang.reflect.3rray.getMength(), passing the array as an argument to the method.
int length = args.length:
55 or
int length) = 3rray.getMength(args):
1)) *ow do $ sort an array?
The 3rrays class in #a"a.util pro"ides a series of sort () methods for sorting arrays. $f the array
is an array of primiti"es or an array of a class that implements /omparable then you can #ust
call the method directly8
3rrays.sort(the3rray):
$f, howe"er, it is an array of ob#ects that don,t implement the /omparable interface then you
need to pro"ide a custom /omparator to help you sort the elements in the array.
3rrays.sort (the3rray, the/omparator):
10) What,s the fastest way to tra"erse all the elements of a Lector?
$f speed is of the essence, do not use a Lector. $nstead, use an 3rrayMist. 3ll accesses to a
Lector are synchroni(ed, whether you need it or not. $f you 'now you arenSt accessing the
structure from multiple threads, the 3rrayMist will be much faster.
With that said, what about if you need to stay with a Lector? There are at least four ways to
tra"erse through all the elements of a Lector8
4sing a for loop and accessing each element with element3t(inde) or get(inde)
4sing an Dmumeration
4sing an $terator
4sing an Dnumeration5$terator, but relying on an eception to catch ending
&f the four, there are neglible differences in performance. While looping through to a specific
inde is a little faster, you lose the fleibility of changing to another data structure at a later
time. With the Dnumeration 5 $terator approach, there is the added cost to create the
Dnumeration5$terator to wal' through. With the eception approach, you are relying on
Page 21 of 136
<o+uchDlementDception to be thrown to catch the ending of the wal' through. While creating
the eception ta'es time, this approach a"oids the repeated test of has?oreDlement(). 3s the
structure gets larger, a"oiding the test condition can sa"e lots of time.
16) *ow does a *ashtable internally maintain the 'ey1"alue pairs?
The *ashtable class uses an internal (pri"ate) class named Dntry to hold the 'ey1"alue pairs.
3ll entries of the *ashtable are stored in an array of Dntry ob#ects with the hash "alue of the
'ey ser"ing as the inde. $f two or more different 'eys ha"e the same hash "alue these entries
are stored as a lin'ed list under the same inde.
1=) *ow do $ loo' through each element of a *ash?ap?
To go through all the elements of a *ash?ap, or any class that implements the ?ap interface,
call the entry+et() or 'ey+et() methods than loop through what is returned. The entry+et()
returns a group of ?ap.Dntry elements, whereas the 'ey+et() method #ust returns a +et of 'ey
elements. $f you then want what the 'ey refers to, you,d ha"e to loo' them up.
&nce you ha"e a +et to wor' with, you would then use an $terator to go through all its
elements. The following demonstrates8
?ap map = some hash map
+et set = map.'ey+et():
$terator it = set.iterator():
while (it.has<et()) 9
+ystem.out.println(it.net()):
;
1>) *ow do $ create a read1only collection?
The /ollections class has si methods to help out here8
unmodifiable/ollection (/ollection c)
unmodifiableMist (Mist list)
unmodifiable?ap (?ap m)
4nmodifiable+et (+et s)
unmodifiable+orted?ap (+orted?ap m)
unmodifiable+orted+et (+orted+et s)
$f you then get an $terator from one of these unmodifiable collections, when you call remo"e() it
will throw an 4nsupported&perationDception
1@) *ow can $ process through the 'eys of a *ashtable in sorted order?
$n order to get all the 'eys for a *ashtable, you use the 'eys() method to get an Dnumeration
or the 'ey+et() method to get a +et. $f you are using 2a"a ), and can use the collections
framewor', what you should do is get the 'ey set of the *ashtable and create a Tree+et from
it. -ou can then get an iterator() from the created Tree+et that will ha"e the 'eys in order. $f
you can,t use the collections framewor', you,ll ha"e the sort the Dnumeration you get bac'
from 'eys() yourself.
1A) Which collections in 2a"a are synchroni(ed and which aren,t?
The original collection classes in 2a"a are all synchroni(ed8 Lector and *ashtable, along with
their subclasses +tac' and Iroperties. Those classes introduced with the 2a"a ) /ollections
Page 22 of 136
!ramewor' are all <&T synchroni(ed by default, the sets, lists, and maps. $f you need to
synchroni(e those, see *ow do $ synchroni(e a collection?.
1B) What are the differences between 3rrayMist and Min'edMist?
3n 3rrayMist is a Mist implementation bac'ed by a 2a"a array, similar to the Lector class. 3s
the number of elements in the collection increases, the internal array grows to fit them. $f there
are lots of growth periods, performance degrades as the old array needs to be copied into the
new array. *owe"er, random access is "ery quic' as it uses an array inde to access.
With a Min'edMist, the Mist implementation is bac'ed by a doubly lin'ed list data structure,
allowing easy inserts5deletions anywhere in the structure, but really slow random accesses as
the access must start at an end to get to the specific position.
)E) What is the difference between a singly lin'ed list and doubly lin'ed list?
3 singly lin'ed list is one that has only a pointer5reference to the net element in the list. 3
doubley lin'ed list has both a pre"ious and net pointer5reference.
)1) What is a polymorphic algorithm?
$n general, an algorithm is called polymorphic if it can achie"e the same functionality using
different data structures. !or eample, if the same sorting or searching algorithm could be
used with different types of containers, such as "ectors, lists, maps, etc., then that algorithm
would be called polymorphic. 3s a case in point, the generic algorithms of the +TM library in /P
P are polymorphic because they can be used for different container classes.
$n the contet of 2a"a collections, the polymorphic algorithms are all supplied by the
"arious static methods of the #a"a.util./ollections class. /onsider, for eample, the
method sort( Mist list ). This method is capable of sorting any collection that has
implemented the Mist interface, and that includes containers of types 3rrayMist,
Min'edMist, Lector, etc.
))) *ow do you sort the elements of a "ector?
+ince the Lector class implements the Mist interface, you can call the /ollections.sort() method
to sort the elements in place. -ou can also manually insert elements into a Lector to 'eep the
"ector sorted. &f course, if 'eeping sorted access is such a big deal, you should consider
using a different, more appropriate data structure li'e a Tree+et.
!or 1.1 2a"a users, you,ll need to sort the elements yourself. There is no built1in support for
this. 3 better option might be to sort the elements as you insert each element.
)0) *ow do you control growth of "ectors when their internal arrays are full?
The "ector constructor can include either an initial capacity or a capacity and growth
increment. When not specified, the initial si(e of the "ector is 1E and growth will double when
necessary. &therwise, initiali(e si(e and growth will grow when needed as specified by the
arguments to the constructor.
$f the argument to the constructor is a collection, the initial si(e of the internal structure is 1ET
larger than the collection. +ince there is no second argument to control growth, the capacity
will double when necessary.
)6) Why can,t $ add a collection to itself?
This will cause a stac' o"erflow eception to be generated on calls to methods li'e to+tring()
and hash/ode(), which recursi"ely call the method on the elements of the collection.
Page 23 of 136
)=) What is a wea' reference and what are they used for?
<ormally the 2a"a garbage collector plays safe. $t will only free up the memory used by an
ob#ect when that ob#ect can no longer be accessed by the program. &nce an ob#ect become
impossible to reach it is eligible for collection, and e"entually its memory will be reclaimed.
This eliminates one of the most common programming errors in some other languages (li'e /P
P), where code accidentally tries to access an ob#ect that has been freed. 4nfortunately it can
lead to another problem, where you lea"e open a potential access route to an ob#ect that you
don,t need any more. ?emory fills up, and the program slows down or reports an %&ut of
?emory% error.
To a"oid this, you can be "ery careful to close off access paths to an ob#ect once you ha"e
finished using it. 2a"a ) introduces another alternati"e, the wea' reference. Wea' references
pro"ide access to an ob#ect without pre"enting it from being freed. When you use a wea'
reference you ha"e to accept that the ob#ect referred to may ha"e disappeared, which results
in the reference being automatically set to null. &n the other hand, the wea' reference will not
hold the ob#ect in memory once it is inaccessible "ia normal references (or "ia %soft% references
1 see below). Wea' references are not appropriate in all circumstances, but sometimes they
can ma'e code easier to write and understand.
The most common use of wea' references is indirect 1 they are used internally by the
Wea'*ash?ap class. Mi'e *ash?ap, Wea'*ash?ap associates 'ey ob#ects with "alues.
*owe"er, once the 'ey ob#ect becomes inaccessible "ia stronger references it becomes
eligible for garbage collection. When it is freed, the map entry magically disappears. The
assumption here is that if you are not using the 'ey anywhere other than in the map you will
ha"e no need to loo' it up, so it should be freed.
&ther specialist references are soft references (which inhibit collection until memory runs
short), and phantom references (used for cleanup when ob#ects are freed).
!or more detailed (and precise) information, see the #a"a.lang.ref 3I$ docs, and also the article
Ceference &b#ects and .arbage /ollection at the +un website.
)>) *ow does 3rrayMist increase its capacity?
4nli'e Lector where you can specify a capacity increment, 3rrayMist doesn,t support this.
$nstead, 3rrayMist will increase capacity by about a half when it runs out of space. The
refernece implementation uses the forumla8
new/apacity = (old/apacity N 0)5) P 1
though, this isn,t part of the class definition so others can implement it differently.
)@) What are the differences between *ash?ap and *ashtable?
7oth pro"ide 'ey1"alue access to data. The *ashtable is one of the original collection classes
in 2a"a. *ash?ap is part of the new /ollections !ramewor', added with 2a"a ), "1.).
The 'ey difference between the two is that access to the *ashtable is synchroni(ed on the
table while access to the *ash?ap isn,t. -ou can add it, but it isn,t there by default.
3nother difference is that iterator in the *ash?ap is fail1safe while the enumerator for the
*ashtable isn,t. $f you change the map while iterating, you,ll 'now.
Page 24 of 136
3nd, a third difference is that *ash?ap permits null "alues in it, while *ashtable doesn,t.
!or new code, $ would tend to always use *ash?ap.
)A) What are the differences between Lector and 3rrayMist? Which is best to use?
Lector and 3rrayMist are "ery similar. 7oth of them represent a ,growable array,, where you
access to the elements in it through an inde.
3rrayMist it,s part of the 2a"a /ollection !ramewor', and has been added with "ersion 1.),
while Lector it,s an ob#ect that is present since the first "ersion of the 2GF. Lector, anyway, has
been retrofitted to implement the Mist interface.
The main difference is that Lector it,s a synchroni(ed ob#ect, while 3rrayMist it,s not.
While the iterator that are returned by both classes are fail1fast (they cleanly thrown a
/oncurrent?odificationDception when the orignal ob#ect has been modified), the Dnumeration
returned by Lector are not.
4nless you ha"e strong reason to use a Lector, the suggestion is to use the 3rrayMist.
Threads
1) What is a thread?

3 thread is a set of instructions eecuting apart from other threads (with its own
stac') but sharing the same memory space (with the same heap).
)) *ow do $ create a new thread and ha"e it start running?

/reating a thread in"ol"es creating a new (,read and in"o'ing its start()
method. /alling start() causes the run() method of the (,read subclass or
the +unnable ob#ect passed to the (,read constructor to eecute.
Thread t1 = new Thread() 9
public "oid run() 9
for (int i=E: iU1EE: iPP) 9
+ystem.out.println(%Tastes .reat%):
;
;
;:
Cunnable r = new Cunnable() 9
public "oid run() 9
for (int i=E: iU1EE: iPP) 9
+ystem.out.println(%Mess !illing%):
Page 25 of 136
;
;
;:
Thread t) = new Thread(r):
t1.start():
t).start():
0) *ow do $ get a thread to pause?

The static sleep() method of the (,read class will let your thread sleep for a
set number of milliseconds (or nanoseconds). When the thread wa'es up, it will
be scheduled to eecute in the future. $t may not start eecuting immediately
after the timeout.
try 9
Thread.sleep(0EEE): 55 0 seconds
; catch ($nterruptedDception e) 9
+ystem.err.prinlnt(%-ou interrupted me%):
;
J
-ou can ha"e another thread wa'e up the sleeping thread prematurely by calling
t.interrupt() (where %t% is a pointer to the thread ob#ect).
<ote that since Thread.sleep is a static method, the following code will not do
what you epect it to8
Thread t = new ?yThread():
t.start():
try 9
t.sleep(0EEE):
; catch ($nterruptedDception e) 9
+ystem.err.prinlnt(%-ou interrupted me%):
;
$t will pause the current thread, meaning the thread eecuting the shown code,
not the child thread (t5?yThread).
<on1static synchroni(ed methods synchroni(e on the instance (t,is) of the
class.
Page 26 of 136
6) What ob#ect does static synchroni(ed methods use for loc'ing?

+tatic synchroni(ed methods synchroni(e on the class ob#ect
(t,is.getClass()) of the class.
=) *ow can one thread wait for another thread to die before it continues eecution?

The thread,s join() method allows you to wait for another thread to finish
eecution.
Thread t1 = new Thread(runnable):
t1.start():
55 do stuff
...
55 wait for t1 to finish
t1.#oin()
>) What is the use of start () function in starting a thread? Why we do not use the run() funtion
directly to run the thread?

The start() method tells the 2a"a Lirtual ?achine that it needs to create a system
specific thread. 3fter creating the system resource, it passes the Cunnable ob#ect
to it to eecute its run () method. /alling the run() method directly has the
%Thread% eecute in the same thread as the calling ob#ect, not in a separate
thread of eecution, as intended.
$n other words, calling run() is #ust li'e a normal method call. Whereas, calling
start() tells the thread to create the necessary system resources and then
eecute the run() method asynchronously.
@) What is the main difference between a preempti"e scheduler and a non1preempti"e
scheduler?

3 preempti"e scheduler interrupts a thread of eecution when its timeslice runs
out. 3 non1preempti"e (or %cooperati"e%) scheduler waits for the thread to yield
control.
J2a"a nati"e thread implementations are usually preempti"e: the green1threads
implementation is cooperati"e but priority1preempti"e, which means that when a
high1priority thread becomes runnable, it immediately becomes acti"e. 13leK
Page 27 of 136
A) *ow does a preempti"e scheduler manage a thread,s timeslice?

The lowest le"el preempti"e scheduler ('ernel layer) uses the system timer
interrupt and contet switching to manage timeslices. When any /I4 interrupt
occurs, the /I4 ma'es a note of where it was, and what it was doing (pushes all
registers onto the stac'). The /I4 then processes the interrupt and returns to
what it was pre"iously doing (pops all registers from the stac'). The thread
contet in this sense, is the information the /I4 needs to start or resume
eecution in any section of code. The scheduler is in"o'ed by the timer interrupt
routine (it can also be part of the timer interrupt). The scheduler chec's to see if
the current timeslice has epired: if so, the current thread contet is stored and
the net "alid thread contet is restored. The most basic implementation is a
stac' swap, as each thread has its own stac'. When a thread is created, it gets a
new contet with an empty stac'. The new contet directs the /I4 to the
thread,s run() member at the beginning of its timeslice. 3 thread,s contet is
destroyed when the thread returns from the run() member, or its stop() member
is successfully in"o'ed.
B) What are the differences between etending the Thread class and implementing the
Cunnable interface?

Dtending the Thread class will ma'e your class unable to etend other classes,
because of the single inheritence feature in 23L3. *owe"er, this will gi"e you a
simpler code structure. $f you implement runnable, you can gain better ob#ect1
oriented design and consistency and also a"oid the single inheritance problems.
1E) What are the different uses of the synchroni(ed 'eyword?

The 'eyword sync,ronied is used to acquire a eclusi"e monitor loc' on an
ob#ect. $t can be used to mar' either a method or a bloc' of code. $n both cases,
it means to acquire a loc' for the duration of the method or bloc', and to release
the loc' at the end. $t also ta'es a parameter, which names the ob#ect whose loc'
will be acquired. (The parameter is implicit when mar'ing a method, as shown
below.)
synchroni(ed (foo) 9
...
;
3cquires a loc' on the ob#ect instance %foo% at the open brace, and
releases the loc' at the close brace.
synchroni(ed (this) 9
Page 28 of 136
...
;
3cquires a loc' on the current ob#ect instance (%this%) at the open
brace, and releases the loc' at the close brace.
synchroni(ed "oid bar() 9
...
;
3cquires a loc' on the current ob#ect instance at the open brace,
and releases it at the close brace. This is equi"alent (N) to
"oid bar() 9
synchroni(ed (this) 9
...
;
;
class !oo 9
synchroni(ed static "oid bar() 9
...
;
;
3cquires and releases a loc' on the class instance of class !oo.
D"ery class, when loaded, is gi"en an instance of class /lass. That
means that no matter who in"o'es method !oo.bar(), the loc' will
be on the static instance, and not on any specific instance of class
!oo.
$ 'now this sounds confusing, but it has the same semantics as any
other use of static8 all statics (methods, "ariables, etc) are
essentially global, interact with all other statics of the same class,
and do not interact with non1static instance data.
Whether a method is public or not ma'es no difference to the semantics of
sync,ronied.
11) *ow can multiple threads be controlled simultanesously?

$f you create threads in a Thread.roup ob#ect, they may be controlled
simultaneously with the member functions of said ob#ect.
1)) What is a daemon thread? When should $ use setGaemon() and why?

Page 29 of 136
4se thread.setGaemon(true) to tell the 2L? to ma'e the thread a daemon
thread.
3ccording to Webster,s, a daemon ("ariant of demon) is an attendant power or
spirit. Gaemon threads are typically used to perform ser"ices for your
application5applet (such as loading the %fiddley bits%). The core difference
between user threads and daemon threads is that the 2L? will only shut down a
program when all user threads ha"e terminated. Gaemon threads are terminated
by the 2L? when there are no longer any user threads running, including the
main thread of eecution. 4se daemons as the minions they are.
J$n short8 daemon threads do not 'eep the program from quitting: user threads
'eep the program from quitting. 13leK
10) What is the difference between sleep(), wait() and suspend()?

Thread.sleep() sends the current thread into the %<ot Cunnable% state for some
amount of time. The thread 'eeps the monitors it has aquired 11 i.e. if the thread
is currently in a synchroni(ed bloc' or method no other thread can enter this
bloc' or method. $f another thread calls t.interrupt() it will wa'e up the sleeping
thread.
<ote that sleep is a static method, which means that it always affects the current
thread (the one that is eecuting the sleep method). 3 common mista'e is to call
t.sleep() where t is a different thread: e"en then, it is the current thread that will
sleep, not the t thread.
t.suspend() is deprecated. 4sing it is possible to halt a thread other than the
current thread. 3 suspended thread 'eeps all its monitors and since this state is
not interruptable it is deadloc' prone.
ob#ect.wait() sends the current thread into the %<ot Cunnable% state, li'e sleep(),
but with a twist. Wait is called on a ob#ect, not a thread: we call this ob#ect the
%loc' ob#ect.% 7efore loc'.wait() is called, the current thread must synchroni(e on
the loc' ob#ect: wait() then releases this loc', and adds the thread to the %wait
list% associated with the loc'. Mater, another thread can synchroni(e on the same
loc' ob#ect and call loc'.notify(). This wa'es up the original, waiting thread.
7asically, wait()5notify() is li'e sleep()5interrupt(), only the acti"e thread does not
need a direct pointer to the sleeping thread, but only to the shared loc' ob#ect.
JThis answer was edited: the original answer was clear but $ felt $ should epand
on some points: please blame me, not $ngo, for any errors. 13leK
16) What is the difference between a lightweight and a hea"yweight process?

Page 30 of 136
J+hort answer8 threads are lightweight, programs (a'a processes or tas's) are
hea"yweight. 13leK
Mightweight and hea"yweight processes refer the mechanics of a multi1
processing system.
$n a lightweight process, threads are used to di""y up the wor'load. *ere you
would see one process eecuting in the &+ (for this application or ser"ice.) This
process would posess 1 or more threads. Dach of the threads in this process
shares the same address space. 7ecause threads share their address space,
communication between the threads is simple and efficient. Dach thread could be
compared to a process in a hea"yweight scenario.
$n a hea"yweight process, new processes are created to perform the wor' in
parallel. *ere (for the same application or ser"ice), you would see multiple
processes running. Dach hea"yweight process contains its own address space.
/ommunication between these processes would in"ol"e additional
communications mechanisms such as soc'ets or pipes.
The benefits of a lightweight process come from the conser"ation of resources. +ince threads
use the same code section, data section and &+ resources, less o"erall resources are used.
The drawbac' is now you ha"e to ensure your system is thread1safe. -ou ha"e to ma'e sure
the threads don,t step on each other. !ortunately, 2a"a pro"ides the necessary tools to allow
you to do this.
1=) What is the meaning of calling a method or ob#ect %thread1safe?%

7asically, calling a method %thread1safe% means that e"en if multiple threads try
to access it simultaneously, nothing bad happens. *ere %bad% usually means that
due to race conditions, or deadloc', or other pitfalls, the ob#ect,s state gets
corrupted, or its methods produce unreliable results. 3 method usually achei"es
thread1safety by protecting access to shared resources. This usually translates to
using the 2a"a synchroni(ed 'eyword to protect bloc's of code that access
instance "ariables, or other shared "ariables.
!or an ob#ect to be thread1safe, it must be possible for multiple threads to
simultaneously access the same method, or multiple methods, in that ob#ect.
4sually this is achei"ed by assuring that each method is thread1safe, but this
doesn,t always suffice, since methods can call each other in strange ways,
leading to deadloc' and other weirdness.
$t is "ery difficult to pro"e that an ob#ect is thread1safe. The main rule of thumb for
ma'ing thread1safe ob#ects is, %?a'e all the instance "ariables pri"ate, and all
the public accessor methods synchroni(ed.% *owe"er, this is sometimes difficult
to achie"e in practice, due to eigencies of performance, architecture, or
implementation.
Page 31 of 136
3ccurate multithreaded programming is a true art, and "ery difficult to master. Cead %2a"a
Threads% by &a's and Wong, and %/oncurrent Irogramming in 2a"a% by Mea, for inspiration in
your quest to become a thread1safe programmer.
1>) *ow can $ actually, really deallocate a Thread to release the memory? +etting thread = null
does not wor'V

4sing thread = null will not release a running thread. $n order to release the
memory associated with a thread, you need to ma'e sure that all of the following
are done8
?a'e sure that the thread,s start() method has been called.
?a'e sure that the thread has stopped eecuting.
/lear any references to that Thread ob#ect (thread = null:).
This is the best you can do to ensure the release of memory for a Thread. -ou
ha"e to call start() on the thread because se"eral 2L?s ha"e a bug where they
will not release all the thread,s memory if the thread is not started.
1@) What is the difference between a thread and a process?

3 process is an &+1le"el tas' or ser"ice. 3 thread runs %inside% a process and
may be "irtual or simulated. .enerally spea'ing, threads share resources li'e
memory, where processes each ha"e their own separate memory area, and
need to ta'e more elaborate steps to share resources.
3nother name for thread is %lightweight process% to distinguish it from the %hea"yweight%
system processes.
1A) What is the difference between threads and interrupts ?

3 thread is a /I4,s state of eecution as it processes a set of instructions (also
referred to as a tas'). 3n interrupt is a condition that causes the /I4 to store the
state of its current thread of eecution to begin a more important tas', or to begin
or resume the net tas' in a list of tas's. 3n interrupt handler is the set of /I4
instructions associated with any gi"en interrupt (a I/ has se"eral types of
interrupts).
The confusing part is the fact that the thread of eecution in an interrupt handler
is often referred to as an interrupt.
$n short, a thread is a tas' and an interrupt is a signal used to queue a more
important tas'.
Page 32 of 136
1B) When and why is $llegal?onitor+tateDception thrown?

3ccording to the 2a"aGoc, $llegal?onitor+tateDception is thrown %to indicate
that a thread has attempted to wait on an ob#ect,s monitor or to notify other
threads waiting on an ob#ect,s monitor without owning the specified monitor.%
)E) What is deadloc'? *ow can $ eliminate it?

3 simple deadloc' situation is one in which a two threads are waiting. Dach
thread waiting for a resource which is held by the other waiting thread. J$n 2a"a,
this resource is usually the ob#ect loc' obtained by the synchroni(ed 'eyword.K
This deadloc' situation can range from the abo"e two thread situation to any
number of threads waiting in a circular fashion.
?any solutions to this well 'nown problem ha"e been defined o"er the years
including the large range of solutions to %The Gining Ihilosophers% problem.
)1) What is $nterruptedDception? Why do we need to catch it when calling Thread.sleep()?

$nterruptedDception is thrown if another thread calls interrupt() on the sleeping
thread while it is asleep. $f sleep() is setting an alarm cloc' before bed, interrupt()
is a midnight phone call.
This means that you can safely ignore the eception (with
catch ($nterruptedDception e) 9;) since in general, only code that you write will
e"er call interrupt. +ince you didn,t write it, you 'now it won,t happen. 81)
$nterruptedDception was not implemented in 2a"a 1.E: howe"er, it is definitely
a"ailable now.
The eception will also get thrown if the %interrupted% flag is set in the thread,
which happens if another thread calls interrupt e"en before the original thread
sleeps.
))) When eactly is the 3WT thread started?

3nytime the #a"a.awt.Tool'it instance is (directly or indirectly) created. The direct
way to create it is by calling1
Tool'it.getGefaultTool'it():
$ndrect way is by creating any 3WT ob#ect.
Page 33 of 136
*ere is a sample program to play with 1
import #a"a.awt.N:
public class Q
9
static !rame f:
public static "oid main(+tringJK args)
9
55Tool'it.getGefaultTool'it():
f = new !rame():
+ystem.out.println(%...%):
;
;
)0) What is the difference between multithreading and multitas'ing? What about
multiprogramming? ?ultiprocessing?

?ultitas'ing is running multiple %hea"yweight% processes (tas's) by a single &+.
?ultithreading is running multiple %lightweight% processes (threads of eecution)
in a single process 5 tas' 5 program. +ee What is the difference between a
lightweight and a hea"yweight process? for more detail on lightweight "s.
hea"yweight processes.
?ultiprogramming is essentially a synonym for multitas'ing (though multitas'ing
connotes sharing more resources than #ust the /I4, and is the more popular
term).
?ultiprocessing in"ol"es using multiple /I4s, either in the same (+?I) or
different (?II) host boes, to run a program. +ee whatis.com for a good
definition.
?ost 2a"a implementations will split threads among different processors if they,re
running on an +?I bo.
)6) Why is Thread.run() declared public? +houldn,t it be declared protected, as only the
Thread superclass can in"o'e it?

&ne reason is that Thread implements Cunnable, which requires that run() be
public. This is an unfortunate consequence of the definition of 2a"a interfaces.
Page 34 of 136
$t is also not clear whether you would want to prohibit other classes from calling a
Thread,s run() method in a synchronous manner 11 as it is, they ha"e the option
of calling either run() or start() depending on their needs.
)=) $s there any method by which $ can #oin() to a group of threads instead of a single one?

-es. 2ust #oin to each one in turn. That way, when the loop eits, you 'now that
all the threads ha"e eited 11 whether it was the first thread or the se"enth thread
that too' the longest, all threads will be waited for. Cemember, #oin() on a thread
that,s already eited ta'es no time.
$terator i = myThreads.iterator():
while (i.has<et()) 9
((Thread)i.net()).#oin():
;
)>) Why do $ ha"e to call +ystem.eit() from my main method?

4nfortunately, certain system threads are started as regular threads, not daemon
threads. &ne eample is the 3WT thread. That means that if your app opens a
window, then e"en if that window is closed, the 3WT thread continues, so your
app will ne"er quit on its own.
There are many cases where a 2a"a program will quit on its own when main()
eits, but there are also many snea'y cases where a thread is launched without
your 'nowledge by a library routine. Gatabase /onnection Iools are notorious
for doing this.
3 warning8 ?a'e sure you only call +ystem.eit() when you,re really really sure
all bac'ground threads ha"e stopped processing. &therwise the threads will be
stopped prematurely, and may lea"e things in a bad state (for instance, if they,re
halfway through writing a file).
)@) What is the difference between sleep and yield?

yield() tells the 2L? Thread +cheduler that it,s &F to gi"e other threads time
slices. 4sually the 2L? uses this call to acti"ate another thread of the same
thread priority. $n a good preempti"e multithreading en"ironment, yield() is a no1
op. *owe"er, it is important in a cooperati"e multithreading en"ironment, since
without yield(), one thread can eat up all of the /I4.
sleep() tells the 2L? Thread +cheduler to acti"ely put this thread to sleep and
not run it again until at least milliseconds ha"e elapsed.
Page 35 of 136
<either sleep() nor yield() change anything about the status of synchroni(ation
loc's. $f your thread has a loc', and you call sleep(1EEE), then at least a second
will elapse before your thread wa'es up. When it wa'es up it may decide to
release the loc' 11 or it may hold on to it longer.
)A) *ow do we stop the 3WT Thread? &ur +wing application will not terminate.

-ou need to eplicitly call System.e%it(e%it-value) to eit a +wing
application. This is because the e"ent dispatcher thread is not a Gaemon thread,
and won,t allow the 2L? to shut down when other threads are dead.
)B) *ow soon after calling start() will the run() method be eecuted?

-our run method is not guarenteed to run immediately after the Thread.start ()
method is called.
The 2a"a Manguage +pecification gi"es implementations lots of legroom with
respect to the scheduling of threads. -our thread may start immediately, or it
may start = minutes later.
3ny decent implementation will ha"e your thread start as soon as possible under
the scheduling algorithm, so a fi"e minute wait would be unreasonable.
0E) What does it mean to loc' an ob#ect?

D"ery ob#ect instance in 2a"a has a little piece of data hanging off of it called a
%monitor loc'.% This is similar to a semaphore.
When you use the synchroni(ed 'eyword, the current thread attempts to obtain
the monitor loc' for the ob#ect in question (either %this% or the ob#ect named
eplicitly). $f the loc' is una"ailable, because another thread has acquired it, then
the current thread pauses indefinitely. When it wa'es up again, it will ha"e
acquired the loc', and will retain it until the end of the code bloc' where
synchroni(ed was used.
&ne confusing part is that the only thing that this loc' loc's is access to the loc'
itself. $t does not control access to instance "ariables or method access in and of
itself. &ther threads can reach in and modify "ariables and call methods. $f you
want the loc' to control access to "ariables, then you must eplicitly use the
synchroni(ed 'eyword e"ery single place in your code that accesses them.
3 straightforward way to guarantee that no "ariable access happens without a
loc' is by ma'ing all your "ariables pri"ate and using sync,ronied on all your
accessor5mutator methods (get!oo5set!oo).
Page 36 of 136
01) *ow do $ capture an eception stac' trace and put it into a string?

*ere,s how to print the trace in a string8
Dception e = new Dception(%something went wrong%):
+tringWriter sw = new +tringWriter():
e.print+tac'Trace(new IrintWriter(sw)):
+tring stac'trace = sw.to+tring():
+ystem.out.println(%stac'trace = % P stac'trace):
0)) $s it possible to wa'e up a sleeping thread?
/all sleepingThread.interrupt().
Page 37 of 136
I/O
1) *ow can $ compress my data to sa"e bandwidth when sending across a soc'et?
The .O$I$nput+tream and .O$I&utput+tream classes found in the #a"a.util.(ip pac'age
compress data with the .O$I file format, as defined by C!/ 1B=)
)) *ow do $ append to end of a file in 2a"a?
-ou can use java.io.+andom&ccessFile and something li'e the following8
try 9
Candom3ccess!ile raf =
new Candom3ccess!ile(%filename.tt%, %rw%):
raf.s'ip7ytes( (int)raf.length() ):
55 -ou are now at the end of the file,
55 and can start writing new data out, e.g.
raf.write7ytes(
%Mog restarted at 108EEpm 01)1)EEEWn%):
raf.close():
; catch ($&Dception e ) 9
e.print+tac'Trace():
;
or you can use File.riter 5 FileOutputStream and open it for append8
!ileWriter writer =
new !ileWriter(%filename.tt%, true):
0) *ow can $ see from an applet the names of files and directories that are in the ser"er?

There is no built1in support for this. 7asically, you must create a ser"ice on the
ser"er that when requested returns a list of a"ailable files and directories.
6) *ow can $ read .(ip and .#ar file using standard 2a"a classes?

The O$I and 23C reading classes are found in the #a"a.util.(ip and #a"a.util.#ar
pac'ages respecti"ely. The following demonstrates reading from a O$I file, listing
all the files in the (ip and displaying the contents of the first file in the (ip. 23C file
reading is similar, #ust with different classes and ha"ing a manifest.
import #a"a.util.(ip.N:
import #a"a.util.N:
Page 38 of 136
import #a"a.io.N:
public class OipDample 9
public static "oid main(+tring argsJK) 9
try 9
Oip!ile (f = new Oip!ile(%the.(ip%):
Dnumeration entries = (f.entries():
+tring first = null:
while (entries.has?oreDlements()) 9
OipDntry (e = (OipDntry)entries.netDlement():
+ystem.out.println(%Dntry % P (e.get<ame()):
if (first == null) first = (e.get<ame():
;
OipDntry (e = (f.getDntry(first):
if ((e V= null) 9
7ufferedCeader br = new 7ufferedCeader(
new $nput+treamCeader((f.get$nput+tream((e))):
long si(e = (e.get+i(e():
if (si(e X E) 9
+ystem.out.println(first P % Mength is % P si(e):
+tring line:
while ((line = br.readMine()) V= null) 9
+ystem.out.println(line):
;
br.close():
;
;
; catch($&Dception e) 9
e.print+tac'Trace():
;
;
;
=) *ow do $ chec' for end1of1file when reading from a stream?

Dactly how depends upon which stream you are reading from. $f you are reading
with the read() method of $nput+tream5Ceader, this will return 11 on D&!. $f
howe"er you are using 7ufferedCeader.readMine(), then this will return null on
end of file. 3nd, the readQQQ operations of the Gata$nput interface throw an
D&!Dception. $f you are unclear how to terminate your reading, chec' the
#a"adoc for the stream you are using.
>) 4nder what circumstances would $ use random access $5& o"er sequential, buffered $5&?

Page 39 of 136
Whether you use random access $5& or sequential access really depends upon
what you are trying to do. Candom access $5& is usually used for fied1si(e data
records, where you want to o"erwrite the original record with changes, or to
create something li'e a rolling log file. <owadays, there are lightweight database
systems that would do this type of operation for you, adding capabilities li'e
querying and a standard 2G7/ access so you wouldn,t ha"e to waste your time
redesigning the wheel. While not trying to tell you to ne"er use random access
$5&, the 2a"a Candom3ccess!ile class li"es outside the 2a"a streams class
hierarchy meaning that you can,t add a facade around the random access file to
buffer it or enrich its capabilities in any manner. 3nd you would also need to
program in things li'e simultaneous access.
+equential access is #ust for that, when you need to access a file sequentially
from start to finish. While you can s)ip() around the data, it is generally meant
to be read from beginning to end, where the whole file has some meaning. !or
performance reasons, it is best to always buffer your $5&, at least when using
+eader, .riter, /nputStream, and OutputStream classes, but not
+andom&ccessFile.
@) *ow do $ get a listing of the files in a directory?

/reate a #a"a.io.!ile for the directory, then as' for the list of files with one of the
following8
public #a"a.lang.+tringJK list():
public #a"a.lang.+tringJK list(#a"a.io.!ilename!ilter):
public #a"a.io.!ileJK list!iles():
public #a"a.io.!ileJK list!iles(#a"a.io.!ilename!ilter):
public #a"a.io.!ileJK list!iles(#a"a.io.!ile!ilter):
The first two return the filenames as strings (for that directory), the latter three
return actual !ile ob#ects.
A) Where can $ store temporary files?

The java.io.tmpdir system property defines an appropriate area8
+tring tempIath = +ystem.getIroperty(%#a"a.io.tmpdir%):
!ile f = new !ile(tempIath, %test.out%):
B) *ow can $ change time and date of a file?

Page 40 of 136
Iro"ided you ha"e write access to the file and are using 2GF 1.) or later, the
public boolean set0ast*odified(long time) method of File allows
you to modify the timestamp associated with a file.
1E) *ow do $ create a temporary file?

To create a temporary file, use the createTemp!ile() method of the !ile class.
This allows you to set the file prefi, suffi, and directory. $f no directory is
specified, then the #a"a.io.tmpdir +ystem property is used. To ensure the file is
deleted when the program ends (assuming normal termination), be sure to call
the delete&nDit() method of the !ile ob#ect created by createTemp!ile().
!ile temp = !ile.createTemp!ile(%#guru%, %.tmp%):
temp.delete&nDit():
55 use temp li'e any other !ile
11) *ow do $ delete a file 5 directory?

4se the delete() method of the File class.
1)) *ow do $ read tet from standard input?

+ystem.in is the $nput+tream for standard input. The following demonstrating
reading from it a line at a time8
$nput+treamCeader isr = new $nput+treamCeader(+ystem.in):
7ufferedCeader reader = new 7ufferedCeader(isr):
+tring line = null:
while ((line = reader.readMine()) V= null) 9
55 Irocess line
;
10) *ow do $ write tet to a file?

Writing tet in"ol"es writing strings, so you would use a File.riter.
!ileWriter fw = new !ileWriter(filename):
IrintWriter pw = new IrintWriter(fw):
pw.println(%*ello, World%):
pw.close():
16) *ow do $ copy a file?

Page 41 of 136
To ma'e a copy of a file, open the source file as a !ile$nput+tream. &pen the
destination as a !ile&utput+tream. 3s you read a byte from the input, write it to
the output. There is no built1in method to ma'e a file copy for you.
1=) What is a stream?

7asically, a stream is an ordered loo' at a sequence of bytes for input or output.
Mow1le"el streams pro"ide direct access to the underlying bytes, li'e a
!ile$nput+tream, !ile&utput+tream, or /har3rrayWriter, where reading and
writing wor' directly with the underlying input5output de"ice. *igh1le"el streams,
or filters, instead build upon the low1le"el streams to pro"ide additional
capabilities, li'e buffering, counting lines, compressing data, or reading5writing
higher1le"el data members li'e primiti"es or ob#ects. -ou can chain multiple
filters together to get multiple higher1le"el operations on a single low1le"el
stream.
1>) *ow can $ open the same file for reading as well as writing?

The Candom3ccess!ile class supports simultanous reading and writing from the
same file. 2ust open it in %rw% mode8
Candom3ccess!ile raf =
new Candom3ccess!ile(%filename.tt%, %rw%):
4se s'ip7ytes() to mo"e to where you wish to read5write.
1@) *ow do $ list all dri"es5filesystem roots on my system?

The listCoots() method of the !ile class was introduced with the 1.) release for
this8
!ileJK roots = !ile.listCoots():
for(int i=E:iUroots.length:iPP)
+ystem.out.println(%CootJ%PiP%K8% P rootsJiK):
1A) *ow to insert content into the middle of a file without o"erwriting the eisting content?

There is no direct support for inserting content in the middle of a file5stream.
What you need to do is copy the original content into another file5stream with the
new content added where necessary.
1B) *ow do $ get the creation date and time of a file?

Page 42 of 136
There is no support for getting the creation date and time of a file from 2a"a. 3ll
you can get is when the file was last modified, with the the last?odified() method
of !ile.
)E) *ow can you combine multiple input streams to be treated as one?

The +equence$nput+tream class in the standard #a"a.io pac'age allows you to
combine multiple input streams into one. -ou can either create a "ector of
streams, passing the elements() to the constructor, or combine two directly in a
constructor.
)1) *ow can $ rename a file?

The !ile class has a renameTo() method that allows you to rename files, #ust
pass in an argument of the new name as a !ile ob#ect. 3 boolean status is
returned to report success or failure.
))) When do you use the Ceader5Writer classes, instead of the $nput+tream5&utput+tream
classes?

The $nput+tream5&utput+tream classes are for reading and writing bytes, while
the Ceader5Writer classes are for reading characters 5 tet. $f you need to
process tet, you use Ceader5Writer. $f you need to process content at the byte
le"el, either as the raw bytes, or as higher le"el data li'e primiti"es (through
Gata$nput5&utput), ob#ects (through &b#ect$nput5&utput), or possibly compressed
data (.O$I$nput5&utput), then you would wor' with an $nput+trem5&utput+tream.
)0) *ow can $ ma'e a file writable that is currently read1only?

There is only support in 2a"a to ma'e a writable file read1only. There is no way to
go the other way. $ guess someone considered this a security ris' so didn,t add
an appropriate 3I$ to perform.
)6) *ow can $ trap system1specific 'ey sequences li'e /trl13lt1Gel?

3las, using pure, portable 2a"a, you cannot trap those sorts of system1specific
'ey sequences.
)=) *ow can $ get the current wor'ing directory with 2a"a?

The current wor'ing directory is stored in the system property %user.dir%. The
following eample shows how to read this system property from your application8
Page 43 of 136
public class userdir 9
public static "oid main(+tringJK args) 9
+ystem.out.println(%Wor'ing Girectory = % P
+ystem.getIroperty(%user.dir%)):
;
;
)>) What is a resource lea'?

.arbage collection manages only memory, not other system resources. $f your
2a"a program has plenty of free memory, garbage collection will not be triggered
automatically. 4sually, howe"er, there are other resources that are more limited
than memory. !or eample, all &+es ha"e limits on the number of soc'ets, file
handles, etc. that can be open. +ometimes this limit is quite low. This is true e"en
on a des'top, e.g. if your system has 1)AF7 of memory, your 2a"a program can
easily allocate all the a"ailable file handles without coming near to filling up the
heap. $f this happens, your 2a"a program will fail. This is what we call a resource
lea: the unintentional maintenence of references to non1memory resources.
This is why it is important in 2a"a to eplicitly manage non1memory resources.
/lasses which utili(e non1memory resources should pro"ide ways to eplicitly
allocate5deallocate those resources, independent of garbage collection. !or
eample Soc)et, /nputStream and OutputStream each pro"ide eplicit
close() methods for deallocation of file descriptors, .indo" pro"ides a
dispose() method to free the window handle, etc. The way to properly use
these classes is to allocate using the constructor, then deallocate using the
appropriate method (deallocation is preferably done in a finally12 bloc', so it
will eecute whether or not an eception is thrown during use). These classes do
release these non1memory resources in their finalie() method, but
remember that the finali(er only gets called by the garbage collector, and if the
ob#ect is ne"er collected, it will ne"er be finali(ed, hence will ne"er release the
resources.
)@) Why are there two type of $5& in 2a"a, namely byte streams and character (Ceader5Writer)
streams?

The Ceader and Writer classes were added to 2GF 1.1 to support
internationali(ation, since the eisting streams at that time didn,t properly support
the use of multi1byte 4nicode characters or character encodings other than
3+/$$. The Ceader and Writer classes ma'e it possible to wor' with
internationali(ed character streams rather than byte streams.
)A) $s there an easy way of counting line numbers? &r do you ha"e to go through the entire
file?

Page 44 of 136
-ou ha"e to go through the entire file.
try 9
Mine<umberCeader lnr = new Mine<umberCeader(new !ileCeader(filename)):
+tring s:
while ((s = lnr.readMine()) V= null):
+ystem.out.println(%Mines8 % P lnr.getMine<umber()):
)B) What is piped $5& used for?

The piped $5& streams are for inter1thread communication. They manage the
synchroni(ation across thread boundaries of the buffer.
0E) *ow can $ show a progress bar while reading a file?

*ere,s a simple eample of monitoring file read progress
import #a"a.awt.!lowMayout:
import #a"a.awt.e"ent.3ctionD"ent:
import #a"a.awt.e"ent.3ctionMistener:
import #a"a.io.!ile$nput+tream:
import #a"a.io.$nput+tream:
import #a"a.swing.27utton:
import #a"a.swing.2!rame:
import #a"a.swing.Irogress?onitor$nput+tream:
public class Test 9
public static "oid main(+tringJK args) 9
55 create a test frame with a %press me% button
final 2!rame f = new 2!rame(%+ample%):
f.get/ontentIane().setMayout(new !lowMayout()):
27utton b = new 27utton(%Iress me%):
f.get/ontentIane().add(b):
f.pac'():
55 set up the file read action
b.add3ctionMistener(new 3ctionMistener() 9
public "oid actionIerformed(3ctionD"ent e) 9
55 when button is pressed, start a new thread
55 to read the file. 3 new thread is needed because we
55 need to free the .4$ update thread to paint the
55 progress monitor
new Thread() 9
public "oid run() 9
try 9
Page 45 of 136
55 open the file, wrapping it in a Irogress?onitor$nput+tream
$nput+tream in = new !ile$nput+tream(%c8WWbigfile.bin%):
Irogress?onitor$nput+tream pm =
new Irogress?onitor$nput+tream(f,%Ceading the big file%,in):
55 read the file. $f it,s ta'ing too long, the progress
55 monitor will appear. The amount of time is roughly
55 151EEth of the estimated read time (based on how long
55 it too' to read the first 151EEth of the file.)
55 <ote that by default, the dialog won,t appear unless
55 the o"erall estimate is o"er ) seconds.
int c:
while((c=pm.read()) V= 11) 9
55 do something
;
pm.close(): 55 needs better error handling, of course...
;
catch(Dception e) 9
e.print+tac'Trace():
;
;
;.start ():
;;):

55 display the frame
f.setGefault/lose&peration(2!rame.DQ$TY&<Y/M&+D):
f.setLisible(true):
;
;
01) *ow do $ initiali(e a 2Tet3rea from an input file?

The 2Tet/omponent pro"ides a read() method to initiali(e the tet component8
2Tet3rea ta = new 2Tet3rea():
Ceader reader = new !ileCeader(filename):
ta.read(reader, null):
The second parameter is a description.
0)) *ow to ma'e a file read only?

!or any type of file, #ust use the setCead&nly() method of !ile to mar' a file as
read1only. There is no argument to ma'e it writable once it is read1only.
Page 46 of 136
$1A<
1) What is 4nicode?
4nicode pro"ides a standard encoding for the character sets of different languages. The
encoding is independent of the platform, program, or language used to access said data. Lisit
the 4nicode /onsortium (http855www.unicode.org) to learn more about 4nicode de"elopments.
)) *ow can $ get the number of days that ha"e elapsed between two Gate ob#ects?
That depends on what you mean by %between%.
$f you want to find out the number of )61hour periods between two Gate ob#ects d1 and d) (d)
X d1) then you would do this8
double days = (d).getTime()1d1.getTime())51EEE5>E5>E5)6:
+ince Gate.getTime returns milliseconds, you di"ide by 1EEE to get seconds, by >E to get
minutes, by >E again to get hours, and by )6 to get days.
+ometimes this can cause difficulties, especially in countries that ha"e a form of daylight
sa"ings time. !or eample, in the 4.+., there is one day in the !all which has )= hours, and
one day in the +pring which has )0 hours. 3n elapsed1number1of1days calculation on Gates
falling on one of these days may not gi"e the answer you epect.
3nyway, that,s the easy way, and if you,re satisfied with that, then read no further.
$f, on the other hand, you mean the number of midnight1crossings (so that the number of days
elapsed between 118EE I? and 18EE 3? the net day is 1) then you,re better off using the
/alendar class and computing the 2ulian Gay.
7y the way, don,t mista'e the 2ulian Gay for the 2ulian /alendar. The two are different and
named after different %2ulians%.
The 2ulian Gay is defined as the number of days elapsed since <o" )6, 6@16 7/, 1)8EE .?T
.regorian. The year was chosen as being sufficiently in the past so as not to ha"e negati"e
2ulian Gays, the date was chosen because of the (in that year) 0@1day difference between the
2ulian and .regorian calendars (<o" )6, 6@16 7/ .regorian would be 2an 1, 6@10 7/ 2ulian),
and the time was chosen because astronomers do their wor' at night, and it would be a little
confusing (to them) to ha"e the 2ulian Gay change in the middle of their wor'. ($ could be
wrong)
3nyway, the algorithm for computing the 2ulian Gay from a .regorian or 2ulian calendar date
for years 6EE 3G and abo"e is as follows8
Met the date be -, ?, G, where - is the 3G year, ? is the month (2anuary=1, Gecember=1)),
and G is the day (1101).
!or the following calculations, use integer arithmetic (i.e. lop off the fractional part of any
result).
Page 47 of 136
$f ?==1 or ?==) then -11, ?P=1).
Met 3 = -51EE
Met 7 = 356
Met / = )1317 (or /=E if you,re using the 2ulian calendar)
Met D = 0>=.)=N(-P6@1>)
Met ! = 0E.>EE1N(?P1)
2ulian Gay = /PGPDP!11=)6.=
There would be a further ad#ustment for the time of day, but we,re not loo'ing at that. $f you
want your 2ulian Gays to start at midnight, subtract 1=)6 rather than 1=)6.=.
3nd so, your number1of1days1elapsed calculation would loo' li'e this8
/alendar c1 = new .regorian/alendar ():
/alendar c) = new .regorian/alendar():
c1.setTime (d1):
c).setTime (d)):
long #1 = #ulianYday(c1.get(-D3C),
c1.get(?&<T*)P1, c1.get(G3-)):
long #) = #ulianYday(c).get(-D3C),
c).get(?&<T*)P1, c).get(G3-)):
long daysYelapsed = #)1#1:
3nd this would properly calculate the number of midnight1crossings between 118EE I? on one
day and 18EE 3? the net day.
-ou can get a little more information about the 2ulian Gay calculations here.
-ou can get much more information about different calendar systems here, here, and here.
0) What is a Cesource7undle and what it is used for?
3 Cesource7undle is li'e a speciali(ed form of a *ashtable that maps strings to "alues. That
doesn,t sound too eciting by itself, but the magic of Cesource7undle allows you to ha"e
different loo'up tables based upon what Mocale (language5country) a user is coming in from.
3nd, if a setting doesn,t change between languages5countries, there is no need to repeat the
setting in the customi(ed bundle, as the runtime will search through se"eral bundles until it
finds a mapping (though in theory it could find none). Cesource bundles also support another
le"el of "ariants beyond language5country, such that you can ha"e customi(ed
labels5messages for people in /alifornia and <ew -or'.
Page 48 of 136
6) *ow can $ get yesterday,s date?
55 get /alendar with current date
#a"a.util..regorian/alendar g/al =
new .regorian/alendar():
55 get yesterday,s date
g/al.add( /alendar.G3TD, 11 ):
55 get components of yesterday,s date
+tring s?onth = ( g/al.get( /alendar.?&<T* ) P 1 ) P %%:
+tring sGay = g/al.get( /alendar.G3TD ) P %%:
+tring s-ear = g/al.get( /alendar.-D3C ) P %%:
55 get yesterday,s date in milliseconds
long l?illis = g/al.getTime().getTime():
=) *ow do $ display and parse a date?
The 2a"a $1A< way is to use a Gate!ormat. While +impleGate!ormat, which is generally
returned, creates a large number of ob#ects, it is locale aware and will handle most of your
needs. The following sample code initially creates a #a"a.sql.Gate ob#ect and formats it for the
default locale. 3n initial actionIerformed call additionally formats5displays it for a .erman
locale and also displays the resulting #a"a.sql.Gate in standard escape format. &ther dates can
be entered and parsed after the initial display.
55 2G!GI.#a"a 1 Gisplay and Iarse #a"a.sql.Gate
import #a"a.sql.N:
import #a"a.swing.N:
import #a"a.awt.N:
import #a"a.awt.e"ent.N:
import #a"a.tet.N:
import #a"a.util.N:
public class 2G!GI etends 2!rame
implements 3ctionMistener,
WindowMistener
9
55 create a #a"a.sql.Gate
#a"a.sql.Gate #sqlGate = new #a"a.sql.Gate(
+ystem.currentTime?illis() ):
Gate!ormat dfMocal = Gate!ormat.getGate$nstance(
Gate!ormat.+*&CT ):
Gate!ormat df.ermany = Gate!ormat.getGate$nstance(
Gate!ormat.+*&CT, Mocale..DC?3<- ):
27utton #b = new 27utton( %.o% ):
2Mabel #l$ = new 2Mabel(%$nput a Gate8%),
Page 49 of 136
#lG = new 2Mabel(%Gisplay .erman8%),
#lI = new 2Mabel(%Iarsed8%):
2Ianel #p = new 2Ianel():
2Tet!ield #t$ = new 2Tet!ield( 1E ),
#tG = new 2Tet!ield( 1E ),
#tI = new 2Tet!ield( 1E ):
public 2G!GI()
9
super( %2G!GI% ):
addWindowMistener( this ):
#b.add3ctionMistener( this ):
#p.add(#l$):
#p.add(#t$):
#p.add(#b):
#p.add(#lG):
#p.add(#tG):
#p.add(#lI):
#p.add(#tI):
get/ontentIane().add( #p, 7orderMayout./D<TDC ):
pac'():
55 set tet by sending dummy e"ent
#t$.setTet( dfMocal.format( #sqlGate ) ):
actionIerformed(
new 3ctionD"ent( this, 1), %1)% ) ):
show():
; 55 end constructor
55 3ctionMistener $mplementation
public "oid actionIerformed(3ctionD"ent e)
9
#tG.setTet( %% ):
#tI.setTet( %% ):
try
9
#a"a.util.Gate d = dfMocal.parse(
#t$.getTet() ):
#t$.setTet( dfMocal.format( d ) ):
#tG.setTet( df.ermany.format( d ) ):
Page 50 of 136
d = df.ermany.parse( #tG.getTet() ):
55 get new #a"a.sql.Gate
#sqlGate = new #a"a.sql.Gate( d.getTime() ):

#tI.setTet( #sqlGate.to+tring() ):
;
catch( IarseDception pe ) 9 #t$.setTet( %% ): ;
; 55 Dnd actionIerformed
55 Window Mistener $mplementation
public "oid window&pened(WindowD"ent e) 9;
public "oid window/losing(WindowD"ent e)
9
dispose():
+ystem.eit(E):
;
public "oid window/losed(WindowD"ent e) 9;
public "oid window$conified(WindowD"ent e) 9;
public "oid windowGeiconified(WindowD"ent e) 9;
public "oid window3cti"ated(WindowD"ent e) 9;
public "oid windowGeacti"ated(WindowD"ent e) 9;
55 Dnd Window Mistener $mplementation
public static "oid main(+tringJK args)
9
new 2G!GI():
;
; 55 end class 2G!GI
+eriali(ation
1) What is ob#ect seriali(ation?
'eriali(ing an ob#ect in"ol"es encoding its state in a structured way within a byte
array. &nce an ob#ect is seriali(ed, the byte array can be manipulated in "arious
ways: it can be written to a file, sent o"er a networ' using a soc'et1based
connection or C?$, or persisted within a database as a 7M&7.
The seriali(ation process encodes enough information about the ob#ect type
within the byte stream, allowing the original ob#ect to be easily recreated upon
deseriali(ation, at a later point in time.
)) /an $ persist my ob#ects using seriali(ation instead of using a relational or ob#ect
database?
Page 51 of 136
<o. While seriali(ation is a highly "ersatile mechanism ha"ing numerous
applications, your long term storage needs should continue to be addressed by
con"entional relational or ob#ect databases.
<ote that seriali(ation does not pro"ide any features for transaction management
and concurrency control. <or does it pro"ide typical database features li'e
indeed access, caching and a query language.
0) Why doesn,t seriali(ation sa"e the "alue of static "ariables?
Lariables declared as static members are not considered part of the state of an
ob#ect because they are shared by all instances of that class. /lasses which
need to preser"e the "alue of static members during seriali(ation should sa"e
and restore these "alues eplicitly using private void
readObject(Object/nputStream) and private void
"riteObject(ObjectOutputStream).
6) What are the ad"antages and disad"antags of seriali(ation?
The ad"antages of seriali(ation are8
$t is easy to use and can be customi(ed.
The seriali(ed stream can be encrypted, authenticated and compressed,
supporting the needs of secure 2a"a computing.
+eriali(ed classes can support coherent "ersioning and are fleible
enough to allow gradual e"olution of your application,s ob#ect schema.
+eriali(ation can also be used as a mechanism for echanging ob#ects
between 2a"a and /PP libraries, using third party "endor libraries (li'e
CogueWa"e,s Tools.hPP ) within /PP.
There are simply too many critical technologies that rely upon
seriali(ation, including C?$, 2a"a7eans and D27.
*owe"er, seriali(ation has some disad"antages too8
$t should ideally not be used with large1si(ed ob#ects, as it offers significant
o"erhead. Marge ob#ects also significantly increase the memory
requirements of your application since the ob#ect input5output streams
cache li"e references to all ob#ects written to or read from the stream until
the stream is closed or reset. /onsequently, the garbage collection of
these ob#ects can be inordinately delayed.
The +eriali(able interface does not offer fine1grained control o"er ob#ect
access 1 although you can somewhat circum"ent this issue by
implementing the comple Dternali(able interface, instead.
+ince seriali(ation does not offer any transaction control mechanisms per
se, it is not suitable for use within applications needing concurrent access
without ma'ing use of additional 3I$s.
=) What things are required for a class that implements Serialiable?
Page 52 of 136
3 class that implements +eriali(able must also8
*a"e access to a no1argument constructor in its first non1seriali(able
superclass
$dentify non1seriali(able data members using the transient 'eyword or
eplicitly mar' data members as seriali(able using the
serial3ersistentFields member.
>) ?y subclass implements Serialiable but my superclass doesn,t. 7oth subclass and
superclass contain instance "ariables that need to be sa"ed as part of the state of the
subclass. Will seriali(ation sa"e the superclass fields for me?
When you seriali(e an ob#ect, the seriali(ation mechanism wor's by chaining up
the inheritence hierarchy, sa"ing the sate of each +eriali(able superclass in turn.
When seriali(ation reaches the first non1seriali(able superclass, the seriali(ation
stops.
When deseriali(ing, the state of this first non1seriali(able superclass is restored
not from the stream, but by in"o'ing that class, no1argument constructor. $f the
no1argument constructor is not adequate for your purposes, you must customi(e
the seriali(ation of your subclass with "riteObject() and readObject() in
order to write out and restore any information from the non1seriali(able
superclass that you find necessary.
@) What role does seriali(ation ha"e in C?$?
C?$ uses seriali(ation as its basic and only mechanism for sending ob#ects
across a networ'.
$f an ob#ect implements java.rmi.+emote, then the ob#ect,s stub is seriali(ed
and sent to the client. $f the ob#ect implements java.io.Serialiable, then
the ob#ect itself is seriali(ed and sent.
A) Why would $ want to implement E%ternaliable instead of Serialiable?
7y implementing E%ternaliable yourself you can win performance at the
cost of fleibility and etra code to maintain. $f you implement E%ternaliable
yourself you stream the data directly without the need for reflection which is used
in the case of Serialiable.
B) *ow can $ read and write seriali(ed ob#ects to and from a database?
$f your CG7?+ supports them, you can store seriali(ed ob#ects as 7M&7s.
These are 2G7/ ).E features, but ta'e a loo' at java.sql.'lob, +esultSet
and 3reparedStatement for more information.
Page 53 of 136
1E)/an a 4ector or a 5as,table be seriali(ed and deseriali(ed?
7oth these classes implement +eriali(able, and ha"e been designed for
seriali(ation. +o yes, they can be seriali(ed.
&ne thing you ha"e to watch out for, though, is that in order to seriali(e a
collection li'e 4ector or 5as,table, you must also be able to seriali(e all of
the ob#ects contained in these collections. &therwise, the collection would not be
able to be completely restored. -our program will throw a
6otSerialiableE%ception unless all ob#ects stored in the 4ector or
5as,table are also seriali(able.
11) $s there any way to sa"e the state of an ob#ect of a class which does not
implement +eriali(able or Dtenali(able?.
-es. -ou will ha"e to write the "alue of each and e"ery instance "ariable into the persistent
storage. $f there are 1EE "ariables, you will ha"e to store each of them indi"idually. $f some
of the "ariables are ob#ect references, you will ha"e to follow each reference and sa"e the
state of that ob#ect as well. -ou can do that, but it would be a proprietary solution and each
class that wanted to read your ob#ect would also ha"e to 'now all about your proprietary
format.
1)) What is the role of seriali(ation in D27?
3 big part of D27 is that it is a framewor' for underlying C?$8 remote method
in"ocation. -ou,re in"o'ing methods remotely from 2L? space ,3, on ob#ects
which are in 2L? space ,7, 11 possibly running on another machine on the
networ'.
To ma'e this happen, all arguments of each method call must ha"e their current
state pluc'ed out of 2L? ,3, memory, flattened into a byte stream which can be
sent o"er a T/I5$I networ' connection, and then deseriali(ed for reincarnation
on the other end in 2L? ,7, where the actual method call ta'es place.
$f the method has a return "alue, it is seriali(ed up for streaming bac' to 2L? 3.
Thus the requirement that all D27 methods arguments and return "alues must be
seriali(able. The easiest way to do this is to ma'e sure all your classes
implement #a"a.io.+eriali(able.
+ecurity
1) What is %pri"ate 'ey%5%symmetric%5%secret 'ey% cryptography?
3 pri"ate 'ey cryptography algorithm uses the same 'ey for encryption and decryption.
+ince the 'ey is the only data required to decrypt the ciphertet, it must be 'ept
pri"ate5secret.
Page 54 of 136
Dncryption: creating ciphertet from plaintet with a specific encryption algorithm and an
encryption 'ey
Gecryption: reco"ering plaintet from cipertet using a specific encryption algorithm and a
decryption 'ey
)) What is %public 'ey%5%asymmetric% cryptography?
3 public 'ey cryptography algorithm uses two different (but related) 'eys for encryption and
decryption. The 'ey used for decryption is 'ept secret (Iri"ate) whereas the encryption 'ey
can be distributed openly (Iublic). Thus, anyone in possession of the public encryption 'ey
may encrypt and send a message to the holder of the pri"ate decryption 'ey. *owe"er,
only the holder of the pri"ate decryption 'ey may decipher the message. 7oth 'eys must be
created and used in con#unction, and are often referred to as a 'ey pair.
0) What is hybrid cryptography?
/ombination of public and pri"ate 'ey cryptography, where the echange of an
encrypted session 'ey is done using public 'ey cryptography. The following
encrypted session is then pursued with pri"ate5symmetric 'ey cryptography. The
main reason is that pri"ate 'ey cryptography is generally much quic'er than
public 'ey cryptography.
6) What is a ?essage Gigest?
3 ?essage Gigest is a digitally created hash (fingerprint) created from a plaintet
bloc'. 3ll the information of the message is used to construct the ?essage
Gigest hash, but the message cannot be reco"ered from the hash. !or this
reason, ?essage Gigests are also 'nown as one %ay hash !unctions.
The si(e of a ?essage Gigest is always the same, independent of the si(e or content of the
message from which it was created. .enerally, the si(e of a ?essage Gigest is fairly short
( 1E)6 bits). The ideal ?essage Gigest algorithm would possibly alter =ET of the bits in the
resulting hash if one bit was altered in the plaintet message.
=) What is a Gigital +ignature?
Gigital +ignatures are used to ensure the identity of a sender. $n con#unction with ?essage
Gigests, Gigital +ignatures pre"ents someone from altering a message and falsely claiming
you wrote the altered message. Gigital +ignatures are a byproduct of public 'ey cryptography,
as demonstrated below. (7elie"e me, it is simpler to describe the concept of a Gigital +ignature
by ta'ing an eample).
>) What do you need to establish computer security?
There are essentially four aspects of computer security8
Page 55 of 136
Aspect
Generally
achieved by
Explanatin E!!ect
"n!identiality Encryptin
#rtects $essage cntent !r$
any but sender and recipient
%rans$issin
eavesdrppers
cannt read r
use the
$essage
cntent&
Integrity
'essage
(igest
)eri!ies that a $essage has nt
been $di!ied since it *as sent
%rans$issin
hi+ac,ers
cannt $di!y
$essage in
transit
Authenticity
(igital
-ignature .
#ass*rd
/ni0uely identi!ies the sender
! a $essage
)eri!icatin !
actual sender
pssible
Nnrepudiatin
"ryptgraphic
1eceipt
#revents a sender !r$ !alsely
denying sending a $essage
'essage
recipient can
prve that a
$essage *as
sent by sender
@) What is ++M?
++M stands for +ecure +oc'et Mayer. $t is a protocol de"eloped by <etscape for
encrypting information sent between processes o"er T/I5$I soc'ets. $t sits
between application software and the T/I5$I soc'ets. -ou,ll find it frequently
used between web browsers and web ser"ers using the https 4CM prefi,
pro"iding encryption, integrity, authentication, and non1repudiation.
A) *ow can $ support *TTI+ (++M) in a ser"let?
The ser"let technology by design already supports https (++M). *owe"er, the
way this wor's is not through the ser"let technology but through the Web +er"er.
The web ser"er controls whether information is done securely (https) "ersus non1
securely (http).
&ne way to force ser"lets to go down the https path is to define your web ser"er
to only allow secure connections when accessing ser"lets. $n $$+ this can be
accomplished through the definition if $+3I$ filters. The $+3I$ filter can instruct
the web ser"er to route all requests that end with a pre1defined prefi to the
ser"let engine. The tric' is to then define files, with the predefined etension, in
the web ser"ers directory. !or eample, if the ser"let,s name is ?y+er"let a file
with the name ?y+er"let. would be placed on the web ser"er. 3ll calls to this
file would be routed to the ser"let engine. 3nd $$+ would be used to force all calls
Page 56 of 136
to the ?y+er"let. file to go through https. The 2Cun ser"let engine has
eamples of how to do this documented on their web page.
3pplets
1) *ow can $ download a file (for instance, a ?icrosoft Word document) from a ser"er
using a ser"let and an applet?
Try telling the applet to call
get3pplet/ontet().showGocument(%http855foo.com5whate"er5blah.doc%). That
ma'es the browser responsible for fetching and sa"ing the document (including
putting up the %+a"e 3s% dialog).
-ou may also want to chec' the web ser"er configuration to ma'e sure the
approprate ?$?D1type configuration is set. $f your ser"let is the one fetching the
document (or creating it on the fly), then it must set the ?$?D1type using
response.setContent(ype(7application8ms9"ord7) or equi"alent.
)) *ow do $ get an applet to load a new page into the browser?
$n short, get the applet,s contet and tell it to show a different document8
get&ppletConte%t().s,o":ocument(ne"
;+0(7,ttp<88foo.com8",atever8bla,.doc7)). -ou can also pro"ide a
target frame string as in get&ppletConte%t().s,o":ocument(ne"
;+0(7,ttp<88foo.com8",atever8bla,.doc7)= 7target7). There are
four special targets strings. 3ny other string will act as a named top1le"el window,
if the frame doesn,t eist.
%Yself% +how in same frame as applet
%Yparent% +how in the applet,s parent frame
%Ytop% +how in the top1le"el frame of the applet,s window
%Yblan'% +how in a new, unnamed top1le"el window
0) What is the synta of the U3IIMDTX tag?
U3IIMDT
55 Cequired
/&GD = applet)lass or
&72D/T = seriali(ed"pplet
*D$.*T = pi*els
W$GT* = pi*els
55 &ptions
/&GD73+D = codebase+R,
3C/*$LD = archive,ist
3MT = alternateTe*t
<3?D = instance-ame
3M$.< = alignment
Page 57 of 136
*+I3/D = pi*els
L+I3/D = pi*els
X
UI3C3? <3?D = attribute. L3M4D = value.X
UI3C3? <3?D = attribute/ L3M4D = value/X
...
"lternate 0TM,
U53IIMDTX
+upport for &72D/T is limited.
6) *ow do $ create an applet that accepts an unlimited number of parameters?
While there is some upper bounds to the number of parameters the browser will
let you specify, if you would li'e to let a user specify an undefined number of
"alues, you can let them specify a parameter with a number at the end and 'eep
counting until no more parameters following that pattern are there, as in8
Uapplet code=Iarams width=1E height=1EX
Uparam name=IaramE "alue=*elloX
Uparam name=Iaram1 "alue=WorldX
U5appletX
To do this, you #ust increment a counter for the getIarameter() calls8
import #a"a.applet.N:
public class Iarams etends 3pplet 9
public "oid init() 9
+tring "alue:
int i = E:
while (("alue = getIarameter(%Iaram% P i)) V= null) 9
+ystem.out.println (%Iaram% P i P %8 % P "alue):
iPP:
;
;
;
=) *ow can $ connect from an applet to a database on the ser"er?
There are two ways of connecting to a database on the ser"er side.
1. The hard way. 4ntrusted applets cannot touch the hard dis' of a
computer. Thus, your applet cannot use nati"e or other local files (such as
2G7/ database dri"ers) on your hard dri"e. The first alternati"e solution is
to create a digitally signed applet which may use locally installed 2G7/
dri"ers, able to connect directly to the database on the ser"er side.
Page 58 of 136
). The easy way. 4ntrusted applets may only open a networ' connection to
the ser"er from which they were downloaded. Thus, you must place a
database listener (either the database itself, or a middleware ser"er) on
the ser"er node from which the applet was downloaded. The applet would
open a soc'et connection to the middleware ser"er, located on the same
computer node as the webser"er from which the applet was downloaded.
The middleware ser"er is used as a mediator, connecting to and etract
data from the database.
>) *ow do $ display a message in the browser,s status bar?
To show a message in the status bar, you would call the s,o"Status() method
of the &ppletConte%t8
get3pplet/ontet().show+tatus(message):
Feep in mind that the browser can o"erwrite the message at any time or the
browser might not ha"e a "isible status bar. This basically means you should not
use the status bar for messages that might be missed.
@) What are the main differences between applets and applications?
3pplets are created to be embedded within a browser. 3s such, they ha"e
methods that are automatically called by the browser at certain times8 init() when
first loaded, start() when page loaded5entered, stop() when page left, destroy()
when applet unloaded, and paint() when the screen needs to be displayed. $n
addition, applets ha"e se"ere security restrictions as they can be loaded from
untrusted sources o"er the $nternet. 3pplications on the other hand need to be
installed locally, start eecution with the main() method, and ha"e no inherent
security restrictions. 7eyond this, applications control their own operations.
A) *ow can $ get the real local host $I address in an applet?
3pplet security restrictions do not let you get this in an untrusted applet "ia
$net3ddress.getMocal*ost().
*owe"er, you can get this address by creating a +oc'et connection bac' to the
web ser"er from which you came and as'ing the +oc'et for the local address8
4CM url = getGocument7ase():
+tring host = url.get*ost():
+oc'et soc'et = new +oc'et(host, AE):
$net3ddress addr = soc'et.getMocal3ddress():
+tring host3ddr = addr.get*ost3ddress():
+ystem.out.println(%3ddr8 % P host3ddr):
B) *ow do $ load a seriali(ed applet?

Page 59 of 136
$nstead of specifying the /&GD attribute of an U3IIMDTX tag, you use the
&72D/T attribute, as in8
U3IIMDT
&72D/T=The3pplet.ser
W$GT*=0EE
*D$.*T=0EE
X
U53IIMDTX
This allows you to preinitiali(e your applet to some sa"ed state, instead of ha"ing
to reinitiali(e your applet each time it is loaded.
+upport for this in browsers is se"erly limited. Gon,t rely on it.
1E) !rom one applet, how do $ communicate with another applet loaded from the same
ser"er?
$t really doesn,t matter that they are loaded from the same ser"er, as long as they
are running in the same 2L? in the browser, you can call methods between
them.
$f you include a name12applet"2 "alue in the applet tag of the applet you want to
call methods on, you get a reference to it by using the 3pplet/ontet8
?y3pplet appl = (?y3pplet) get3pplet/ontet().get3pplet(%applet3%):
if (null V= appl) 9
appl.register(%*ello thereV%, this):
;
/hec'ing that you get a reference to the class you epect is left as an eerci(e to
the reader 81)
11)$n an applet, is the start() or paint() method eecuted first?
The initial order in which the lifecycle methods of applets are eecuted when
loaded is8
init()
start()
paint()
3nd when done8
stop()
destroy()
Page 60 of 136
This also holds when you call repaint() in the init() method. *owe"er, the
init() method will not be called if you load a seriali(ed applet.
1))What are the main differences between 2a"a7eans and applets?
3pplets are 2a"a programs which are meant to be run by an applet1runner (which
is typically inside a web browser). 7y definition, applets are applets because they
inherit from #a"a.applet.3pplet. 3lso, applets are pretty constrained in what they
are5aren,t allowed to do.
Traditional 2a"a7eans are 2a"a software components. 3 bean may be a single,
simple, standalone class or it may be a complicated behemoth but, as long as it
follows the rules and con"entions of 2a"a7eans, then it,s a 2a"a7ean.
10)*ow do $ use an applet that resides on a remote machine?
-ou would specify the location of the class files in the /&GD73+D attribute of
the U3IIMDTX tag8
Uapplet code=?y3pplet
width = 0EE height = 0EE
/&GD73+D=%http855www.#guru.com5appletdirectory5%X
U5appletX
16)When you communicate with a ser"let from an 3pplet or an application, how can
you ensure that the session information is preser"ed? That is, how do you
manage coo'ies in applet1ser"let communication?
!or sessions, your best bet is to ha"e the ser"let rewrite the 4CMs to include the
session information. With coo'ies read $ am writing an application that retrie"es a
4CM, but that 4CM requires a coo'ie. $s there a way to hold that coo'ie within my
application and send it bac' to the 4CM when requested? Dssentially, you can send
the coo'ie bac' easily with *TTI. !or instance,
url/onnection.setCequestIroperty(%coo'ie%,Ycoo'ie): Where the Ycoo'ie is coming
from a pre"ious call8 +tring Ycoo'ie = url/onnection.get*eader!ield(%set1coo'ie%):
1=)*ow can $ change my application into applet?
/reate a subclass of #a"a.applet.3pplet
Ta'e the code in the main() method of the application and mo"e it to the
init() method of the applet
/reate an *T?M file to load the applet
$f necessary, mo"e any requirements that untrusted applets cannot do into
an appropriate ser"er1side tas'
$f necessary, modify all getting of support files
Test
1>)$n detail, how do the applet life cycle methods init(), start(), paint(), stop(), and destroy()
wor'?
Page 61 of 136
The life cycle methods of an applet are init(), start(), stop(), and destroy(). While
frequently grouped with the methods, the paint() method is not really part of the
applet,s life cycle. The method is #ust called by the browser whene"er a part of
the screen has become in"alidated or in response to a programmer1generated
repaint request. The update() method falls into the same category as paint().
3s far as the other methods go8
init() 1 called once when applet is loaded
start() 1 called e"ery time the page the applet is located on is loaded, after
init() or after lea"ing the page and returning
stop() 1 called e"ery time the page the applet is located on is left
destroy() 1 called when applet is unloaded
$f loading a seriali(ed "ersion of an applet from a .ser file (&72D/T attribute in
U3IIMDTX tag instead of /&GD attribute), the init() method is not called.
4se the start() 5 stop() method pair to deal with starting and stopping threads, as
when the page isn,t acti"e it isn,t nice to use up resources.
Gon,t rely on the destroy() method being called to free a crucial resource, in case
the browser crashes.
$ had heard that start() 5 stop() were called for iconifying and deiconifying, but a
test with the latest browser "ersions shows they aren,t called.
1@)*ow does an applet get loaded into the browser?
The browserSs *T?M interpreter reads the parameters from the 3IIMDT tag. The
rele"ant parameters used to load the appletSs class are /&GD, /&GD73+D, and
3C/*$LD (/&GD73+D and 3C/*$LD are optional 1 &72D/T can be used
instead of /&GD). The /&GD parameter holds the name of the appletSs class
file. The /&GD73+D holds the class file directory (the default is the current
directory), and the 3C/*$LD is the name of a #ar or (ip file that the appletSs class
files are stored in (the default is no archi"e).
The browser then reads the byte code from the class files and performs a
"erification pass, chec'ing for access "iolations and in"alid opcodes (among
other things). The 2a"a Lirtual ?achine (2L?) then builds an ob#ect for each
class (pro"ided the ob#ects ha"e not been created by a pre"ious instance), and
eecutes any static code in each ob#ectSs initiali(ation section. &b#ect initiali(ation
also includes the construction of the superclass ob#ects (the superclass files from
3pplet to &b#ect are typically loaded from the browserSs own 2a"a 3I$ on the
local file system).
$f the applet ma'es it this far without generating security eceptions, missing
class errors, or common errors in static code segments, the 2L? will ma'e calls
to initiali(ation functions in the superclass, then to the appletSs init() member.
Page 62 of 136
1A)What is needed in the 3IIMDT tag to cause an applet to be loaded from a 23C file?
To specify an that an applet loads from a 23C file, instead of from separate
classes, add an 3C/*$LD attribute to your U3IIMDTX tag8
U3IIMDT
/&GD=3pplet/lass
3C/*$LD=%foo.#ar%
W$GT*=)EE
*D$.*T=)EEX
U53IIMDTX
$f you need to specify multiple 23C files, pro"ide a comma separated list.
1B)When should one use applets and when should one use ser"lets?
3pplets run inside browsers, and ser"lets run inside ser"ers. +o broadly
spea'ing, use applets when you need dynamism on the client side, and use
ser"lets when you need dynamism on the ser"er side.
+er"lets can produce any *T?M (or indeed, any file type), and therefore are
much more "ersatile than applets. +er"lets can tailor the *T?M they produce
based on the browser type (as specified in the %4ser13gent% header), and thus
can produce output that will wor' in "irtually any client, including W3I browsers
or the li'e. 3pplets are notoriously poorly supported, and e"en in browsers that
ostensibly ha"e 2a"a support, don,t wor' consistently.
+er"lets can also produce *T?M with embedded 2a"a+cript, which allows a fair
amount of dynamic beha"ior on browsers which support it.
*owe"er, due to the infuriating limitations and bugs in 2a"a+cript, sometimes
you,"e #ust got to ha"e an applet to get the client1side beha"ior you want. $n
these cases, ta'e comfort in the fact that you can generate *T?M containing
3IIMDT tags from inside a ser"let.
)E)Why do $ not create a constructor for an applet?
&ne doesn,t see constructors in applets because the applet container doesn,t
guarantee a complete en"ironment ("alid applet contet) until the init() method is
called.
)1)Why doesn,t applet"iewer appletclass.class wor'?
3pplets are loaded with an *T?M file. -ou need to specify an U3IIMDTX tag in
the .html file to load the 3IIMDT.
)))What are the differences between trusted and untrusted applets?
Page 63 of 136
$n general, applets loaded o"er the net are pre"ented from accessing files on the
client machine, and from ma'ing networ' connections ecept to the host
originating the applet.
$n addition, applets loaded o"er the networ' are pre"ented from starting other
programs on the client. 3pplets loaded o"er the networ' are also not allowed to
load libraries, or to define nati"e method calls, pro"iding accessing to the
underlying computer.
&n the other hand, trusted applets can be permitted to do all that. The trust
model in 2a"a allows you to enable only certain operations, so it is possible that
you enable networ' connections to5from anywhere but don,t permit access to the
local file system.
*ow to enable trusting an applet is different for each browser, $D, <etscape, and
standard 2a"a with the Ilug1in.
)0)Why doesn,t an applet "iewed through the browser respond to 'eyboard e"ents,
but the same wor's fine from within applet"iewer?
$n order to respond to 'eyboard e"ents your applet needs to ha"e the input
focus. $n the case of applet"iewer, there is nothing else on the page that might
ha"e focus. $n the case of a browser, there is. 2ust clic' into the applet,s area to
ha"e it get the input focus and then it will respond to 'eyboard e"ents.
)6)What is the 2a"a Ilug1$n?
The Ilug1in is a replacement 2a"a Cuntime Dn"ironment for your browser. $t allows
you to upgrade the browser,s supported 2a"a "ersion without waiting for the browser
"endor to release a new "ersion of the browser.
)=)*ow do $ automatically set the input focus in my applet to a specific component5tet field
when the browser loads the page that contains the applet?
The #a"a.awt./omponent class has a method named request!ocus(), you can use this to
request focus on any component.
)>)What is an applet stub?
3n applet stub is an interface that the applet container (browser) creator will
implement abstracting out capabilities li'e getting applet parameters, the applet,s
code5document base and other information necessary for the contained
applet(s). 3s an applet program, you,ll rarely use the interface. The only time you
really run across a need to do anything with the interface is if you try to run your
applet in your own container. -ou,ll then ha"e to implement the 3pplet+tub
interface yourself, along with the 3pplet/ontet interface.
Page 64 of 136
)@)*ow do $ stop an applet from running?
7rowsers will constantly call the applet life1cycle methods. There is no way to
stop them. The only way to stop an applet from running 5 displaying anything 5
ta'ing up /I4 time is to set a flag in the code and chec' it within each of the life1
cycle methods. /alling destroy() is not something you as a user 5 de"eloper
should do. /alling the method is the responsibility of the applet container (the
browser) when it wants to unload the applet.
)A)*ow can an applet get information about the 4CM it was called from?
The getGocument7ase() method of 3pplet returns the base 4CM of the *T?M file
that loaded an applet. $t is frequently used in con#unction with getting
supplemental files li'e images, as in $mage image =
get$mage(getGocument7ase(), %foo.gif%):
While in most cases it returns the full 4CM of the *T?M file that loaded the
applet, the 3I$ docs specify that it only needs to return the 4CM for the directory
of the file.
)B)What is an applet?
7asically, an applet is a 2a"a class, etending from #a"a.applet.3pplet that runs
in a Web browser, loaded from an 3IIMDT tag in an *T?M file. The browser
then calls applet life1cycle methods li'e start(), stop(), init(), and destroy() as
needed. There are security restrictions untrusted applets must abide by, li'e not
being able to connect to anywhere besides the web ser"er from which it came.
0E)What 3I$ changes are there for applets with 2GF 1.6?
The constructor for the 3pplet class now throws a *eadlessDception.
3lso, the 3pplet/ontet interface now has three new methods8 set+tream(),
get+tream(), and get+treamFeys().
01)3re there any restrictions placed on applets loaded from *T?M pages generated from
ser"lets 5 2+I pages?
$t is good practice to include the /&GD73+D attribute in the 3IIMDT tag and
specify a directory other then the ser"let directory for storing the applet1related
classes. !or eample8
out.println(U%3IIMDT /&GD=!oo.class /&GD73+D=5applets W$GT*=6EE
*D$.*T=6EE%X):
+ome Web ser"ers thin' that all classes loaded from the ser"lets directory are
automatically ser"lets, thus causing the applet not to load.
Page 65 of 136
0))*ow can $ easily pro"ide default "alues for when applet parameters are not specified?
*ere,s a helper method that you can use to do that8
import #a"a.applet.N:
public class 3pplet4tils 9
pri"ate 3pplet4tils() 9;
public static +tring getIarameter(
3pplet applet, +tring 'ey, +tring 'eyGefault) 9
+tring "alue = applet.getIarameter('ey):
return ("alue == null) ? 'eyGefault 8 "alue:
;
;
*ere,s how to call8
+tring "ar = 3pplet4tils.getIarameter(this, %name%, %2aeger%):
00)What is the default layout manager of an applet?
!or a #a"a.applet.3pplet, the default layout manager is !lowMayout.
!or the content pane of a #a"a.swing.23pplet, the default layout manager is a
7orderMayout.
06)?y applet runs fine with applet"iewer but not in the browser, what can be the problem?
3pplets loaded through applet"iewer are more then li'ely loading their classes
from the local /M3++I3T*, not o"er the networ'. 3s such, they get different
permissions and can do things that applets loaded o"er the networ' cannot. Try
using Tomcat and ser"ing the 3pplet through an *TTI connection, instead of
loading the .*T?M file from the file system.
3lso, 2a"a runtimes in browsers are based on 2a"a 1.1.. $f you need to use
newer capabilities, you,ll need to use the 2a"a Ilug1in. Without it, you,re stuc'
with the older 2a"a runtime capabilities.
0=)What does the class hierarchy of the 3pplet class loo' li'e?
The inheritence hierarchy of the #a"a.applet.3pplet class is as follows8
Page 66 of 136
P11111111111P
Z &b#ect Z
P11111111111P
Z
P11111111111P
Z /omponent Z
P11111111111P
Z
P11111111111P
Z /ontainer Z
P11111111111P
Z
P11111111111P
Z Ianel Z
P11111111111P
Z
P11111111111P
Z 3pplet Z
P11111111111P
0>)*ow can $ maintain a single instance of an ob#ect in an applet?
$n start(), instead of always creating a new ob#ect, return the eisting one if it
eists or create a new one if it doesn,t.
<etwor'ing
1)What is 4GI and how does it wor'?
4GI stands for 4ser Gatagram Irotocol. 4GI pro"ides an unreliable pac'et
deli"ery system built on top of the $I protocol. 3s with $I, each pac'et is an
indi"idual, and is handled separately. 7ecause of this, the amount of data that
can be sent in a 4GI pac'et is limited to the amount that can be contained in a
single $I pac'et. Thus, a 4GI pac'et can contain at most >==E@ bytes (this is
the >==0=1byte $I pac'et si(e minus the minimum $I header of )E bytes and
minus the A1byte 4GI header).
4GI pac'ets can arri"e out of order or not at all. <o pac'et has any 'nowledge
of the preceding or following pac'et. The recipient does not ac'nowledge
pac'ets, so the sender does not 'now that the transmission was successful. 4GI
has no pro"isions for flow control11pac'ets can be recei"ed faster than they can
be used. We call this type of communication connectionless because the pac'ets
ha"e no relationship to each other and because there is no state maintained.
The destination $I address and port number are encapsulated in each 4GI
pac'et. These two numbers together uniquely identify the recipient and are used
by the underlying operating system to deli"er the pac'et to a specific process
Page 67 of 136
(application). Dach 4GI pac'et also contains the sender,s $I address and port
number.
&ne way to thin' of 4GI is by analogy to communications "ia a letter. -ou write
the letter (this is the data you are sending): put the letter inside an en"elope (the
4GI pac'et): address the en"elope (using an $I address and a port number): put
your return address on the en"elope (your local $I address and port number):
and then you send the letter.
Mi'e a real letter, you ha"e no way of 'nowing whether a 4GI pac'et was
recei"ed. $f you send a second letter one day after the first, the second one may
be recei"ed be!ore the first. &r, the second one may ne"er be recei"ed.
)) What is a Gatagram?
Gatagram is another name for a 4GI pac'et.
2a"a pro"ides two classes for eplicitly dealing with datagrams,
:atagramSoc)et and :atagram3ac)et. These are both found in the
java.net pac'age.
0)Why use 4GI if it is unreliable?
Two reasons8 speed and o"erhead. 4GI pac'ets ha"e almost no o"erhead11you
simply send them then forget about them. 3nd they are fast, because there is no
ac'nowledgement required for each pac'et. Feep in mind that unreliable doesn,t
mean that pac'ets can be lost or misdirected for no reason 1 it simply means that
4GI pro"ides no built1in chec'ing and correction mechanism to gracefully deal
with losses caused by networ' congestion or failure.
4GI is appropriate for the many networ' ser"ices that do not require guaranteed
deli"ery. 3n eample of this is a networ' time ser"ice. /onsider a time daemon
that issues a 4GI pac'et e"ery second so computers on the M3< can
synchroni(e their cloc's. $f a pac'et is lost, it,s no big deal11the net one will be
by in another second and will contain all necessary information to accomplish the
tas'.
3nother common use of 4GI is in networ'ed, multi1user games, where a player,s
position is sent periodically. 3gain, if one position update is lost, the net one will
contain all the required information.
3 broad class of applications is built on top of 4GI using streaming protocols.
With streaming protocols, recei"ing data in real1time is far more important than
guaranteeing deli"ery. Damples of real1time streaming protocols are Ceal3udio
and CealLideo which respecti"ely deli"er real1time streaming audio and "ideo
o"er the $nternet. The reason a streaming protocol is desired in these cases is
because if an audio or "ideo pac'et is lost, it is much better for the client to see
this as noise or %drop1out% in the sound or picture rather than ha"ing a long pause
Page 68 of 136
while the client software stops the playbac', requests the missing data from the
ser"er. That would result in a "ery choppy, bursty playbac' which most people
find unacceptable, and which would place a hea"y demand on the ser"er.
6) What is ?ulticast and how does it wor'?
T/I and 4GI are both unicast protocols: there is one sender and one recei"er.
?ulticast pac'ets are a special type of 4GI pac'ets. 7ut while 4GI pac'ets
ha"e only one destination and only one recei"er, multicast pac'ets can ha"e an
arbitrary number of recei"ers.
?ulticast is quite distinct from broadcast: with broadcast pac'ets, every host on
the networ' recei"es the pac'et. With multicast, only those hosts that ha"e
registered an interest in recei"ing the pac'et get it.
This is similar to the way an 3WTD"ent and its listeners beha"e in the 3bstract
Window Tool'it. $n the same way that an 3WTD"ent is sent only to registered
listeners, a multicast pac'et is sent only to members of the multicast group. 3WT
e"ents, howe"er, are unicast, and must be sent indi"idually to each listener11if
there are two listeners, two e"ents are sent. With a ?ulticast+oc'et, only one is
sent and it is recei"ed by many.
3s you might guess, ?ulticast+oc'et is a subclass of Gatagram+oc'et which has
the etended ability to #oin and lea"e multicast groups. 3 multicast group consists
of both a multicast address and a port number. The only difference between 4GI
and multicast in this respect is that multicast groups are represented by special
internet addresses in the range ))6.E.E.1 to )0B.)==.)==.)==, inclusi"e. 2ust as
there are well1'nown ports for networ' ser"ices, there are reser"ed, well1'nown
multicast groups for multicast networ' ser"ices.
When an application subscribes to a multicast group (host5port), it recei"es
datagrams sent by other hosts to that group, as do all other members of the
group. ?ultiple applications may subscribe to a multicast group and port
concurrently, and they will all recei"e group datagrams.
When an application sends a message to a multicast group, all subscribing
recipients to that host and port recei"e the message (within the time1to1li"e range
of the pac'et, see below). The application needn,t be a member of the multicast
group to send messages to it.
=) What are C!/s and where can $ find them?
C!/ stands for %Cequest for /omment%. The C!/s form an integral part of the
$nternet standards: standards are formed by first publishing a specification as an
C!/.
$f you wish to implement a standard protocol in 2a"a, the first thing to do is
download and read the applicable C!/.
Page 69 of 136
>) *ow can $ send ob#ects across the networ' using soc'ets?
&b#ects that implement +eriali(able may be sent across a soc'et connection
using an &b#ect$nput+tream and &b#ect&utput+tream combination.
*ere are the steps to follow8
1. !irst, define an ob#ect to send. 3s an eample, we can define a class
called *essage to encapsulate our communications8
). public class ?essage implements +eriali(able 9
0. pri"ate int sender$G:
6. pri"ate +tring messageTet:
=.
>. public ?essage(int id, +tring tet) 9
@. sender$G = id:
A. messageTet = tet:
B. ;
1E. public +tring getTet() 9
11. return messageTet:
1). ;
10. ;
16. <et, instantiate the ob#ect, wrap the soc'et,s streams in ob#ect streams,
then send the message across the soc'et8
1=. ?essage sayhey = new ?essage(%1)06=>@AB%, %*ello%):
1>.
1@. +oc'et soc'et = new +oc'et(host, port):
1A. &b#ect&utput+tream out = new
&b#ect&utput+tream(soc'et.get&utput+tream()):
1B.
)E. out.write&b#ect(sayhey):
)1. &n the other side of the soc'et, the message can be retrie"ed and used
by in"o'ing methods on the returned ob#ect8
)). &b#ect$nput+tream in = new &b#ect$nput+tream(soc'et.get$nput+tream()):
)0. ?essage message&b#ect = (?essage) in.read&b#ect():
)6. +tring messageTet = message&b#ect.getTet():
@) *ow can $ obtain a hostname gi"en an $I address?
The code snippet8
+tring host = $net3ddress.get7y<ame(%)1>.)1@.B.1@)%).get*ost<ame():
should gi"e you the hostname www.#guru.com
A)*ow can $ obtain the $I address for a gi"en hostname?
The code snippet8
ip =$net3ddress.get7y<ame(%www.#guru.com%).get*ost3ddress():
Page 70 of 136
should gi"e you the $I address )1>.)1@.B.1@)
B)*ow can $ download files from a 4CM using *TTI?
&ne way to do this is by using a ;+0Connection to open a stream to your
desired 4CM, then copy the data out of the stream to a file on your local file
system. 3s an eample, here,s a little snippet of code which lets you download
the #.uru logo to your machine8
4CM url = new 4CM(%http855www.#guru.com5images5logo.gif%):
4CM/onnection connection = url.open/onnection():
$nput+tream stream = connection.get$nput+tream():
7uffered$nput+tream in = new 7uffered$nput+tream(stream):
!ile&utput+tream file = new !ile&utput+tream(%logo.gif%):
7uffered&utput+tream out = new 7uffered&utput+tream(file):
int i:
while ((i = in.read()) V= 11) 9
out.write(i):
;
out.flush():
<ote the use of %+tream% classes instead of %Ceader% classes. This is done because
in general a 4CM may contain binary data, as in this eample. 3lso note that both
the input and the output streams are buffered 1 this greatly speeds the download
time and is far more efficient that reading and writing a single byte at a time,
especially o"er the networ'.
11) What is T/I and how does it wor'?
$nternet Irotocol, or $I, pro"ides an unreliable pac'et deli"ery system11each
pac'et is an indi"idual, and is handled separately. Iac'ets can arri"e out of order
or not at all. The recipient does not ac'nowledge them, so the sender does not
'now that the transmission was successful. There are no pro"isions for flow
control11pac'ets can be recei"ed faster than they can be used. 3nd pac'et si(e is
limited.
Transmission /ontrol Irotocol (T/I) is a networ' protocol designed to address
these problems. T/I uses $I, but adds a layer of control on top. T/I pac'ets
are lost occasionally, #ust li'e $I pac'ets. The difference is that the T/I protocol
ta'es care of requesting retransmits to ensure that all pac'ets reach their
destination, and trac's pac'et sequence numbers to be sure that they are
deli"ered in the correct order. While $I pac'ets are independent, with T/I we
can use streams along with the standard 2a"a file $5& mechanism.
Thin' of T/I as establishing a connection between the two endpoints.
<egotiation is performed to establish a %soc'et%, and the soc'et remains open
throughout the duration of the communications. The recipient ac'nowledges
each pac'et, and pac'et retransmissions are performed by the protocol if
Page 71 of 136
pac'ets are missed or arri"e out of order. $n this way T/I can allow an
application to send as much data as it desires and not be sub#ect to the $I pac'et
si(e limit. T/I is responsible for brea'ing the data into pac'ets, buffering the
data, resending lost or out of order pac'ets, ac'nowledging receipt, and
controlling rate of data flow by telling the sender to speed up or slow down so
that the application ne"er recei"es more than it can handle.
There are four distinct elements that ma'e a T/I connection unique8
$I address of the ser"er
$I address of the client
Iort number of the ser"er
Iort number of the client
Dach requested client soc'et is assigned a unique port number while the ser"er
port number is always the same. $f any of these numbers is different, the soc'et
is different. 3 ser"er can thus listen to one and only one port, and tal' to multiple
clients at the same time.
+o a T/I connection is somewhat li'e a telephone connection: you need to
'now not only the phone number ($I address), but because the phone may be
shared by many people at that location, you also need the name or etension of
the user you want to tal' to at the other end (port number). The analogy can be
ta'en a little further. $f you don,t hear what the other person has said, a simple
request (%What?%) will prompt the other end to resend or repeat the phrase, and
the connection remains open until someone hangs up.
1)) What,s a ?alformed4CMDception?
When you try to create a new 4CM by calling its constructor, it will throw a
*alformed;+0E%ception if the 4CM string is not parseable or contains an
unsupported protocol.
10) *ow can $ get the real local host $I address in an applet?
3pplet security restrictions do not let you get this in an untrusted applet "ia
$net3ddress.getMocal*ost().
*owe"er, you can get this address by creating a +oc'et connection bac' to the
web ser"er from which you came and as'ing the +oc'et for the local address8
4CM url = getGocument7ase():
+tring host = url.get*ost():
+oc'et soc'et = new +oc'et(host, AE):
$net3ddress addr = soc'et.getMocal3ddress():
+tring host3ddr = addr.get*ost3ddress():
+ystem.out.println(%3ddr8 % P host3ddr):
Page 72 of 136
16) *ow do $ get the real local host $I address in an application (or trusted applet)?
The /net&ddress class pro"ides the necessary support8
$net3ddress local*ost = $net3ddress.getMocal*ost():
+ystem.out.println(local*ost.get*ost<ame()):
+ystem.out.println(local*ost.get*ost3ddress()):
1=) ?y machine has more than one $I address. *ow can $ specify which address to use for
a soc'et connection?
7oth Soc)et and ServerSoc)et ha"e a constructor which allows you to
specify a particular local $I address to use. $n the case of Soc)et, there are two
constructors8
public +oc'et($net3ddress address, int port, $net3ddress local3ddr, int
localIort)
public +oc'et(+tring host, int port, $net3ddress local3ddr, int localIort)
$n the case of ServerSoc)et, the constructor is8
public +er"er+oc'et(int port, int bac'log, $net3ddress local3ddr)
3ll three of these constructors may throw an /OE%ception.
1>) 3re there any performance ad"antages to be gained by using a Soc)et to connect to
an *TTI ser"er, instead of ;+0 or ;+0Connection?
4sing a +oc'et gi"es you more control o"er the connection 1 you can set soc'et
options, use your own streams, or e"en use your own soc'et implementation
factory. *owe"er, this comes at great epense: 4CM and 4CM/onnection do a lot
of things for you that you would need to implement from scratch. !or eample,
you would ha"e to completely implement the *TTI protocol, including support for
proies, maintain this code, and 'eep it up to date as *TTI e"ol"es. 4CM and
4CM/onnection let you etend functionality through content and protocol
handlers 1 you would need to implement this mechanism yourself or lose that
etensibility. $ don,t 'now why you would want to do this 1 the networ' o"erhead
for *TTI dwarfs any potential sa"ings in /I4 time you might get from dealing
with low1le"el soc'ets, and you lose generality, fleibility, and maintainability.
$f you,re con"inced you really want control at the soc'et le"el, $ would suggest
that you consider writing and using your own protocol handler instead of
rein"enting ;+0 and ;+0Connection.
Page 73 of 136
1@) Go $ ha"e to eplicitly close the soc'et input and output streams before $ close a
soc'et?
While closing the soc'et will close the underlying soc'et input and output
streams, programs typically wrap these streams in other streams. $t is important
to flush and close these other streams, preferably in a finally bloc', before
closing the soc'et. This will help to ensure that all application data is properly
sent or recei"ed and that your program isn,t unnecesarily holding on to file
descriptors that it no longer needs. 3n eample of this follows8
+oc'et soc'et:
7uffered&utput+tream out:
try 9
soc'et = new +oc'et(host, port):
out = new 7uffered&utput+tream(soc'et.get&utput+tream()):
55
55 write to the soc'et using the%out% stream
55
;
catch ($&Dception e) 9
55 handle errors
;
finally 9
try 9
out.flush():
out.close():
soc'et.close():
;
catch ($&Dception e) 9 5NignoreN5 ;
;
3lthough the structure of the finally bloc' is a little aw'ward in this case, it does
ensure that the streams and the soc'et are properly closed down, whether or not
an eception occurred.
1A) What protocols are supported by the ;+0 and ;+0Connection classes?
The protocols supported by 4CM and 4CM/onnection are L?1specific. +un,s
2GF supports a different set than the browser L?s or third1party 2GF L?s. The
protocols that seem to be common to all implementations are *TTI and !TI and
file. &ther protocols that might be supported include *TTI+, mailto, gopher, and
TDM<DT.
$n the table below, some of the more common L?s are listed showing the ma#or
protocols they support. There are other protocols not shown in this table that may
be supported.
Page 74 of 136
2GF 1.) <etscape 6.@ $D =.E
file -es -es -es
http -es -es -es
https -esN -es -es
ftp -es -es -es
telnet <o -es <o
mailto -es -es -es
gopher -es -es -es
N 2GF 1.) supports *TTI+ only when the 2++D etension is installed
$f a protocol is not supported in your L?, you can etend the functionality of the
;+0 class by writing and installing your own protocol handler.
1B) *ow can $ use the mailto< protocol from ;+0 or ;+0Connection?
7oth 4CM and 4CM/onnection act as mail user agents when using the mailto8
protocol. They need to connect to a mail transfer agent to effect deli"ery. 3n
?T3, for eample sendmail, handles deli"ery and forwarding of e1mail.
<ote that a mailto< 4CM doesn,t contain any information about where this ?T3
is located 1 you need to specify it eplicitly by setting a 2a"a system property on
the command line. !or eample, to run the program mailto.#a"a shown below,
you would use the command8
#a"a 1Gmail.host=mail.yourisp.net mailto
This tells the mailto< protocol handler to open a soc'et to port )= of
mail.yourisp.net and spea' +?TI to it. -ou should of course substitute the name
of your own +?TI ser"er in the abo"e command line.
import #a"a.io.N:
import #a"a.net.N:
public class mailto 9
public static "oid main(+tringJK args) 9
try 9
4CM url =
new 4CM(%mailto8foo[bar.com%):
4CM/onnection conn =
url.open/onnection():
Irint+tream out =
new Irint+tream(conn.get&utput+tream(), true):
Page 75 of 136
out.print(
%!rom8 #guru1fan[yourisp.com%P%WrWn%):
out.print(
%+ub#ect8 Wor's .reatV%P%WrWn%):
out.print(
%Than's for the eample 1 it wor's greatV%P%WrWn%):
out.close():
+ystem.out.println(%?essage +ent%):
; catch ($&Dception e) 9
+ystem.out.println(%+end !ailed%):
e.print+tac'Trace():
;
;
;
)E) What is the difference between a 4C$ and a 4CM?
4CMs are a subset of all 4C$s.
The term %4niform Cesource Mocator% (4CM) refers to the subset of 4C$ that
identify resources "ia a representation of their primary access mechanism (e.g.,
their networ' %location%), rather than identifying the resource by name or by some
other attribute(s) of that resource.
)1) *ow do $ create a simple Gatagram client?
1. !irst allocate space to hold the data we are sending and create an
instance of :atagram3ac)et to hold the data.
). byteJK buffer = new byteJ1E)6K:
0. int port = 1)06:
6. $net3ddress host = $net3ddress.get7y<ame(%#guru.com%):
=. GatagramIac'et pac'et = new GatagramIac'et(buffer, buffer.length,
>. host, port):
@. /reate a :atagramSoc)et and send the pac'et using this soc'et.
A. Gatagram+oc'et soc'et = new Gatagram+oc'et():
B. soc'et.send(pac'et):
The :atagramSoc)et constructor that ta'es no arguments will allocate a free
local port to use. -ou can find out what local port number has been allocated for
your soc'et, along with other information about your soc'et if needed.
55 !ind out where we are sending from
$net3ddress local*ostname = soc'et.getMocal3ddress():
int localIort = soc'et.getMocalIort():
The client then waits for a reply from the ser"er. ?any protocols require the
ser"er to reply to the host and port number that the client used, so the client can
now in"o'e soc)et.receive() to wait for information from the ser"er.
Page 76 of 136
))) *ow do $ create a simple Gatagram ser"er?
To create a ser"er with 4GI, do the following8
1. /reate a :atagramSoc)et attached to a port.
). int port = 1)06:
0. Gatagram+oc'et soc'et = new Gatagram+oc'et(port):
6. 3llocate space to hold the incoming pac'et, and create an instance of
:atagram3ac)et to hold the incoming data.
=. byteJK buffer = new byteJ1E)6K:
>. GatagramIac'et pac'et =
@. new GatagramIac'et(buffer, buffer.length):
A. 7loc' until a pac'et is recei"ed, then etract the information you need
from the pac'et.
B. 55 7loc' on recei"e()
1E. soc'et.recei"e(pac'et):
11.
1). 55 !ind out where pac'et came from
10. 55 so we can reply to the same host5port
16. $net3ddress remote*ost = pac'et.get3ddress():
1=. int remoteIort = pac'et.getIort():
1>.
1@. 55 Dtract the pac'et data
1A. byteJK data = pac'et.getGata():
The ser"er can now process the data it has recei"ed from the client, and issue an
appropriate reply in response to the client,s request.
)0) What is a port?
Iort numbers are the means by which an operating system routes incoming
pac'ets to the appropriate waiting process. &nly one process at a time can listen
for incoming pac'ets on a gi"en port. The combination of destination $I address
and port uniquely identifies the destination process for a pac'et. Mi'ewise, the
combination of source $I address and port uniquely identifies the source
process.
!or both T/I and 4GI, the port number field of a pac'et is specified as a 1>1bit
unsigned integer 1 this means that "alid port numbers range from 1 through
>==0=. (Iort number E is reser"ed and can,t be used).
2a"a does not ha"e any unsigned data types: 2a"a,s short data type is 1> bits,
but its range is 10)@>A to 0)@>@ because it is a signed type. Thus, short is not
large enough to hold a port number, so all classes which use or return a port
number must represent the port number as an int. $n the 2GF 1.1P, using an int
with a "alue greater than >==0= will generate an $llegal3rgumentDception. $n the
2GF 1.E.) and earlier, "alues greater than >==0= are truncated and only the low1
order 1> bits are used.
Page 77 of 136
Iort numbers 1 through )== are reser"ed for well1'nown ser"ices. 3 well1'nown
ser"ice is a ser"ice that is widely implemented which resides at a published,
%well1'nown%, port. $f you connect to port AE of a host, for instance, you may
epect to find an *TTI ser"er. &n 4<$Q machines, ports less than 1E)6 are
pri"ileged and can only be bound by the root user. This is so an arbitrary user on
a multi1user system can,t impersonate well1'nown ser"ices li'e TDM<DT (port
)0), creating a security problem. Windows has no such restrictions, but you
should program as if it did so that your applications will wor' cross1platform.
)6) *ow do $ control whether ;+0Connection uses the I&+T or .DT method when
sending data to an *TTI ser"er?
+ince these methods are part of the *TTI protocol, they can only be used when
the 4CM is an %http855% 4CM. $n that case, you can cast the connection returned
from ;+0.openConnection() to be a 5ttp;+0Connection, which has a
set+equest*et,od() method which lets you select whether .DT or I&+T is
used. !or eample8
if (connection instanceof *ttp4CM/onnection)
((*ttp4CM/onnection)connection).setCequest?ethod(%I&+T%):
.DT is used by default.
)=) What is a proy ser"er and how does it wor'?
3 proy is something or somebody representing some other party. $n the case of
an *TTI proy ser"er, it is a ser"er that relays browser requests to the
appropriate web site, recei"es the web ser"er response, and relays the response
bac' to the browser. 3n *TTI proy ser"er is typically used through a firewall to
a"oid clients connecting directly to the $nternet. The *TTI protocol eplains how
a client should get pages through a proy.
)>) What is a 4C$?
3 4C$ (4niform Cesource $dentifier) is a means of unambiguously locating a
resource on the $nternet.
There are two types of 4C$s8
4CM (4niform Cesource Mocator)
4C< (4niform Cesource <ame)
3 4CM is a pointer to a particular resource on the $nternet at a particular location, while a
4C< is a pointer to a particular resource but without reference to a particular location.
)@) $s there a way to programmatically find out if a port number is in use?
-ou can do the following8
Page 78 of 136
try 9
+er"er+oc'et s = new +er"er+oc'et(portno):
;
catch($&Dception e) 9
+ystem.out.println(%port % P portno P % already in use%):
;
)A) *ow can $ determine when multiple instances of my program are running on the same
machine?
The most portable, general way is for your program to attempt to create a ser"er
soc'et on a particular port. The first instance will be able to create the port and
so it will 'now that it,s the first. +ubsequent instances won,t be able to bind to that
ser"er soc'et and so they,ll 'now that they aren,t the first.
$f you need to trac' or otherwise manage all of the instances then you can
change things such that if they can,t bind to the ser"er soc'et that they then try to
connect to the first instance of the program using a client connect through the
soc'et and you can do whate"er you want from there.
&f course, if you,re worried about controlling the number of copies of your
program for %copy protection% purposes or you,re wanting to control multiple
instances of unsigned applets then you need to mediate the connections through
a trusted ser"er that you control.
)B) *ow would you send a file o"er a soc'et connection?
$f both ends of the connection 'new eactly what was happening or epected
(e.g. a single file with a constant filename, in the simplest case), you could do
something as simple as ha"e one end read from a !ile$nput+tream and write to
the soc'et,s &utput+tream, while the other end reads from the soc'et,s
$nput+tream and writes to a !ile&utput+tream.
$f you need to transfer multiple files, or need to transfer some details about the
file other than the contents (for eample, the file name and path), you could
create a class which represents the file and seriali(e it out to the soc'et. 3t the
simplest that might loo' li'e this8
import #a"a.io.N:
public class Transferable!ile implements +eriali(able
9
pri"ate byteJK contents:
pri"ate +tring file<ame:
public Transferable!ile(+tring Yfile<ame) 9
file<ame = Yfile<ame:
55 &pen a !ile$nput+tream and populate
Page 79 of 136
55 the contents array
;
public "oid write!ile() 9
55 &pen a !ile&utput+tream to write
55 the contents array
;
;
.. at one end you could create the Transferable!ile and seriali(e it out to the
soc'et. 3t the other end you deseriali(e and in"o'e write!ile().
3n impro"ement on that would be to do the file $5& in the read&b#ect() and
write&b#ect() methods. That is, read the file from the dis' in write&b#ect() and
stream the data straight out to the soc'et, then write the data directly to the dis'
in read&b#ect(). This would allow you to handle arbitrarily large files without
changing the memory requirement.
$f you need to do anything more comple than that, your best bet is to get an !TI
client5ser"er. 3 quic' search in this <etwor'ing !3R or in .oogle should list a
few options.
0E) What is %local loop bac'% used in networ'ing
1)@.E.E.1 is a special $I addressed reser"ed for the local host, or %loopbac'
address%. $t refers to the host on which your program is running. &perating
systems typically implement %networ'% communications with the local host by a
sort of software short1circuiting the ethernet hardware, effecti"ely looping bac'
the connection.
01) ?y computer is mapped to more than one $I adress. !rom my program, how can $
retrie"e all the $I addresses the machine is mapped to?
-ou can use something li'e8
$net3ddress ia=$net3ddress.getMocal*ost():
$net3ddressJK a=ia.get3ll7y<ame(ia.get*ost<ame()):
0)) What is a Feep13li"e? *ow is it implemented differently in *TTI 1.E and *TTI 1.1?
*ttp operates on what is called the request5response paradigm. The client
application generates a request for information which is passed to the ser"er,
which then replies to it. $n the earliest implementation of *TTI, each request
created a new soc'et connection to the ser"er, sent the command, then read the
response from the same connection. 3lthough this was simple to specify and
implement, it was also slow, especially in a high "olume situation.
Page 80 of 136
Feep1ali"es were added to *TTI to basically reduce the significant o"erhead of
rapidly creating and closing soc'et connections for each new request. The
following is a summary of how it wor's within *TTI 1.E and 1.18
*TTI 1.E
The *TTI 1.E specification does not really del"e into how Feep13li"e should
wor'. 7asically, browsers that support Feep13li"e appends an additional header
to the request as8
/onnection8 Feep13li"e
When the ser"er processes the request and generates a response, it also adds a
header to the response8
/onnection8 Feep13li"e
When this is done, the soc'et connection is not closed as before, but 'ept open
after sending the response. When the client sends another request, it reuses the
same connection. The connection will continue to be reused until either the client
or the ser"er decides that the con"ersation is o"er, and one of them drops the
connection.
*TTI 1.1
4nder *TTI 1.1, Feep13li"e is implemented differently. 3ll connections, by
default, are 'ept open, unless stated otherwise with the following header8
/onnection8 close
00) what is 4CM/onnection?
4CM/onnection is a general purpose class for accessing the attributes of a remote
resource. &nce you ma'e a connection to a remote ser"er, you can use 4CM/onnection to
inspect the properties of the remote ob#ect before actually transporting it locally.These
attributes are eposed by the http protocol specification and as such only ma'e sense for
4CM ob#ects that are using the http protocol.
Tomcat
1) *ow can $ debug my ser"let?
*oo boy, that,s a tough one.
!irst off, you should always do your own eception handling. 3n uncaught
eception can silently 'ill your ser"let, and if you don,t 'now where to loo' in the
log files, or if your ser"er has a bug in it whereby it silently swallows certain
eceptions, you,ll ha"e no idea where the trouble is.
Page 81 of 136
The following code sets up a catc, bloc' that will trap any eception, and print
its "alue to standard error output and to the ServletOutputStream so that the
eception shows up on the browser (rather than being swallowed by the log file).
/hances are that any error is in your code: the eception shows you what line
the problem happened at. ($f you see 7Compiled Code7 instead of line
numbers in the eception stac' trace, then turn off the 2$T in your ser"er.)
res.set/ontentType(%tet5html%):
+er"let&utput+tream out = res.get&utput+tream():
try 9
55 do your thing here
...
;
catch (Dception e) 9
+tringWriter sw = new +tringWriter():
IrintWriter pw = new IrintWriter(sw):
e.print+tac'Trace(pw):
out.println(%
%):
out.print(sw.to+tring()):
out.println(%
%):
;
Mately, $,"e started catching all Throwables, #ust in case. $ 'now this is bad form
but what are you gonna do?
<et, you should ma'e liberal use of the log() method, and you should 'eep your
own log files. 3gain, don,t trust the ser"er to do the right thing. 3lso, printing the
log after e"ery request can help debugging because you can immediately see the
output of your ser"let without going into the ser"er1side log files. (3nother
problem this a"oids is that some ser"let engines forget to flush their logs after
each request, so e"en if you go to the ser"er, you won,t see the most recent log
messages.)
*ere,s some source code you can add to any 5ttpServlet that 'eeps an in1
memory log8
+tring7uffer log7uffer = new +tring7uffer():
public "oid log(+tring s) 9
s = new Gate().to+tring() P %8 % P s:
+ystem.err.println(s):
log7uffer.append(s):
log7uffer.append(%Wn%):
super.log(s):
;
Page 82 of 136
3nd here,s some code that you can add to the end of your do.et or doIost
method that prints out the entire log after each request8
out.println(%U*CXWnU*0XDrror log this session8U5*0XWnUICDX%):
out.println(log7uffer.to+tring()):
out.println(%U5ICDXUIX%):
7oth of these should be disabled once you actually ship your ser"let, but they
can be "ery useful during de"elopment and debugging.
-ou should remember to use ser"letrunner (renamed %2+GF Web+er"er% with
the 2+GF "ersion ) 11 run with the script startser"er) to debug your ser"let. $t,s a
tool that ships with the 2+GF that basically starts up a miniature web ser"er that
runs your ser"let inside itself. $t means you don,t ha"e to stop and restart your
real web ser"er e"ery time you recompile your ser"let. $t also affords a more pure
en"ironment, so you can ma'e sure your ser"let truly conforms to the spec
before you try to run it inside a (possibly buggy or nonstandard) ser"let engine.
(<ote that Tomcat does not ha"e a replacement for ser"letrunner 81(.)
3 few $GDs support ser"let debugging. +ymantec /afe claims to ha"e a fairly
robust system for doing "isual source1le"el debugging of ser"lets (as well as
C?$, /&C73, and D27 ob#ects).
)) /an $ use Tomcat or 2a"aWeb+er"er as a ser"ice on Windows <T or Windows
)EEE?
!or Tomcat8
Gownload #'YntYser"ice.ee and follow the instructions in the document %<T1
+er"ice1howto.html% (on the 2a'arta Web site and included in the Tomcat
distros). 3lso see the minimalistic users guide, included with the Tomcat
distribution.
!or 2W+8
<ear the end of the installation program you will be as'ed if you want to ha"e the
2a"a Web +er"er start automatically on system reboot. (That is, whether you
want to install the 2a"a Web +er"er as an <T +er"ice).
$f you clic' -es8 3n entry will be added to the /ontrol Ianels 1X +er"ices and the
2a"aWeb+er"er <T +er"ice will be started up automatically e"ery time you
restart your system.
$f you clic' <o8 <o entry will be made in the /ontrol Ianel,s +er"ices panel.
$f you change your mind later, the product documentation pro"ides instructions
for how to setup the web ser"er to start automatically. !or instructions, see the
file8
Page 83 of 136
Jser"erYrootKWdocWenWadministrationWser"erYstartYWin.html
0) While $ am still ma'ing changes to a ser"let code, how can $ ma'e a ser"let
reload e"ery time $ test it?
$t depends on the web ser"er you are using to test your ser"let. !or instance,
with Tomcat, you would replace the W3C file and the ser"er notices the change
and loads the new ser"let on the net request, without ha"ing to restart the
ser"er.
J+hort answer8 for Tomcat, add reloadable=%true% to the U/ontetX tag for that
web application.
<ote that there is a bug in Tomcat where replacing the W3C file doesn,t wor':
you also ha"e to delete the unpac'ed directory under T&?/3T5webapps5foo (for
T&?/3T5webapps5foo.war).
$f you are not using W3C file deployment, simply replacing the ser"let classfile
should wor', as long as the class file is stored in webapp5WD71$<!5classes, or
replacing the 23C file in webapp5WD71$<!5lib5foo.#ar.
6) $s there any method to unload a ser"let from Web +er"er memory without
restarting the ser"er?
There is no standard method5mechanism to unload a ser"let from memory. +ome
ser"ers, li'e 2W+, pro"ide the means to load and unload ser"lets from their
administration module. &thers, li'e Tomcat, require you to #ust replace the W3C
file.
=) $,"e #ust set up Tomcat 0.1, created a contet, and when $ try and run a sample
2+I page, $ get8 Drror8 =EE, $nternal +er"let Drror8 #a"a.lang.<ullIointerDception
-ou probably forgot to create a classes folder located at8
UcontetX5WD71$<!5classes
/reate the folder, restart tomcat, all should be well.
>) *ow do $ ma'e Tomcat 0.1 in"o'e my ser"lets "ia the url UhostX5ser"lets5UclassX
instead of UhostX5ser"let5UclassX that it,s doing now?
/hange the url1pattern of the default ser"let in"o'er located in the %deployment
descriptor% for your web application. This file us usually located in
UcontetX5WD71$<!5web.ml file. Ceplace8
5ser"let5N
with8
Page 84 of 136
5ser"ets5N
3lso note that in Tomcat 0.1, web applications begin with the default %deployment
descriptor% located in Utomcat home dirX5conf5web.ml. -ou can change the
%default% for all web applications there.
@) Why doesn,t Tomcat shut down when $ run shutdown.bat (or shutdown.sh)?
&ne possibility is that if you disabled the 3p#1) connector in your ser"er.ml you
ha"e also disabled the mechanism by which Tomcat shutdown is eecuted 11 try
putting that bac' in if you,"e commented it out
A) Where do $ find web.ml and ser"er.ml configuration files?
<ote that Tomcat uses the default web.ml file, located in
T&?/3TY*&?D5conf5web.ml, as the base for all contets: indi"idual webapps
can o"erride specific settings in a custom WD71$<!5web.ml file.
!or ser"er.ml, loo' in the Tomcat distribution, in the directory you un(ipped,
under 8doc8uguide8tomcat-ug.,tml 11 scroll down to the %Tomcat,s
/onfiguration !iles% section.
B) *ow do $ set init parameters in the ser"let engine?
$t depends on the ser"let engine. Dach has its own type of config file in which you
can set the names and "alues of init parameters: these get passed to the ser"lets
(or 2+Is) "ia the get$nitIarameter() call.
!or Tomcat and 2+WGF, edit the conf5web.ml file.
1E)$s Tomcat robust enough for production use?
$?*& yes.
We are presently running Tomcat (ser"let H #sp requests) with 3pache (graphics,
perl, html) on B +olaris5+parc ser"ers ser"icing o"er 1E million ser"let5#sp
transactions per day.
11)$s there a problem with calling Cesponse.sendCedirect() after
Cesponse.add/oo'ie() ?
-es, there is a bug in Tomcat 0.1 (and possibly other ser"let engines). To send a
coo'ie through a redirect, you must set the headers manually.
/oo'ie longYterm = new /oo'ie(M&<.YTDC?Y/&&F$DY<3?D,
userYname):
longYterm.set?a3ge(>EN>EN)6N6):
longYterm.setIath(%57lah%):
Page 85 of 136
response.add/oo'ie(longYterm):

response.set+tatus(*ttp+er"letCesponse.+/Y?&LDGYTD?I&C3
C$M-):
response.set*eader(%Mocation%,CDG$CD/TYI3.D):
1))What "ersion of the +er"lets or 2+I specification is supported by my fa"orite
ser"let product? (2+GF, 2+WGF, Tomcat, 2)DD, etc.)
Iroduct Iroduct Lersion +er"let spec 2+I spec
Tomcat 0.1 ).) 1.1
Tomcat 0.E ).) 1.1
+un 2)DD Ceference $mplementation beta ).) ?
+un 2+WGF 1.E.1 ).1 1.E.1
+un 2+GF ).1 ).1 none
+un 2+GF ).E ).E none
3llaire 2Cun 0.E ).) 1.1
+un 2a"a Web +er"er ).E ).1 1
+un 2a"a Web +er"er 1.1 ).E 1
+un5<etscape iIlanet Web +er"er 6.1 ).) ?
10)Where should $ place my beans and ser"lets under Tomcat?
Where you place the beans and ser"lets depends on which %application% it
belongs to. 3ssuming that you are running your 2+I pages under the default
%eamples% application, you should place your ser"lets under the path
5tomcat5eamples5WD71$<!5classes
-our beans should be placed under
5tomcat5eamples5WD71$<!5#sp5beans
7oth these paths are placed within /M3++I3T* by Tomcat,s startup script file.
16)/an $ configure Tomcat so that the name of the webapp is not used in the 4CM?
D.g. http855localhost5ser"let5*elloWorld, instead of
http855localhost5eamples5ser"let5*elloWorld.
-ou can ... but $,m not sure $,d do this on a li"e systemV
The path you gi"e a contet must be unique within the ser"er.ml document.
Page 86 of 136
Therefore, all you need to do is change the path of the C&&T webapp (to %5root%
for eample) and change the path of your webapp to an empty string as below.
U/ontet path=%% doc7ase=%webapps5eamples% debug=%E% reloadable=%true% X
1=)/an $ use Tomcat under Windows BA? $s there anything $ ha"e to watch out for
during configuration?
Tomcat wor's "ery well with winB=5winBA. .enerally there is #ust one problem, in
that, calling startup.bat or tomcat.bat results in "ery strange outputs. This is
related to a space characters problem within the .bat file due to difference in file
formats under winB= and win<T.
!or all these problems, my standard solution was to copy the file with an editor
li'e ?+ Word and sa"e to another bat file. $f you starts changing bat file yourself,
its "ery confusing.
1>)/an $ use 7asic *TTI 3uthentication using 3pacheP2+er"?
$ recently did this with 3pache and Tomcat. 4sing 7asic *TTI 3uthentication is
an 3pache function, so this method should wor' with 3pache and any ser"let
engine. Gifferent web ser"ers will, of course, wor' differently.
$f you ha"en,t already done so, read the 3pache !3R about authentication
(section .) at apache.org, especially R3 ..). 3lso read the 3pache Wee' article
referenced there (http855www.apachewee'.com5issues5B>11E11A\userauth).
These resources will gi"e you a good idea about how 3pache can be configured
to restrict access to 4CM,s. <either one eplicitly tells you how to use
authentication with ser"lets, so $,ll spell it out here.
4se the UMocationX directi"e to indicate to 3pache that your specific ser"let 4CM
or ser"let 4CM prefi (for multiple ser"lets) can be accessed only by
authenticated users. The following template should be added to one of the
3pache configuration files (such as http.conf) with appropriate substitutions for
your system8
UMocation 5your5ser"let5url X
3uth<ame %your realm%
3uthType 7asic
3uth4ser!ile 5your5user5file
require "alid1user
U5MocationX
This UMocationX directi"e tells 3pache to restrict access to the specified 4CM, so
don,t use the filesystem path to your ser"let. 4se the ser"let,s 4CM.
-ou will also need to create a user file with htpasswd.
Page 87 of 136
1@)With regard to "ersion 0.1 of Tomcat, what specifically must be done to enable
automatic reloading of ser"lets?
3utomatic reloading of ser"lets by a ser"let container comes in handy during the
de"elopment phase when you are frequently modifying and recompiling the
ser"lets. *a"ing to constantly shutdown and restart the ser"let container each
time you modify a ser"let class can become tiring "ery quic'ly.
3utomatic reloading of ser"lets in Tomcat 0.1 is predicated upon two entries in
two different files in the directory T&?/3TY*&?D5conf8
1. $n the file (O*C&(-5O*E8conf8server.%ml, you must set the
reloadable attribute to true in the contet element pertaining to your
webapp. !or eample, $ ha"e a webapp named form9processing. +o $
added the following entry to the file (O*C&(-5O*E8conf8server.%ml8
>.
3. U/ontet path=%5form1processing% doc7ase=%webapps5form1processing%
?. debug=%E% reloadable=%true% X
5. U5/ontetX
>.
7. The file T&?/3TY*&?D5conf5tomcat.properties allows you to specify a
classpath that is passed on to the 2L?. The ser"lets that you want
automatically reloaded must not be in this classpath. <ote that this
classpath is in addition to the classpath specified in the startup file
tomcat.bat in the directory T&?/3TY*&?D5bin. !or the simple webapp
form1processing that $ mentioned abo"e, $ do not need to specify any
additional classpaths in the T&?/3TY*&?D5conf5tomcat.properties file.
!or those #ust getting into Tomcat 0.1, $ should add the ca"eat mentioned in the
Tomcat readme file that the automatic reload feature in Tomcat 0.1 is not
recommended for production applications. 3t this time, it is an eperimental
feature that when enabled creates etra o"erhead in processing ser"let requests.
1A)$ had Tomcat installed on c8WtcW#a'arta1tomcat, but need to run .#sp stored on
d8WabcWtest. *ow can $ accomplish this?
4nless you are using a %2)DD web application% there is no simple way to do this. $
would suggest creating a new web application and registering it with tomcat.
3 web application is essentially a standardised directory structure containing all of
the resources for your application. 4sing this standardised approach means that you
can migrate your application to another 2+I 1.15+er"let ).) compatible ser"er in the
future "ery easily.
The eamples directory under your tomcat webapps directory (c8WtcW#a'arta1
tomcatWwebapps) is a good eample of how to setup a webapp, and the important
points to note are the WD71$<! directory and its web.ml file.
Page 88 of 136
&nce you,"e setup your web application, you can register it with tomcat by opening
up the ser"er.ml file from the %conf% directory under your tomcat installation. 3gain,
ta'e a loo' at how the eample application is registered and use the same
mechanism for registering your new webapp. 3ll you need to do is specify the
%doc7ase% attribute as a fully qualified path.
1B)$f $ enable automatic ser"let reloading for a webapp, will the init() method of
the ser"let get eecuted for each automatic reload?
-es.
This question is important because it is possible to misconstrue the community
literature dealing with ser"lets and belie"e that the init() method of a ser"let will
get eecuted only once 11 the first time a ser"let gets loaded into the container.
The following simple ser"let, called (estServlet, can be used to "erify the
answer to the question. $n my Tomcat 0.1 container, this ser"let is inside a
webapp called test9suite and resides in the directory
T&?/3TY*&?D5webapps5test1suite5WD71$<!5classes
$n accordance with the #.uru !3R posting, $ ha"e enabled automatic reloading
for this webapp by including the following element in the server.%ml file in the
(O*C&(-5O*E8conf directory8
U/ontet path=%5test1suite% doc7ase=%webapps5test1suite% debug=%E%
reloadable=%true% X U5/ontetX
3s the following code shows, the ser"let contains a line %Ce"ision number8 %
where can be edited to create a change in the ser"let to trigger automatic
reload. 4pon each reload, the print statement in the init() method will be
printed out in the Tomcat console window. *ere is the code for this ser"let8
55filename8 Test+er"let.#a"a
import #a"a.io.N:
import #a"a.ser"let.N:
import #a"a.ser"let.http.N:
public class Test+er"let etends *ttp+er"let 9
public "oid init() throws +er"letDception
9
+ystem.out.println(%Test+er"let being loaded into the container%):
;
Page 89 of 136
public "oid do.et(*ttp+er"letCequest request, *ttp+er"letCesponse response)
throws +er"letDception, $&Dception
9
response.set/ontentType( %tet5html% ):
IrintWriter out = response.getWriter():
out.println( %UhtmlX% P
%UheadXUtitleX Test+er"let U5titleXU5headX% P
%*ello there from Test+er"let 11111 % P
%Ce"ision number8 1A% P
%U5bodyXU5htmlX% ):
;
;
)E)What is Tomcat?
Tomcat is the code name for the flagship product of the 2a'arta Iro#ect . $t is a
commercial1quality, open1source implementation of the 2a"a +er"let ).) and
2a"a+er"er Iages 1.1 +pecifications that runs either standalone or integrated with a
web ser"er. $t is also the official Ceference $mplementation for those specifications
(sanctified by +un).
)1)With regard to automatic ser"let reloading in Tomcat 0.1, what happens if one
ser"let ma'es references to other ser"lets in the same webapp? Will automatic
reloading get enabled for all such ser"lets?
The short answer to the question is8 <o.
Met,s say that a webapp for which automatic reload has been enabled consists of
a group of mutually referencing ser"lets. Met,s also say that you ha"e modified
and recompiled all the ser"lets. When you hit the reload button on the browser,
only one ser"let 11 the ser"let that the browser is pointing to 11 will be
automatically reloaded by the container. *itting the reload button on the browser
for the other ser"lets will not cause their reload into the container and you will
only see their older "ersions. $f you want the newer "ersions of the other ser"lets
to be reloaded into the container, in general you,d need to shutdown and restart
the ser"let container.
This beha"ior of Tomcat 0.1 is in 'eeping with the following statement that
appears in Tomcat 0.1 release notes8
2###### changes to classes other than the servlet you are re3uesting
do not trigger class reloads -- you %ill need to restart Tomcat to
re!lect changes in those classes#2
$n the rest of this posting, $ will eplain this property of Tomcat 0.1 with the help
an eample. The reader is also referred to a posting by /ostin ?anolache on this
aspect of automatic class reloading in Tomcat 0.1.
Page 90 of 136
To demonstrate this beha"ior of Tomcat 0.1, $ ha"e constructed the following
eample that consists of two simple mutually referencing ser"lets called
(estServlet-@ and (estServlet->. $n my Tomcat 0.1 container, both these
ser"lets are in a webapp called test9suite and reside in the directory
(O*C&(-5O*E8"ebapps8test9suite8.E'9/6F8classes. $n accordance
with the #.uru !3R posting, $ ha"e enabled automatic reloading for this webapp
by including the following element in the server.%ml file in the
(O*C&(-5O*E8conf directory8
U/ontet path=%5test1suite% doc7ase=%webapps5test1suite% debug=%E%
reloadable=%true% X U5/ontetX
Met,s say that after starting the ser"let container, you point your browser to the
following 4CM8
http855localhost8AEAE5test1suite5ser"let5Test+er"letY1
the ser"let container will load Test+er"letY1 into the container, which will cause
the browser to display a %*ello...% message. $f you clic' inside this message
where indicated, the browser will ma'e a request for Test+er"letY) and it will be
loaded into the container.
<ow suppose you ma'e changes to both the ser"lets by altering, say, the "alue
of %Ce"ision number8 %. $f your browser is pointing to Test+er"letY1 and you hit
reload button, the ser"let container will automatically reload Test+er"letY1. 7ut
the container will <&T reload Test+er"letY) e"en if you hit the reload button on
the browser when the browser is pointing to Test+er"letY).
To see the newer "ersion of Test+er"letY), you ha"e two choices8 1) Cecompile
the classes and this time start out by pointing your browser to Test+er"letY). &r,
)) +hutdown and restart the ser"let container.
*ere is the code for the two ser"lets8
5555555555 file8 Test+er"letY1.#a"a 5555555555
import #a"a.io.N:
import #a"a.ser"let.N:
import #a"a.ser"let.http.N:
public class Test+er"letY1 etends *ttp+er"let 9
public "oid init() throws +er"letDception
9
+ystem.out.println(%Test+er"letY1 being loaded into the container%):
;
Page 91 of 136
public "oid do.et(*ttp+er"letCequest request, *ttp+er"letCesponse response)
throws +er"letDception, $&Dception
9
response.set/ontentType( %tet5html% ):
IrintWriter out = response.getWriter():
out.println( %UhtmlX% P
%UheadXUtitleX Test+er"letY1 U5titleXU5headX% P
%*ello there from Test+er"letY1 1111111 % P
%To see the hello message from Test+er"letY),% P
% clic' Ua href=W%5test1suite5ser"let5Test+er"letY)W%XhereU5aX 111111 % P
%Ce"ision number8 1@% P
%U5bodyXU5htmlX% ):
;
;
5555555555 file8 Test+er"letY).#a"a 5555555555
import #a"a.io.N:
import #a"a.ser"let.N:
import #a"a.ser"let.http.N:
public class Test+er"letY) etends *ttp+er"let 9
public "oid init() throws +er"letDception
9
+ystem.out.println(%Test+er"letY) being loaded into the container%):
;
public "oid do.et(*ttp+er"letCequest request, *ttp+er"letCesponse response)
throws +er"letDception, $&Dception
9
response.set/ontentType( %tet5html% ):
IrintWriter out = response.getWriter():
out.println( %UhtmlX% P
%UheadXUtitleX Test+er"letY) U5titleXU5headX% P
%Test+er"letY) saying hello 1111111 % P
%To see the hello message from Test+er"letY1,% P
% clic' Ua href=W%5test1suite5ser"let5Test+er"letY1W%XhereU5aX 111111 % P
%Ce"ision number8 1@% P
%U5bodyXU5htmlX% ):
;
Page 92 of 136
;
)))$s there any way to tell Tomcat (or any ser"let engine) ne"er to use coo'ies for
session management?
$,m not sure about Tomcat but in WebMogic (from 6.E.) to =.1 "ersions) there is
parameter in the weblogic.properties file which can enable (or disable) coo'ies.
The parameter line is8
weblogic.httpd.session.coo'ies.enable=true
or
weblogic.httpd.session.coo'ies.enable=false
)0)$s it possible to use a TagMib without defining a web app using Tomcat? J$,m
using .#sp without webapps and e"erything,s o', but $ can,t ma'e it wor' with
taglibsK
When using taglibs with an application you specify the location of a tag library in
the web.ml file, web.ml resides in (O*C&(-+OO(8"ebapps8&336&*E8.E'9
/6F. The taglib entries in web.ml loo' li'e8
UtaglibX
Utaglib1uriX
blahblah
U5taglib1uriX
Utaglib1locationX
5WD71$<!5#sp57lah7lah.tld
U5taglib1locationX
U5taglibX
There is another web.ml which seems to be a global one8
(O*C&(-+OO(8conf8"eb.%ml +imply place the abo"e Q?M there, the last
entry in my conf5web.ml was a %welcome1file1list% entry, the taglib ml can be
placed after that. $ don,t 'now where the .tld file should be placed, maybe under
(O*C&(-+OO(8"ebapps8+OO(8.E'9/6F8jsp ?
)6)Goes Tomcat support D27?
<o, Tomcat does not support D27. $t is a +er"let52+I container, not an D27
container.
The 2a'arta Iro#ect pro"ides an implementation of the +er"lets 3I$ called
Tomcat, and an implementation of 2a"a+er"er Iages called 2asper. These are
bundled together in the Tomcat release.
Page 93 of 136
*owe"er, the 2)DD Ceference $mplementation, which supports D27, is bundled
with an old "ersion of Tomcat. This adds Tomcat,s support for +er"lets and 2+I
to the 2)DD product.
)=)*ow do $ deploy a W3C file in Tomcat?
/urrently (as of "ersion 0.)) the procedure for deploying a new W3C file is8
1. +top Tomcat.
). Gelete eisting deployment. $f you ha"e pre"iously deployed %foo.war% in
T&?/3TY*&?D5webapps, then it has been unpac'ed into
webapps5foo5... -ou must delete this directory and all its contents. &n
4ni, this can be done with
rm 1r ]T&?/3TY*&?D5webapps5foo
0. /opy W3C file to T&?/3TY*&?D5webapps5.
6. +tart Tomcat.
This process may become easier in the future. 3 %deploy tool% is on the Tomcat
%to1do% list.
<ote that if you deploy a W3C file in this manner, you do not need to ma'e any
changes to server.%ml 11 it will automatically be recogni(ed and acti"ated.
*owe"er, if you wish to specify non1default options for this webapp, you may do
so by adding an element li'e
U/ontet doc7ase=%webapps5foo% ...
to ser"er.ml.
)>)What is the difference between 2+er" and Tomcat? 3nd what,s up with
modY#ser" and modY#'?
2+er" was one of the "ery first ser"let engines. $t is now an open source pro#ect,
consisting of two parts8 a pure1#a"a ser"let engine, compliant with the +er"let
spec "ersion ).E, and an 3pache module written in / called modY#ser" that
allows 3pache to send ser"let requests to the 2+er" 2L?.
Tomcat is a completely separate product, originally written by +un, that is now
also open1source and administered by 3pache. $t supports the +er"let spec
"ersion ).), and the 2+I spec "ersion 1.1. $t also contains a pure 2a"a ser"let
engine, and a number of connectors for se"eral commercial web ser"ers.
*ere,s the confusing part8 originally, when it was time to write a connector from
3pache to Tomcat, they started with the code base of modY#ser". 3lthough it has
been rewritten and re"ised to the point where it is no longer compatible with the
modY#ser" that comes with 2+er", unfortunately, it is still called modY#ser". This
Page 94 of 136
means that if you ha"e the 2+er" modY#ser" installed, it will not wor' with
Tomcat, and "ice "ersa.
!ortunately, the latest "ersion of Tomcat comes with a new connector for
3pache, called modY#'. This connector supports Tomcat but not 2+er". $t is also
more ad"anced, in that it supports Tomcat1style load balancing, and also
supports ++M authentication (though this latter functionality is still a bit rough and
may ha"e bugs in actually NreportingN that the connection is secure).
+o if you #ust use modY#' and Tomcat, you should ha"e no problems (at least as
far as this connector issue is concerned).
)@)$ am runing Tomcat on 3pache for <T. When $ put a W after the the #sp page, e.g.
%http855www.myser"er.com5includes5topYna".#spW%, it shows the code, i.e. the #a"a
embedded in the *T?M. *ow do $ resol"e this issue?
This is a bug. 3!3$F it has been fied in the latest "ersion (0.)) of Tomcat.
)A)Why do $ get a %#a"a.net.7indDception83ddress in use% error?
Irobably because the address is in use 81)
-ou,re already running an instance of your ser"let engine, or another ser"ice is
running on its port. ?a'e sure the other ser"ice is fully stopped before launching
another one.
)B) What are the contents of WD71$<!?
The contents of the WD71$<! directory are8
5WD71$<!5web.ml deployment descriptor
5WD71$<!5classes5N directory for ser"let and utility classes. The classes in
this directory are used by the application class loader to load classes from.
5WD71$<!5lib5N.#ar area for 2a"a 3Cchi"e files which contain ser"lets,
beans, and other utility classes useful to the web application. 3ll such
archi"e files are used by the web application class loader to load classes
from.
Uh0X+ample Web 3pplication Girectory +tructureU5h0X
$llustrated here is a listing of all the files in a sample web application8
5inde.html
5howto.#sp
5feedbac'.#sp
5images5banner.gif
5images5#umping.gif
5WD71$<!5web.ml
Page 95 of 136
5WD71$<!5lib5#spbean.#ar
5WD71$<!5classes5com5mycorp5ser"lets5?y+er"let.class
5WD71$<!5classes5com5mycorp5util5?y4tils.class
0E) What is a W3C file and how do $ create one?
3 W3C (or %web archi"e%) file is simply a pac'aged webapp directory. $t is
created using the standard 2a"a jar tool. !or eample8
cd 5home5ale5webapps5mywebapp
#ar cf ..5mywebapp.war N
01) *ow are initiali(ation parameters passed to a ser"let under +er"let 3I$ "ersion ).)?
Through the webapp deployment descriptor, which is the web.ml file in the
directory WD71$<!.
<ote that there are two different types of web.ml files in Tomcat 0.8 There is a
web.ml that sits in the top1le"el configuration directory T&?/3TY*&?D5conf
and then there can be a separate web.ml for each webapp in the directory
WD71$<! for that webapp. -ou would want to 'eep webapp specific deployment
information, such as initiali(ation parameters and their "alues, in the web.ml
specific to that webapp.
The best on1line eample that illustrates ser"let initiali(ation through a webapp,s
deployment descriptor is, $ belie"e, the Servlet3aram ser"let in the test
webapp in your Tomcat software pac'age. This ser"let can be called with two
different canonical names, as for eample in
http855localhost8AEAE5test5ser"let5ser"letIaram1
and
http855localhost8AEAE5test5ser"let5ser"letIaram)
The deployment descriptor maps the canonical names servlet3aram@ and
servlet3aram> to the actual ser"let Servlet3aram but with different "alues
of the initiali(ation parameters. When the ser"let Servlet3aram is called with
the name servlet3aram@, the initiali(ation parameter1"alue pairs are
param1 "alue1
param) "alue)
and when the same ser"let is called with the name servlet3aram>, the
parameter1"alue pairs are
param0 "alue0
param6 "alue6
Page 96 of 136
The following constitutes a sufficient deployment descriptor for this eample8
UV11 filename8 web.ml in the directory T&?/3TY*&?D5webapps5Uyour1
webappX5WD71$<!5 11X
U?ml "ersion=%1.E%?X
UVG&/T-ID web1app +-+TD? %http855#a"a.sun.com5#)ee5dtds5web1
appY).).dtd%X
Uweb1appX
User"letX
User"let1nameX
ser"letIaram1
U5ser"let1nameX
User"let1classX
+er"letIaram
U5ser"let1classX
Uinit1paramX
Uparam1nameXparam1U5param1nameX
Uparam1"alueX"alue1U5param1"alueX
U5init1paramX
Uinit1paramX
Uparam1nameXparam)U5param1nameX
Upram1"alueX"alue)U5pram1"alueX
U5init1pramX
U5ser"letX
User"letX
User"let1nameX
ser"letIaram)
U5ser"let1nameX
User"let1classX
+er"letIaram
U5ser"let1classX
Uinit1pramX
Upram1nameXparam0U5pram1nameX
Upram1"alueX"alue0U5pram1"alueX
U5init1pramX
Uinit1pramX
Upram1nameXparam6U5pram1nameX
Upram1"alueX"alue=EEEU5pram1"alueX
U5init1pramX
U5ser"letX
U5web1appX
Page 97 of 136
The first half of the "eb.%ml file associates the ser"let Servlet3aram with the
name servlet3aram@ and then goes on to declare its parameter1"alue pairs.
The second half does the same for the name servlet3aram>.
0)) $s it possible to bind Tomcat to one specific $I address on a multi1homed host (for
"irtual hosting)?
-es, from "ersion 0.1 you can a "irtual host bind to one of the ip adresses owned
by the machine, if you add something li'e the following to ser"er.ml8
U*ost name=%1)@.E.E.1% X
U/ontet path=%%
doc7ase=%webapps5eamples% 5X
U/ontet path=%5eamples%
doc7ase=%webapps5C&&T% 5X
U5*ostX
as you can see you can put a $I adress for the Lirtual *ost name, ergo you can ha"e a
Lirtual *ost pointed to any particular $I configured in your machine.
00) /an $ use the latest "ersion of Tomcat inside +un,s 2)DD implementation?
The 2)DD reference implementation ships with Tomcat. The classes for Tomcat
are located inside the WlibW#)ee.#ar. $f you wanted to use the latest "ersion of
Tomcat you would ha"e to replace the classes in this archi"e.
This would of course not be supported.
06) What are the ad"antages5disad"antages of using Tomcat,s built1in *TTI ser"er
instead of, say, 3pache?
Cegarding Tomcat,s disad"antages when used as a stand1alone ser"er, here is a
list reproduced from the Tomcat13pache *&WT& page8
1. Tomcat is not as fast as 3pache when it comes to static pages.
). Tomcat is not as configurable as 3pache.
0. Tomcat is not as robust as 3pache.
6. There are many sites with long time in"estment in certain web ser"ers, for
eample, sites that are using /.$ scripts5+er"er 3I$ modules5perl5php.
We cannot assume that all of them will want to ditch this legacy.
The page further says that % !or all these reasons it is recommended that real
world sites use an industrial strength web ser"er, such as 3pache, for ser"ing the
static content of the site, and use Tomcat as a +er"let52+I add1on.%
The main thing that Tomcat has going for it is that it the official reference
implementation of the 2a"a +er"let ).) and 2a"a+er"er Iages 1.1 technologies
Page 98 of 136
de"eloped under the 3pache license by some of the best de"elopers around the
world.
0=) What is an in"o'er ser"let in a Tomcat ser"let container?
The %in"o'er ser"let% is a system1supplied ser"let that etracts the name of the
requested ser"let class from the portion of the 4CM that comes after %5ser"let%.
The in"o'er ser"let then loads the requested ser"let into the container and
eecutes it.
$f you loo' at the contents of the webapp deployment descriptor file, "eb.%ml, in
the (O*C&(-5O*E8conf directory, you will find the following servlet element
at the beginning8
User"letX
User"let1nameX
in"o'er
U5ser"let1nameX
User"let1classX
org.apache.tomcat.ser"lets.$n"o'er+er"let
U5ser"let1classX
U5ser"letX
which declares the name and the place of the system1supplied in"o'er ser"let.
+hortly thereafter appears the following servlet9mapping element8
User"let1mappingX
User"let1nameX
in"o'er
U5ser"let1nameX
Uurl1patternX
5ser"let5N
U5url1patternX
U5ser"let1mappingX
which tells the container that all requests that begin with %5ser"let% (relati"e to root of the
webapp specified by the name that comes before %5ser"let%) are to be sent to the
invo)er ser"let.
0@)When $ recompile a ser"let which is already loaded by the container, it is
automatically reloaded. *owe"er the destroy() method of the ser"let does not get
called. Goes this mean that the ser"let is not unloaded before reloading?
Page 99 of 136
The obser"ation you ma'e does not apply to the "ersion of Tomcat 0.1 that is
currently a"ailable for download from the 2a'arta1Tomcat site. *owe"er, it does
apply to Tomcat 0.) beta 6. ?ore on 0.) later in this posting. !irst, $,d li'e to say a
few words about what $ am basing my 0.1 answer on.
The test ser"let for which $ show code below has both an init() method and a
destroy() method. When the init() method is in"o'ed, it prints out the
following message in the Tomcat window8
Test+er"let being loaded into the container
and when the destroy() method is in"o'ed, it prints out the following message
in the Tomcat window8
Test+er"let about to be unloaded
<ote that the init() method will only be in"o'ed when the ser"let class is loaded
into the container and its instance created. The destroy() method will only be
in"o'ed #ust prior to the container unloading the ser"let.
$f $ carry out the following steps in the sequence indicated8
1. request the ser"let through a client browser
). recompile the ser"let
0. hit the reload button on the browser
$ get the following sequence of messages in the Tomcat window8
Test+er"let being loaded into the container
Test+er"let about to be unloaded
CDM&3GVVV

Test+er"let being loaded into the container
This shows the ser"let is actually unloaded and its destroy() method in"o'ed
before the new "ersion of the ser"let is automatically loaded in.
*ere is the code for the ser"let8
import #a"a.io.N:
Page 100 of 136
import #a"a.ser"let.N:
import #a"a.ser"let.http.N:
public class Test+er"let etends *ttp+er"let 9
public "oid init() throws +er"letDception
9
+ystem.out.println(%Test+er"let being loaded into the container%):
;
public "oid do.et(*ttp+er"letCequest request, *ttp+er"letCesponse response)
throws +er"letDception, $&Dception
9
response.set/ontentType( %tet5html% ):
IrintWriter out = response.getWriter():
out.println( %UhtmlX% P
%UheadXUtitleX Test+er"let U5titleXU5headX% P
%*ello there from Test+er"let% P
%U5bodyXU5htmlX% ):
out.close():
;
public "oid destroy()
9
+ystem.out.println( %Test+er"let about to be unloaded% ):
;
;
Therefore, with regard to automatic loading and unloading, Tomcat 0.1 wor's as
specified in the +er"let ).1 3I$. *owe"er, the beta 6 "ersion of Tomcat 0.)
seems to ha"e a bug in it. When you do eactly the same thing as described
abo"e in Tomcat 0.), the destroy() method is not in"o'ed, meaning that the
old copy of the ser"let does not get unloaded.
0A)$,"e setup Tomcat 0.1 with 3pache on my web ser"er to ser"e 2+I pages. $t
wor's well for 2a"a +er"lets and 2+I pages. *owe"er, this is one issue8 if the
target 2+I page does not eist, the ser"er will send out a !ile <ot !ound Drror
6E6 along with the GDT3$M I3T*, such as %!ile 5usr5local5#a'arta1
tomcat5webapps5... <ot found%. *ow can $ stop tomcat from spilling off its own
detail file path on the ser"er.
$f you loo' the code of the Tomcat,s 2+I+er"let.#a"a, you will find the following
code in the ser"ice method8
Page 101 of 136
try9
55loo' for the #sp file
; catch (!ile<ot!oundDception e) 9
response.sendDrror(*ttp+er"letCesponse.+/Y<&TY!&4<G,
/onstants.get+tring(%#sp.error.file.not.found%, new &b#ectJK 9 e.get?essage() ;)):
3s you can see that the !ile<ot!oundDception directly wor's with the response
ob#ect and the message is ta'en from the messages.properties files to send it
directly to the caller (browser). 3lso $ did not find any other mechanism in the
Tomcat,s configuration to suppress the error messages. +o it will not be possible
to suppress this message.
0B) *ow is +ingleThread?odel implemented in Tomcat? $n other containers? J$
would assume that Tomcat uses its connection thread pool, and creates a new
instance of the ser"let for each connection thread, instead of sharing one instance
among all threads. $s that true?K
The question mies together two rather independent aspects of a ser"let
container8 %concurrency control% and %thread pooling%.
/oncurrency control, such as achie"ed by ha"ing a ser"let implement the
+ingleThread?odel interface, addresses the issue of thread safety. 3 ser"let will
be thread1safe or thread1unsafe regardless of whether the ser"let container used
a thread pool. Thread pooling merely eliminates the o"erhead associated with
the creation and destruction of threads as a ser"let container tries to respond to
multiple requests recei"ed simultaneously. $t is for this reason that the
specification document for +er"let ).) 3I$ is silent on the sub#ect of thread
pooling 11 as it is merely an implementation detail. *owe"er, the document does
indeed address the issue of thread safety and how and when to use
+ingleThread?odel ser"lets.
+ection 0.0.0.1 of the +er"let ).) 3I$ +pecification document says that if a
ser"let implements the +ingleThread?odel it is guaranteed %that only one
request thread at time will be allowed in the ser"ice method.% $t says further that
%a ser"let container may satisfy this guarantee by seriali(ing requests on a
ser"let or by maintaining a pool of ser"let instances.%
&b"iously, for superior performance you,d want the ser"let container to create
multiple instances of a Single(,read*odel type ser"let should there be many
requests recei"ed in quic' succession. Whether or not a ser"let container does
that depends completely on the implementation. ?y eperiments show that
Tomcat 0.1 does indeed create multiple instances of a Single(,read*odel
ser"let, but only for the first batch of requests recei"ed concurrently. !or
subsequent batches of concurrent requests, it seems to use only one of those
instances.
6E) Which ser"let containers ha"e persistent session support? +pecifically, does Tomcat
0.1?
Page 102 of 136
3ll ser"let containers that implement the +er"let ).) 3I$ must pro"ide for session trac'ing
through either the use of coo'ies or through 4CM rewriting. 3ll Tomcat ser"let containers
support session trac'ing.
61) *ow do $ write to a log file using 2+I under Tomcat? /an $ ma'e use of the log()
method for this?

-es, you can use the +er"let 3I$,s log method in Tomcat from within 2+Is or
ser"lets. These messages are stored in the ser"er,s log directory in a file called
servlet.log.
6)) When 4sing Tomcat 0.1 with 3pache, how do you set up your contet and web ser"er
inde so that a .#sp file is set as the inde file?
$n 3pache, first map the desired #sp filename to the directory inde. !or eample8
$n srm.conf Jor httpd.confK8
Girectory$nde inde.#sp
Then in your webapp,s web.ml or in your ser"er,s web.ml, loo' at the bottom
for the Uwelcome1file1listX tag. -ou can add Uwelcome1fileX tags to this tag, such
as8
Uwelcome1file1listX
Uwelcome1fileX
desired1inde.#sp
U5welcome1fileX
U5welcome1file1listX
60) /an $ include two #sp8plugin actions on one 2+I page? $t does not compile under Tomcat
-es. 2ust include an etra set of 9;,s around the plugin code8
UT 9 TX
U#sp8plugin
type=%applet%
code=%/loc').class%
codebase=%5eamples5#sp5plugin5applet%
#re"ersion=%1.)%
width=%1>E%
height=%1=E% X
U#sp8fallbac'X
Ilugin tag not supported.
U5#sp8fallbac'X
U5#sp8pluginX
UT ; TX
Page 103 of 136
UT 9 TX
U#sp8plugin
type=%applet%
code=%/loc').class%
codebase=%5eamples5#sp5plugin5applet%
#re"ersion=%1.)%
width=%1>E%
height=%1=E% X
U#sp8fallbac'X
Ilugin tag not supported.
U5#sp8fallbac'X
U5#sp8pluginX
UT ; TX
66) *ow do you enable 73+$/ authentication using Tomcat?
JRuestion continues8 $,m able to get the dialog bo requesting the username and
password to pop up, howe"er, e"en though $ insert one of the usernames and
passwords from the tomcat1users.ml file, $ always get an %3uthori(ation failed.
Cetry?% dialog.K
?a'e sure that the user has been designated a role in the tomcat1users.ml that
matches the role(s) defined in the auth1constraint section of the web.ml8
%eb#*ml4
Uauth1constraintX
Urole1nameXrole1U5role1nameX
U5auth1constraintX
tomcat-users#*ml4
Utomcat1usersX
Uuser name=%test% password=%tomcat% roles=%role1% 5X
U5tomcat1usersX
6=) *ow do $ set up "irtual hosting on Tomcat in standalone mode?
$n Tomcat 0.)b>, it is "ery easy to setup "irtual hosts in standalone mode. !irst,
be sure to set the correct port for the *TTI listener (the default is AEAE, and
you,ll probably want to change it to AE). +econd, wrap your ser"let contet
definitions (in your ser"er.ml) with a UhostX tag, specifying the domain name to
wor' on. *ere is an eerpt from a ser"er.ml that is configured for "irtual hosting8
U*ost name=%ser"er1.domain.com%X
U/ontet path=%% doc7ase=%5"ar5www5ser"er1% reloadable=%true% debug=%E% 5X
U5*ostX
U*ost name=%ser"er).domain.com%X
U/ontet path=%% doc7ase=%5"ar5www5ser"er1% reloadable=%true% debug=%E% 5X
U5*ostX
Page 104 of 136
6>) *ow do $ set up "irtual hosting on Tomcat with 3pache?
-ou can configure your 3pache ser"er,s "irtual hosts to map to "irtual hosts in a
single Tomcat instance. Dach "irtual host would eist as a separate ser"let
contet.
J!or modY#' instructions, see the user,s guide. !or modY#ser"...K
!irst configure 3pache with modY#ser", mapping the appropriate hostnames to
Tomcat. *ere is a sample from httpd.conf8
3p2+er"?anual on
3p2+er"+ecretFey G$+37MDG
3p2+er"?ount/opy on
3p2+er"MogMe"el notice
3p2+er"GefaultIrotocol a#p"1)
3p2+er"GefaultIort AEE@
3p2+er"Gefault*ost localhost
3ddType tet5#sp .#sp
3dd*andler #ser"1ser"let .#sp
<ameLirtual*ost 1B).1>A.E.)
ULirtual*ost 1B).1>A.E.)X
GocumentCoot 5"ar5www5ser"er1
+er"er<ame ser"er1.lo'itech.com
3p2+er"?ount 5ser"let 5C&&T
UGirectory 5"ar5www5ser"er15WD71$<!X
&rder allow,deny
Geny from all
U5GirectoryX
U5Lirtual*ostX
ULirtual*ost 1B).1>A.E.)X
GocumentCoot 5"ar5www5ser"er)
+er"er<ame ser"er).lo'itech.com
3p2+er"?ount 5ser"let 5C&&T
UGirectory 5"ar5www5ser"er)5WD71$<!X
&rder allow,deny
Geny from all
U5GirectoryX
U5Lirtual*ostX
+econd, configure Tomcat for "irtual hosts. $n your ser"er.ml, you will wrap each
ser"let contet in a UhostX. *ere is a sample from ser"er.ml8
Page 105 of 136
U*ost name=%ser"er1.domain.com%X
U/ontet path=%% doc7ase=%5"ar5www5ser"er1% reloadable=%true% debug=%E% 5X
U5*ostX
U*ost name=%ser"er).domain.com%X
U/ontet path=%% doc7ase=%5"ar5www5ser"er1% reloadable=%true% debug=%E% 5X
U5*ostX
6@) *ow do you do ser"let aliasing with 3pache and Tomcat?
+er"let aliasing is a two part process with 3pache and Tomcat. !irst, you must
map the request in 3pache to Tomcat with the 3p2+er"?ount directi"e, e.g.,
3p2+er"?ount 5myser"let 5C&&T
+econd, you must map that url pattern to a ser"let name and then to a ser"let
class in your web.ml configuration file. *ere is a sample eerpt8
User"letX
User"let1nameXmyser"letU5ser"let1nameX
User"let1classXcom.mypac'age.?y+er"letU5ser"let1classX
U5ser"letX
User"let1mappingX
User"let1nameXmyser"letU5ser"let1nameX
Uurl1patternX5myser"letU5url1patternX
U5ser"let1mappingX
6A) /an Tomcat be configured to interpret all, or selected, .html files within a gi"en contet as
2+I? &r, do 2+I files ha"e to end with a .#sp etension?
yes you can do that by modifying the web.ml file. -ou will ha"e to in"o'e the
org.apache.#asper.runtime.2sp+er"let for all the requests ha"ing etension .html.
-ou can do that by changing the +er"let mapping code8
User"let1mappingX
User"let1nameX
#sp
U5ser"let1nameX
UurlXN.htmlU5urlX
U5ser"let1mappingX
3nd comment out the following bloc'
Umime1mappingX
UetensionX
html
U5etensionX
Umime1typeX
tet5html
Page 106 of 136
U5mime1typeX
U5mime1mappingX
6B) $s there any way $ can assign different "alues of /M3++I3T* to different contets?
&ne way to get the functional equi"alent is to put the files in question in either
%Uapp1pathX5WD71$<!5classes% or %Uapp1pathX5WD71$<!5lib%, depending on
whether you are tal'ing about a .class or .#ar. The /M3++I3T* for a gi"en
webapp will include WD71$<!5classes and all the .#ar files found in WD71$<!5lib.
+ay you had utils.#ar and form1taglib.#ar in WD71$<!5lib, the resulting classpath
would loo' li'e8
]/M3++I3T*8Uapp1pathX5WD71$<!5classes8Uapp1pathX5WD71
$<!5lib5utils.#ar8Uapp1pathX5WD71$<!5lib5form1taglib.#ar
=E) *ow do $ change the port from AEAE to AE?
&pen ser"er.ml in TT&?/3TY*&?DTWconf directory and edit the
U/onnectorX element.
!or +impleTcp/onnector, change the sub1element %port% "alue to AE. -es, -ou
got itV
=1) *ow to deploy a ser"let that includes #a"a.mail.N on Tomcat?
2ust place the mail.#ar and acti"ation.#ar files (and possibly the pop.#ar file if you are using
I&I0) in the /M3++I3T* of the web ser"er. The simplest way to do this is to rely on the 2a"a
etensions framewor'. 3dd them to the 23L3Y*&?D5#re5lib5et directory. 2ust copy the files
there. &therwise, set the /M3++I3T* en"ironment "ariable before starting Tomcat. The
startup scripts retain the eisting /M3++I3T*, adding the Tomcat1specific stuff to the end.
=)) What is the difference between apache webser"er, #a"a webser"er and tomcat ser"er?
3pache is an *TTI ser"er written in / that can be compiled and run on many
platforms. +ee http855www.apache.org5
2a"a Web+er"er is an *TTI ser"er from +un written in 2a"a that also supports
+er"lets and 2+I.
Tomcat is an open1source *TTI ser"er from the 3pache !oundation, written in
2a"a, that supports +er"lets and 2+I. $t can also be used as a %plug1in% to nati"e1
code *TTI ser"ers, such as 3pache Web +er"er and $$+, to pro"ide support for
+er"lets (while still ser"ing normal *TTI requests from the primary, nati"e1code
web ser"er).
=0) What is /atalina?
Page 107 of 136
/atalina is the name gi"en to the Tomcat 6.E ser"let engine component, in the
same way that the 2+I compiler5runtime component is called 2asper.
=6) Where do $ install the 2G7/ dri"er O$I files, 23C files H GMMs? *ow do $ ensure they,re in
Tomcat,s /M3++I3T*?
+ince "ersion 0.), all the 23C+ present in the TT&?/3TY*&?DT5lib directory
are automatically appended to Tomcat,s classpath, but only the #ars are
appended. To ha"e a O$I automatically appended rename it to N.#ar ( as a #ar is
only a renamed (ip ) and "oila....
JThere are two other options8
1. Iut the #ar file in your webapp,s WD71$<!5lib5 directory. This set of 23Cs is
added to the classpath for your webapp only. 7e careful, howe"er8 if a
different dri"er for the same 2G7/ 4CM is already on the system
classpath, then it may (mayV) be loaded instead of yours. (Whether it is or
not depends on whether that dri"er has already been loaded yet.)
). /hange the Tomcat /M3++I3T* en"ironment "ariable, or %1classpath%
command1line option, to contain your 23C or O$I. This is set in the Tomcat
startup script, tomcat.bat5tomcat.sh. Cead that file for details on how to
edit it.
==) Where do +ystem.out and +ystem.err go in Tomcat?
7y default, they will go to the console where the tomcat is started. -ou ha"e to modify the
startup scripts to redirect them to appropriate files.
&n the other hand, if you are running Tomcat as an <T +er"ice, you can modify the
conf5wrapper.properties file and set wrapper.stdout and wrapper.stderr properties to
point to your log files.
=>) $,"e written a ser"let that was using 2+er" and now $ upgrade to use Tomcat. What would $
need to change?
The only thing you should ha"e to change code1wise is whate"er has been
changed in the +er"let 3I$ between the 3I$ used in 2+er" and the api used it
Tomcat... #ust a couple that come to mind are
encode4CM() is now encode4rl() and encodeCedirect4CM is now
encodeCedirect4rl(). -ou can get the entire list by loo'ing at the specs for the
ser"let 3I$s on the #a"a site. There is usually a section in the specs that is
%What,s <ew in the 3I$%.
=@) /an $ do ser"let chaining in Tomcat? $f so, how?
<ot yet.
Page 108 of 136
The net "ersion ().0) of the +er"let +pec will allow something li'e ser"let
chaining. $t,s called %filters.%
=A) /an $ use a .eneric +3Q5G&? Q?M parser for Tomcat instead of parser.#ar? $ tried using
Qerces and get class not found errors for sun. parser during Tomcat initiali(ation.
Try to configure Qerces as customi(ed +3Q5G&? implementation by system
properties. 7y default #ap uses
com.sun.ml.parser.Gocument7uilder!actory$mpl and
com.sun.ml.parser.+3QIarser!actory$mpl (this is why you get
/lass<ot!oundDception if you miss parser.#ar from the classpath).
Dample8
+ystem.setIroperty(%#a"a.ml.parsers.Gocument7uilder!actory%,
%org.apache.erces.#ap.Gocument7uilder!actory$mpl%):
+ystem.setIroperty(%#a"a.ml.parsers.+3QIarser!actory%,
%org.apache.erces.#ap.+3QIarser!actory$mpl%):
=B) 4nder what circumstances will a ser"let be reloaded?
That depends on the +er"let container.
?ost of the +er"let containers reload the ser"let only it detects the code change
in the +er"let, not in the referenced classes.
$n Tomcat,s ser"er.ml deployment descriptor, if you ha"e mentioned
U/ontet path=%5my3pp%
doc7ase=%G85my3pp5webGe"%
cross/ontet=%true%
debug=%E%
reloadable=%true%
trusted=%false% X
U5/ontetX
The reloadable = true ma'es the magic. D"ery time the +er"let container detects
that the +er"let code is changed, it will call the destroy on the currently loaded
+er"let and reload the new code.
7ut if the class that is referenced by the +er"let changes, then the +er"let will not
get loaded. -ou will ha"e to change the timestamp of the ser"let or stop1start the
ser"er to ha"e the new class in the container memory.
>E) Why do $ get the compiler error %pac'age #a"a.ser"let does not eist% or %pac'age
#a"a.ser"let not found in import%?
Page 109 of 136
Try this8 3ssume that you ha"e tomcat location li'e8
c8Wtomcat
at the command promt type8
set classpath=c8WtomcatWlibWser"let.#ar
>1) *ow can you set the session timeout in tomcat higher?
Goes anybody 'now how you can set the session time in tomcat higher? <ow it is 0E minutes,
but $ want to set it higher.
-ou can specify the timeout of a session in the deployment descriptor of your
web application (web.ml)8
Uweb1appX
Usession1configX
Usession1timeoutX>EU5session1timeoutX
U5session1configX
...
U5web1appX
The number within the session1timout element must be epressed in minutes
>)) $s 2a"a+cript supported as a 2+I scripting language under Tomcat?
$n short, no.
Iutting things "ery "ery simply, Tomcat is essentially a 2a"a +er"let /ompiler,
ta'ing the .#sp file you write and translating it to a #a"a ser"let that runs in the
bac'ground.
2a"a, according to the 3pache de"elopment group that wrote Tomcat ('nown as
the 2a'arta group) conforms solely to the 2+I 1.) 5 +er"let 1.1 specification by
+un ?icrosystems. When they wrote Tomcat, they only had in mind to use 2a"a
as the %scripting language%. $n fact, Tomcat is built with #a"a, thereby hea"ily
integrating the technology.
$ hope you 'now this, but 2a"a+cript and 2a"a are two entirely different
languages (some things are similar, but most are not). The two technologies are
by no means interchangeable, and this intuiti"ely applies to Tomcat. To the best
of my 'nowledge the 3pache Tomcat de"elopmental teams ha"e no current
Page 110 of 136
plans to integrate other scripting technologies into the software (for many
reasons, of which $ won,t go into here for bre"ity).
*owe"er, you may include 2a"a+cript within the .#sp file (not within #sp
interpretable UT TX tags), and it will be output to the client browser for
interpretation #ust li'e in an *T?M page. The 'ey here is to reali(e that it has no
interaction5functionlity with the ser"er before it is sent to the client.
>0) Goes T&?/3T pro"ide 2G7/ /onnection Iooling ?
<o.
Tomcat (tal'ing about "ersion 0..) is the reference implementation of the
webapp part of 2)DD (ie, no D27). $n this spec connection pooling is not
contemplated.
>6) *ow do $ include a file in a 2+I page?
-es, there are two different ways to do that8
The first one is done using the ,include, directi"e8
UT[ include file=%relati"e4CM% TX
$n this case the gi"en page will be statically included inside the the #sp page.
The second include is done using the #sp tag ,include,8
U#sp8include page=%9relati"e4CM Z UT= epression TX;% flush=%true% 5X
With this synta, the page will be included statically or dinamically, depending on
the page itself.
$f the page to be included is dynamic, parameters can be passed to it using this
synta8
U#sp8include page=%9relati"e4CM Z UT= epression TX;% flush=%true% X
U#sp8param name=%parameter<ame%
"alue=%9parameterLalue Z UT= epression TX;% 5X
U5#sp8includeX
<ote8 with 2sp 1.1 the %flush% parameter can only be true.
>=) Where to sa"e the $mages, *T?M, and other static data in Tomcat?
$mages and *T?M shall be put inside the contet of your application8
Page 111 of 136
somewhere inside 5#a'arta1tomcat10.).15webapps5yourYcontet5
somewhere inside the "ar file of your application
war file must be put inside 5#a'arta1tomcat10.).15webapps5
3n eample of tree of a web application (in a ."ar archi"e) can be8
war1file
Z
Z1111?DT31$<!
Z Z111?3<$!D+T.?!
Z
Z111WD71$<!
Z Z111web.ml
Z Z111#sp
Z Z Z111taglib (.tld)
Z Z111classes
Z Z111(.class5.properties)
Z111#sp
Z Z111(.#sp5.html5.shtml)
Z
Z111images
Z Z111(.gif5.png5.#peg)
Z
Z111binaries
Z111(.(ip5.tar5...)
chec' eamples in ja)arta9tomcat93.>.@8"ebapps8
>>) *ow do $ find out Tomcat,s home directory from inside a running ser"let?
When Tomcat is eecuted (and you can chec' both tomcat.sh and tomcat.bat in the tomcat,s
bin directory) the property ,tomcat.home, is set using 1G. This means that you should be able to
access it using +ystem.getIroperty(%tomcat.home%).
>@) *ow to read a file from the W3C or webapp? $f $ ha"e a configuration file, say an Q?M file,
stored inside the W3C, how do $ open it from a ser"let? $.e.,
$nput+tream in = new !ile$nput+tream(????):
The W3C file is automatically opened by the ser"let container during the
startup... at least this is what the ser"let specs are saying (and it is happening
with both Cesin and Tomcat). &nce you reach the ser"let #ust use
+er"let/ontet.getCealIath() to get the file.
!or eample if the file is in a ,template, dir under the root of the contet, use
Page 112 of 136
getCealIath(%5template5file.ml%):
>A) *ow and where do $ change the option for 2L? heap memory in Tomcat?
$f you loo' into the tomcat.sh or tomcat.bat under the bin directory of tomcat, you
can see an en"ironment "ariable called T&?/3TY&IT+.
-ou can use it for passing all the 2L? specific parameters, li'e the 1Q or 1G.
-ou can set it directly in the file, or set it in the en"ironment before calling it. !or
eample in uni you can do8
e*port T5M)"T657T'12 -8ms.9M -8m*.9M2
tomcat#sh start
>B) Where are the ser"let source files for 2+Is compiled in Tomcat?
J2+I is first translated into ser"let than compiled. +o where are those ser"let
.#a"a or .class files for 2+I eamples in Tomcat?K
They are located in the wor' directory of the T&?/3TY*&?D, under a directory
that is normally called localhostYUportXT)EUcontetYnameX.
The source for 2+Is from the eamples webapp should be something li'e
localhostYAEAET)Eeamples.
@E) What is the difference between startup.bat, shutdown.bat, and tomcat.bat?
tomcat.bat ta'es a parameter, %start% or %stop%.
Cunning %startup% is the same as running %tomcat start%. Cunning %shutdown% is
the same as running %tomcat stop%.
@1) *ow do $ assign the user,s role without using a login form?
7asically the concept is that you can use the standard http authentication schemes (i.e.8 basic,
digest). This means that you can authenticate a user among a database (or, for eample,
another source) without de"eloping html login forms.
@) ) What,s the difference between IoolTcp/onnector and +impleTcp/onnector ?
The main difference is that the Iool connector will create a pool of simple
connectors, allowing the ser"er to answer to more requests at the same time,
while a simple connector can anwer only a response at a time.
Page 113 of 136
The simple connector hasn,t been designed to be used unless you 'now that you
will process only a request at a time.
@0) Go $ really need to build a complete ,webapp, #ust to add a simple ,*elloworld, ser"let to the
ser"er?
<ot at all. -ou can put a single ser"let anywhere on your hard dis' but you will
ha"e to configure your path in ser"er.ml and ser"let alias in web.ml as usual.
Met me be a bit more descripti"e.
$f $ ha"e my *elloWorld ser"let under c85foo5hello directory, i will set my path in
ser"er.ml li'e
U/ontet path=%5hello% doc7ase=%c85foo5hello%XU5contetX
3nd then in web.ml 8
User"let1nameXhelloU5ser"letnameX
User"let1classX*elloWorldU5ser"let1classX
that tomcat considers while starting and you can start your ser"let.
@6) Why does Tomcat,s first ser"let request ta'e so long?
+ounds li'e it is the +ecureCandom class initiali(ing. Ilease disable this (set the
"alue in ser"er.ml to %#a"a.util.Candom%) and see if it helps.
*owe"er, be warned that this method lea"es your sessions open to attac'. $t
would ta'e a dedicated hac'er, but if you,re storing any sensiti"e data, this is a
big no1no. +o put it bac' to +ecureCandom when you,re done testing this.
@=) *ow do $ disable port AEAE? $ want Tomcat to run only through my Web ser"er, not directly
through Tomcat.
.o to the T&?/3TY*&?D directory and edit ser"er.ml, find 8
class<ame=%org.apache.tomcat.ser"ice.IoolTcp/onnector%
and wrap it in a comment so it,s not interpreted. That,s it V
@>) *ow do $ pre"ent users from "iewing the contents of my WD71$<! directory?
+er"let Dngines (e.g. Cesin or Tomcat) should not allow directory browsing of
WD71$<!. Tomcat 0.), for eample, had that same issue and they ha"e fied it in
Tomcat 0.).1. This was happening when Tomcat was used standalone (not #ust
as a container, but e"en as a web ser"er).
Page 114 of 136
$f this problem happens with a specific "ersion of a standalone Cesin, you should
consider to try the latest "ersion ($,m running 1.).=) and, e"entually, send a bug
to /aucho.
/onsider that this issue should happen when using the container in standalone
mode. When the container (Cesin, Tomcat or abother one) is used #ust for
ser"ing ser"let H #sp behind a more reliable and complete web ser"er, li'e
3pache, the problem is on 3pache, that is ser"ing e"erything else. When you as'
for WD71$<!, in fact, 3pache doesn,t e"en connect to Tomcat, there is no
reason.
+o, if this is your scenario, you should add lines li'e these8
UGirectory 5WD71$<!X
3llow&"erride <one
Geny !rom 3ll
U5GirectoryX
$nside the "irtual host or whate"er you thin' is appropriate and, ob"iously,
changing %5WD71$<!% with the appropriate contet.
@@) What is the password for the Tomcat admin webapp?
-ou ha"e to modify tomcat1users.ml in your ]T&?/3TY*&?D5conf directory to
add an administrati"e role as in following eample8
Utomcat1usersX
Uuser name=%scott% password=%tiger% roles=%admin% 5X
Uuser name=%role1% password=%tomcat% roles=%role1% 5X
Uuser name=%both% password=%tomcat% roles=%tomcat,role1% 5X
U5tomcat1usersX
Then you can login with scott5tiger.
@A) Go $ need to create my own web.ml file?
<o, you don,t. 7ut it,s normally better to.
<ormally the ser"let container 'nows how to eecute ser"lets and what to call for
eecuting #sps, so you can sur"i"e without defining your own web.ml file.
There are many ad"antages of the web application descriptor, though. !or
eample if you ha"e a ser"let that it,s part of a pac'age, you would be able to
assign it a name and a mapping, so instead of calling it, for eample, with
Page 115 of 136
5ser"let5com.foo.ser"lets.?y+er"let, you can ma'e it 5?y+er"let. &r, you can use
a ser"let name that it,s common and when you change the class that you are
using, you don,t ha"e to change the code or the pages that are using it.
Ilus there are other interesting features, li'e parameter passing, securities and
so on.
7ut, again, to answer to your question8 yes, you don,t need to create a web.ml
file.
@B) /an the web application reside on a machine other than where Tomcat is running?
$f by %web application% you mean the set of #sps, ser"lets, classes, and all the
other required files, $,m afraid not. JTomcat must be able to read the files from a
locally mounted file system.K
What you can do, though, is to ha"e Tomcat running on one machine and the
web ser"er running on another, but $ don,t thin' that you can ha"e the files of the
application be read through the net without some sort of file ser"er mounting
solution li'e ntfs, samba or similar.
AE) /an anyone tell me the ad"antages and disad"antages between Tomcat, 2Cun, and 2+er"
for 3pache Web +er"er?
Iroduct Iros /ons
Tomcat !ree as in both beer and
speech
3cti"e open1source
de"elopment effort
Lery current in terms of
ser"let 3I$ compliance
<ot the fastest implementation on
the planet
-ou,re on your own for support
2Cun !ree as in beer for
de"elopers
Celati"ely speedy
+upported by 3llaire
(?acromedia)
/osts money for production use
Lersions that $,"e used (pre10.E) had
lots of configuration headaches
+lightly behind the times with
updates (compared to open source
pro#ects)
3pache
2+er"
!ree as in both beer and speech <o longer in acti"e de"elopment
(Tomcat inherited this effort)
*as some thread1lea'ing issues, in
my eperience
&nly supports ser"let 3I$ ).E (not
later)
Page 116 of 136
-ou,re on your own for support
A1) Goes Tomcat support 2?+ (2a"a ?essaging +er"ice)?
Tomcat is #ust a ser"let container, not an D27 container nor an application ser"er, so it does
not contains any 2?+ basic support.
A)) *ow do $ load an applet from a ser"let or 2+I? Where do $ place my applet class files?
3n applet is eecuted on the client side (browser), not on the ser"er side (ser"let
container). -ou need to place the applet class files in a location accessible from
the browser, which means you ha"e to treat them li'e normal files (li'e *T?M or
.$! files that you want the browser to load). Thus they need to go in the webapp
directory tree, but not in the WD71$<! subdirectory.
$t is best to thin' of the set of applet class files as entirely different from the set of
ser"let class files. They will be loaded by different Lirtual ?achines, and may
e"en ha"e different "ersions of classes. $t is a simple matter to configure your
build en"ironment (3nt or ma'e) to create copies of common class files in the two
different classpath directories.
+ince the concept of %current directory% is 'ind of fu((y in the +er"let 3I$, it is
usually easiest to ma'e a separate directory #ust for your applet class files, and
use the optional /&GD73+D parameter to the 3IIMDT tag. *ere is an
architecture that wor's well8
myapp5WD71$<!5classes5?y+er"let.class
myapp5WD71$<!5classes54til.class
myapp5inde.html
myapp5applets5?y3pplet.class
myapp5applets54til.class
Then if your ser"let generates a line li'e8
out.println(%Hamp:lt:3IIMDT /&GD=,?y3pplet.class, W$GT*==E *D$.*T==E
/&GD73+D=,5applets,Hamp:gt:%Hamp:gt::
The browser will be able to load ?y3pplet.class and 4til.class from your 5applets
web directory. $t will not be able to load anything from WD71$<!5classes, since
those files are accessible only by the ser"let engine.
<ote that loading an applet from a page generated by a ser"let is much the same
as loading an image. $t is also easier to use a common %images% directory in that
case, so that images can be loaded from any page regardless of %current%
directory.
A0) $s it possible in Tomcat to allow running all ser"lets from a directory without configuring
each one in web.ml ?
Page 117 of 136
maybe you can #ust use the same logic that is used by the ser"let, calling an
in"o'er for the gi"en directory. $ ne"er tested it, but it sound right8
User"letX
User"let1nameX
in"o'er
U5ser"let1nameX
User"let1classX
org.apache.tomcat.ser"lets.$n"o'er+er"let
U5ser"let1classX
U5ser"letX
User"let1mappingX
User"let1nameX
in"o'er
U5ser"let1nameX
Uurl1patternX
5myGirectory5N
U5url1patternX
U5ser"let1mappingX
A6) 4sing #sp8forward on Tomcat, why do $ get the error +ava&lang&IllegalArgu$entExceptin
at +avax&servlet&http&2ttp/tils&parseNa$e32ttp/tils&+ava:4567 ?
Tomcat misinterprets #sp8param tag of #sp8forward if the name is represented as
"ariable, i.e.
U#sp8param name=%frame% "alue=%bottom%5X
wor's well but
U#sp8param name=%UT= "ar TX% "alue=%bottom%5X
doesnt. The later is what we had in our code hence the eception.
A=) *ow do $ restrict access from ser"lets to certain directories?
$t,s not that difficult. -ou can simply use the 2a"a +ecurity, pro"ided you ha"e
2a"a ).
!or eample 8
grant 9
permission #a"a.io.!ileIermission %1%, %read,write%:
;
Page 118 of 136
This only allows to read and write in the current directory and its sub1directories.
Write this in your tomcat.policy file and then start tomcat li'e this 8
5path5to5#a"a5bin5#a"a 1G#a"a.security.manager
1G#a"a.security.policy=5path5to5tomcat5conf5tomcat.policy
1Gtomcat.home=5path5to5tomcat org.apache.tomcat.startup.Tomcat %][% H
Gon,t forget the necessary permissions for tomcat to wor' properly.
A>) *ow do $ determine a class,s file location at runtime?
This method returns a 4CM to the class file in question. !rom that you can
manipulate it to get what you want.
public #a"a.net.4CM locate/lass(/lass p/lass)9
55 get the name of the class (e.g. my.pac'age.?y/lass)
+tring class<ame = p/lass.get<ame():

55 create the resource path for this class
+tring resourceIath = %5% P class<ame.replace(,.,,,5,) P %.class%:

55 get the resource as a url (e.g. file85/85temp5my5pac'age5?y/lass.class
#a"a.net.4CM class4CM = p/lass.getCesource(resourceIath):
return class4CM:
;
A@) Goes Tomcat 6 ha"e a .4$?
3ccessing http855localhost8AEAE5manager directly will not do anything. -ou gan
gi"e command to it li'e8
http855localhost8AEAE5manager5list
-ou will get a page ("ery simple) that show all the acti"e web applications.
AA) *ow do $ set session timeouts of greater than 0E minutes?
Tomcat session 'eeps epiring in spite of entries in web.ml to the effect of
Usession1configX
Usession1timeoutX>EU5session1timeoutX UV11 0E minutes 11X
U5session1configX
AB) Why can,t Tomcat find my &racle 2G7/ dri"ers in classes111.(ip?
Page 119 of 136
T&?/3T 6.E.1 on <T6 throws the foll eception when i try to connect to &racle
G7 from 2+I.
#a"a.ser"let.+er"letDception 8 oracle.#dbc.dri"er.&racleGri"er
Coot /ause 8 #a"a.lang./lass<ot!oundDception8 oracle8#dbc8dri"er8&racleGri"er
7ut, the &racle 2G7/ dri"er O$I file (classes111.(ip)is a"bl in the system
classpath.
?y problem was sol"ed. $ copied the &racle Gri"er class file (classes111.(ip) in
TT&?/3TY*&?DTWlib directory and renamed it to classess111.#ar. $t wor'ed.
<ow i am able to connect to &racle G7 from T&?/3T 6.E1 "ia &racle 2G7/1
Thin Gri"er.
BE) /an $ use N.ear files in Tomcat?
<o, Tomcat is a Web container, not an D27 container.
B1) /an $ place my classes somewhere other than inside WD71$<!?
+un,s specifications for +er"let define only the WD71$<!5classes and WD71
$<!5lib directories in order to ma'e the web application portable.
$f you are not interested in portability, you can still put all your classes into the
/M3++I3T* en"ironment "ariable.
The startup script for Tomcat 0.). should automatically add that classpath to the
one used by Tomcat, while, with "ersion 6.E. and 0.0., you definitely need to
ma'e a small change in the startup script to add the /M3++I3T* en"ironment
to the one that is generated by the script to esecute Tomcat.
The only issue is that the classes5#ars you,"e added will be a"ailable to all the
web applications running under that instance.
B)) $ am attempting to configure Tomcat,s WebGa" application (http855localhost8AEAE5webda")
to allow e"eryone to "iew the directory. *owe"er $ need authori(ed users to be able to edit the
content of the directory.
*ere some additional info regarding the problem.
!irst $ set the property in the webapps5webda"5web.ml file to allow read and
write access. 7y default this gi"es e"eryone access to change content.
Uinit1pramX
Upram1nameXreadonlyU5pram1nameX
Upram1"alueXfalseU5pram1"alueX
Page 120 of 136
U5init1pramX
$ tested this and it wor'ed as epected11e"eryone was able to ma'e changes to
the content. <et $ attempted to change the security settings for the directory so
only certian users could ma'e changes.
Usecurity1constraintX
Uweb1resource1collectionX
Uweb1resource1nameXThe Dntire Web 3pplicationU5web1resource1nameX
Uurl1patternX5NU5url1patternX
U5web1resource1collectionX
Uauth1constraintX
Urole1nameXtomcatU5role1nameX
U5auth1constraintX
U5security1constraintX
Ulogin1configX
Uauth1methodX73+$/U5auth1methodX
Urealm1nameXTomcat +upported CealmU5realm1nameX
U5login1configX
Usecurity1roleX
UdescriptionX
3n eample role defined in %conf5tomcat1users.ml%
U5descriptionX
Urole1nameXtomcatU5role1nameX
U5security1roleX
This modified things so you need to login as a user defined as ha"ing a role of
%tomcat% in conf5tomcat1users.ml in order to edit or vie% anything in the webda"
directory.
$ need it to allow anyone to access the file o"er the web, but only prompt for a
password if they try to modify the file.
Trying to remo"e the Usecurity1roleX section doesn,t wor'.
7asically whithin the Uweb1resource1colletionX section of the web.ml file you
can define waht methods are protected. +o you could protect the I4T command
while lea"ing the .DT command open to e"eryone.
$ added the following and the beha"ior is what $ was trying for8
Uweb1resource1collectionX
....
Uhttp1methodXGDMDTDU5http1methodX
Uhttp1methodXI&+TU5http1methodX
Page 121 of 136
Uhttp1methodXI4TU5http1methodX
Uhttp1methodXM&/FU5http1methodX
U5web1resource1collectionX
This prompts for authentication when a user tries to loc' a file for editing as well
as I&+Ting and I4Tting. $,m not sure if this will ha"e any effect on forms ability
to function and send stuff to a #sp page. (!or eample8 will the user be as'ed for
a password if they fill out and submit a form.) This isn,t really a problem because
all my webda" content will be in a separate folder at this point.
*opefully that is useful to some other people as well.
B0) Where should $ copy the class file of applet in Tomcat? Where should $ copy respecti"e
*T?M file?
*T?M (and .2+I) files are placed under the webapps5C&&T directory under the
installation directory (or other than C&&T if you,"e defined a different contet).
3pplet .class files would then be placed relati"e to the location of the *T?M file.
-ou can also specify a specific codebase by pro"iding that paramter to the *T?M
file.
B6) What,s the initial user name and password for 2a'arta Tomcat 6,s admin tool?
3s far as $ 'now, there is no user that is assigned the ,admin, role after an
installation of tomcat. (!or security reasons $ assume).
-ou can assign this role to a username5password combination of your choice in
the 5conf5tomcat1users.ml file.
B=) $ put my 23C file inside WD71$<!5lib, but my classes are not getting found. *owe"er, when
i un(ipped classes into WD71$<!5classes5, it wor's. What,s up?
+ome old "ersions of Tomcat do not include WD71$<!5lib5N.#ar in Web3pp classpath. -ou may
handle it updating to a newer "ersion of tomcat or (as you did) unpac'ing #ars into WD71
$<!5classes5.
B>) Why request.getCemote4ser() returns <4MM ?
3s specified by the documentation, this method returns the login o! the user
maing this re3uest$ i! the user has been authenticated$ or null i! the user has
not been authenticated.
The aut,entication, in this case, is the ,ttp aut,entication.
3pplication +er"er
Page 122 of 136
1) *ow can $ get access to the properties of my running WebMogic ser"er that ha"e
been set inside the weblogic.properties file? $n particular $ am after the document
root of my ser"er.
$n WebMogic =.1, to gain access to the weblogic properties, you can use the
/onfig+er"icesGef interface which is accessible from the T0/lient. The particular
property that you are after is 8
weblogic.httpd.documentCoot
-ou may need to pre1pend the following properties to get the full path
weblogic.system.home
weblogic.system.name
The following is some sample code that should get you going
import weblogic.common.N:
public class +impleT0/lient 9
public static "oid main(+tringJK arg") throws Dception 9
T0/lient t0 = new T0/lient(%t0855localhost8@EE1%):
t0.connect():
+tring prop = t0.ser"ices.config()
.getIroperty(%weblogic.httpd.documentCoot%):
t0.disconnect():
;
;
)) What is the difference between WebMogic Dpress ser"er and WebMogic ser"er?
WebMogic Dpress is a %cut1down% "ersion of the WebMogic +er"er and contains the
2G7/ connection pool and +er"let functionality but amongst others, does not
contain an D27 /ontainer or transcation ser"ices.
0) What are the tradeoffs between using a single 2CD "ersus running multiple,
separate instances of the 2L? for a comple application li'e an application
ser"er?
&ne of the ma#or problems with 2L? is garbage collection. When running small,
short1li"ed applications there are not significant problems with .arbage
/ollection.
*owe"er, in the case of an 3pplication +er"ers, which must ser"ice clients for
long durations, memory usage is high and the amount of wor' required by the
.arbage /ollector is in turn high. This can lead to the following problems8 +low
.arbage /ollection or the .arbage /ollector ta'ing large amounts of
time5resources to complete its, cycles.
Page 123 of 136
+o, for scalability, it is better to run multiple L?s 1 ma'ing each L? use only 1EE
1 )EE megs of memory.
6) *ow do $ configure my 3pplication +er"er to show a different Drror page upon an
eception from a 2+I or +er"let?
There should be one answer to this question that wor's for all ).) compliant
ser"let containers. The answer is to edit the "eb.%ml deployment descriptor for
your web app and add an error9page tag. The error9page tag tells the
container the location of a page to return when an eception or error occurs. -ou
can use the same mechanism to return customi(ed error pages based either on
a specific eception that is thrown, or based on the *TTI status code that is
returned. The tag loo's li'e this8
Uerror1pageX
Ae%ception9typeBjava.lang.6ull3ointerE%ceptionA8e%ception9
typeB
AlocationBmy3age.,tmlA8locationB
A8error9pageB
&r
Uerror1pageX
Aerror9codeB5$$A8error9codeB
AlocationBmy3age.,tmlA8locationB
A8error9pageB
=) When are stubs H s'eletons created for my D27 components? is it at
de"elopment time, deployment time or run time?
The time of creation of stubs and s'eletions for D27 components "aries from
ser"er to ser"er.
The creation of stubs and s'eletons for the popular ser"ers is outlined below8
Inprise "pplication 'erver :#*
The stubs and s'eletons can be created during de"elopment time, for
de"elopment and testing with the command line utility of with 27uilder. The stubs
and s'eletons for the D27 can also be created during deployment using the $3+
/onsole. There is also an option to create a /lient 2ar file. The /lient 2ar file
contains the necessary stubs and interfaces for the D27 which a client requires to
in"o'e the D27.
;eb,ogic 'erver :#9#*$ 9#*
The stubs and s'eletons are created at deployment time using the command line
utility called weblogic.e#bc. $n WebMogic =., there is also a Geployer Tool
a"ailable that will in"o'e the e#bc utility automatically.
Page 124 of 136
&<oss 'erver
$n #7oss, the stubs and s'eletons are not required to be generated by the
de"eloper or deployer. The +er"er ta'es care of the creation and downloading of
stubs.
>) What are the features5limitations of /ontainer ?anaged Iersistnce with Weblogic
=.. 3re there any recommendations when using it?
-ou can,t specifiy storage of ob#ects. !or instance, &racle Ai does support
storage of ob#ects, i.e 7lobs and /lobs.
-ou are limited to the +tring ob#ects and a few other primiti"e types. (!or
storage of arrays of "alues, you may need to find a wor' around. )
3n Dntity 7ean can only map to one table, if more comple #oins are
required, you may require a more comple persistence manager( such as
/oco7ase or TopMin')
@) $n WebMogic 6.=1 and =., what is the weblogic.system.eecuteThread/ount
used for? What is its maimum and recommended "alue(s)?
The weblogic.system.eecuteThread/ount property is used to configure the
number of eecute threads inside the eecute thread pool that ser"ice requests
made to the WebMogic ser"er. The maimum "alue for this parameter is
operating system dependent and recommended setting will "ary upon your
application beha"ior.
3 general strategy for determining the optimal "alue for your system is to monitor
your /I4 utili(ation whilst running a test application.
$f the WebMogic ser"er is not responding to requests made from a client, and the
/I4 utili(ation is not at least @=T P, then you should increase the "alue and re1
run the test.
A) $s there an eample of writing a WebMogic /?I D27 that has a user1defined
finder method with multiple parameters?
!or Weblogic =.1 the finder method is written as follows8
find7y3ccount(+tring str,+tring str1)
!or the abo"e finder method we write in the deployment descriptor8
UfinderX
Amet,od9nameBfind'y&ccountA8met,od9nameB
Amet,od9paramsB
Amet,od9pramBjava.lang.String A8met,od9pramB
Amet,od9pramBjava.lang.String A8met,od9pramB
A8met,od9paramsB
Afinder9queryBA C DC:&(&D(E (F name G$) (F address G@))HHB
A8finder9queryB
A8finderB
Page 125 of 136
B) What is a weblogic.properties file? *ow can $ create a new one?
The weblogic.properties file is used to configure the Weblogic ser"er. $t is used in
"ersions =. and pre"ious. $n "ersion >.E, it has been deprecated and replaced
with an ml file (config.ml).
The weblogic.properties file is a plain tet file that follows the standard 2a"a
property file format 1 see this !3R for more details. 3ll configuration information
for the Weblogic ser"er is placed inside this file, including8
Geployments of D27,s and +er"lets
Gefinitions of 2G7/ /onnection Iools and Gata+ources
+ystem configuration 1 Iort and 3ddress settings
+ecurity and 3ccess /ontrol Mist definitions
3n eample of a property from a weblogic.properties file is as follows8
weblogic.system.listenIort=@EE1
To create a new weblogic.properties file, simply create a new tet file with the
name weblogic.properties.
1E)$n WebMogic =., how can $ turn off logging to the console window?
-ou can do this by setting the following property in your weblogic.properties file
weblogic.system.enable/onsole=false
11)What is a third party tool?
!irst party tools would be something you create yourself. +econd party tools
would be tools you buy from a "endor, li'e an $GD. Third party tools are tools for
use with second party tools that aren,t from the second party "endor. Thin' of
them as add1ons to ma'e second party tools more useful.
1))*ow do you deploy D27 components inside the iIlanet 3pplication +er"er?
The iIlanet deployment tool, is in my opinion, the simplest way to deploy D27s.
*owe"er, for a more fleible and faster way using command line, the process is
the following8
E*ample assumes bean called Foo
1. /ompile your source files8 !oo.#a"a, !oo*ome.#a"a,
). ). .enerate the stubs using e#bc.ee. The format is8 usage (typical)8 D27/
UoptionsX UhomeX UremoteX UimplX
usage (C?$/ mode)8 D27/ UoptionsX 1rmic UremoteX
options8
1sl /ompile as stateless session bean
Page 126 of 136
1sf /ompile as stateful session bean
1cmp /ompile as /?I entity bean
1iiop .enerate additional /&C73 classes
1gs .enerate #a"a source files
1d UdirX &utput directory
1help +how this message
1rmic .enerate C?$/ code (see usage)
1cp UclasspathX +et classpath
1#a"accp UclasspathX Irefi to #a"ac classpath
0. Ilace your files and the compiled stubs in a directory along with the Q?M
descriptors in a 2ar compliant directory structure.
6. .enerate a #ar file (!oo.#ar) that contains the descriptors, the stubs, your
class files and the manifest.
=. Decute e#breg as follows8 e#breg !oo.#ar
This will register the bean. -ou will still need to ma'e sure that the #ar file is in
iIlanet,s classpath ('regedit for <T, edit '#s in 4ni)
10)$n WebMogic, *ow $ can set my own property name and "alue in the
%eblogic#properties file and read that properties from a my code?
To do this, prepend your property with #a"a.system.property.
and access your property using the +ystem class. !or eample, if we ha"e a
property called %website% then we would add it to our property file as follows8
#a"a.system.property.website=www.#guru.com
The code used to access this property would be as follows8
+tring s = +ystem.getIroperty(%website%):
16)$n Weblogic, where do you find the classes for the #a"a.naming and #a"a.sql
pac'ages?
$n WebMogic =.1, these pac'ages are located in
Uweblogic dirX WlibWweblogicau.#ar
$n WebMogic >, they are located in
Uweblogic dirXWlibWweblogic.#ar
1=)$n WebMogic =.1, what options are there for +ession Iersistence? *ow do they
compare in relation to performance, and le"el of fail1o"er?
Page 127 of 136
There are four different implementations of session persistence8
1. ?emory (single1ser"er, non1replicated)
). !ile system persistence
0. 2G7/ persistence
6. $n1?emory replication (across a cluster)
!or customers who want the highest in ser"let session persistence, 2G7/1based
persistence is the best choice.
!or customers who want to sacrifice some amount of session persistence in
fa"or of drastically better performance, in1memory replication is the appropriate
choice.
2G7/1based persistence is noticeably slower than in1memory replication. $n
some cases, in1memory replication has outperformed 2G7/1based persistence
for ser"let sessions by a factor of eight.
1>)When calling an D27 from another D27 should they both be pac'aged in same
23C?. 3re the any preferences for Weblogic or any other ser"ers?
Gefinitely not. -ou can use any ob#ect published in 2<G$ by loo'ing up it by
name, obtain reference to it and narrowing this reference. 3s far as $ 'now this
can be done with any 2)DD compatible ser"er.
The only possible catch is to ha"e the client classes a"ailable to the calling bean.
1@)Which WebMogic 6.=5=. property is used to control the number of queued
requests inside the WebMogic ser"er?
The property that you are loo'ing for is weblogic.system.acceptBacklog
1A)When $ try load N.#sp files, $ see the source code of each 2+I files in my browser,
what is wrong?
-ou can only load a 2+I file through you webser"er, if you open them by hand
the browser will show the 2a"a code inside the *T?M file. 7y starting you Tomcat
(or an other 2+I 5 +er"let engine) the ser"er will compile the 2+I and will send a
,normal, *T?M file to you browser that will beha"e as you coded it in the 2a"a
code between the *T?M tags.
$f you did start the 2+I 5 +er"let engine but you are still seeing the 2+I code then
the ser"er mappings are wrong. The engine does not 'now that it should compile
the 2+I file that is requested and simple shows the complete file. $n the Tomcat
engine this is specified in the server#*ml file in the con! directory. The server#*ml
should contain this8
Page 128 of 136
User"letX
User"let1nameX
#sp
U5ser"let1nameX
User"let1classX
org.apache.#asper.runtime.2sp+er"let
U5ser"let1classX
Uload1on1startupX
1)16@6A0>6>
U5load1on1startupX
U5ser"letX
This piece of Q?M tells the Tomcat ser"er that it must use the 2sp+er"let class
when a 2+I file is requested. The 2sp+er"let then chec's if the 2+I file is
compiled or not.
1B)What can $ do if my +er"let is recei"ing a <ullIointerDception when accessing
init parameters "ia the +er"let/onfig ob#ect in WebMogic?
?a'e sure that your +er"let calls super.init(config) inside the init() method.
e.g.
public void init(ServletConfig config) 1
...
super.init(config):
...
;
)E)*ow are +er"lets and 2+I,s deployed inside WebMogic?
Ilace all your +er"let /lass files in the following directory
weblogic5myser"er5ser"letclasses5Upac'age structureX 3dd the following lines in
your weblogic.properties file
weblogic.httpd.register.ser"lets=weblogic.ser"let.+er"let+er"let
and weblogic.httpd.ser"let.classpath=Udri"e name8X
5weblogic5myser"er5ser"letclasses5
Ilace all your 2+I,s in the following directory weblogic5myser"er5publicYhtml
)1)$n a Weblogic /?I D27, how to obtain the maimum "alue in the specified
database column? $n WMRM is there something similar to ?3Q() function in +RM?
dont 'now how to write in WMRM. 3nother solution is to write the query using
+RM inside the weblogic1cmb1rdbms1#ar.ml file.
Page 129 of 136

U?ml "ersion=%1.E% encoding=%4T!1A%?X
Ufinder1listX
UfinderX
Amet,od9nameBfind'yOrgnA8met,od9nameB
Amet,od9paramsB
Amet,od9pramB
Apram9typeBjava.lang.StringA8pram9typeB
Apram9nameBorgnCodeA8pram9nameB
A8met,od9pramB
A8met,od9paramsB
Afinder9typeBSI0A8finder9typeB
Afinder9queryB
A C D C:&(&DSE0EC( J F+O* &sn-Koal-* .5E+E ( orgn-code F LorgnCode and
:E0E(E-F0&KFM6M) H H B
A8finder9queryB
A8finderB
)))When using 2a"a7eans from my 2+I inside WebMogic, where should $ place the
2a"a7ean classes?
-ou should place these inside of a Web 3pplication
$f you are using an older "ersion of WebMogic, you can place these classes on
your +er"let /lasspath.
)0)What is the difference between an 3pplication ser"er and a Iortal ser"er?
3 %portal ser"er% is #ust an application ser"er running a portal sofware or a portal
application (?icrosoft +harepoint Iortal +er"er is an eample).
3n application ser"er is a system that pro"ides the eecution en"ironment that is
at the core of networ' computing or web1based architectures, pro"iding a full set
of ser"ices.
)6)*ow do $ use an D27 to handle simple authentication to an MG3I
directory?
?y recommendation would be to create a session bean that acquires an MG3I
52<G$ contet in the set+ession() method. 3 subsequent call to authenticate
would pass in a user and password. The following code shows how to
authenticate the passed "alues8
en".put(/ontet.$nitial/ontet!actory, %com.sun.#ndi.ldap.Mdap/t!actory%): == I
added this line mysel!
en".put(/ontet.+D/4C$T-Y34T*D<T$/3T$&<, %simple%):
en".put(/ontet.+D/4C$T-YIC$</$I3M, %cn=+. 4ser, ou=<ew*ires,
o=2<G$Tutorial%):
en".put(/ontet.+D/4C$T-Y/CDGD<T$3M+, %mysecret%):
Page 130 of 136
55 /reate the initial contet
Gir/ontet ct = new $nitialGir/ontet(en"):
3 failure in authentication will cause this code to throw a
#a"a.naming.3uthenticationDception
-ou may want to store the actual MG3I tree that contains the users you are
authenitcating so youi can dynamically set it without recoding, so the actual code
may loo' li'e this if you store the MG3I tree name in 2<G$ as
%my4serMG3ITree% (ou=<ew*ires, o=2<G$Tutorial)8
en".put(/ontet.$nitial/ontet!actory, %com.sun.#ndi.ldap.Mdap/t!actory%): == I
added this line mysel!
en".put(/ontet.+D/4C$T-Y34T*D<T$/3T$&<, %simple%):
en".put(/ontet.+D/4C$T-YIC$</$I3M, %cn=% P passed4ser<ame P %,% P
(+tring)new $nitial/ontet().loo'up(%my4serMG3ITree%)):
en".put(/ontet.+D/4C$T-Y/CDGD<T$3M+, passedIassword):
55 /reate the initial contet
Gir/ontet ct = new $nitialGir/ontet(en"):
The simply return a true, or a false if a #a"a.naming.3uthenticationDception is
thrown.
)>) $ want to set some user defined properties to be used in my application
running in WebMogic appser"er. $n WebMogic =.1, $ was able to do this by
setting them as +ystem properties inside the weblogic.properties file li'e8
#a"a.system.property.myproperty=my"alue
*ow do $ achie"e the same in WebMogic > ?
To be WebMogic > and 2)DD compliant, you should use en"ironment entries inside
your ml descriptors for both D27 application archi"es and web application archi"es
and use the 2<G$ en"ironment naming contet (D</) to retrie"e the "alues.
)@) Gifferences in obtaining connection pools $,m trying to understand the difference
between two ways to get a connection from a Weblogic >.E connection pool.
What are the two ways and is either method preferable to the other? &r does it not
matter?
The two different ways that we can get a connection from a pool are listed as
follows(ta'en from the original posting from the author).
1. *a"e a connection pool manager with a get/onnection method that uses the
following code8
/onnection conn = null:
Page 131 of 136
Gri"er myGri"er
=(Gri"er)/lass.for<ame(%weblogic.#dbc.pool.Gri"er%).new$nstance():
Iroperties props = new Iroperties():
props.put(%connectionIool$G%,%Iool<ame%):
conn = myGri"er.connect(%#dbc8weblogic8pool%, props):
). 4sing 2<G$ and pro"iding a 4CM (such as IC&L$GDCY4CM below) for the
machine the connection pool is on. The following code could be used in a
/onnectionIool?anager class too8
/ontet ct = null:
*ashtable ht = new *ashtable():
ht.put(/ontet.$<$T$3MY/&<TDQTY!3/T&C-,%weblogic.#ndi.WM$nitial/ontet!a
ctory%):
ht.put(/ontet.IC&L$GDCY4CM,%t0855hostname8port%):
try 9
ct = new $nitial/ontet(ht):
#a"a.sql.Gata+ource ds =(#a"a.sql.Gata+ource)
ct.loo'up(%my2tsGata+ource%):
#a"a.sql./onnection conn = ds.get/onnection():
; catch (Dception e) 9;
The underlying result is the same. *owe"er, using a Gata+ource is the newer
and much preferred method as the de"eloper does not tie themsel"es to a
particular dri"er or connection pool. There is also the added fleibility of changing
connection pool properties without modifying the code.
)@) $s there a simple eample of how to use web application security in WebMogic?
!ollowing is an eample for WebMogic >. that protects all 4CMs that begin with
5secure8
WD71$<!5web.ml 1 Gefine a constraint and a role
UVG&/T-ID web1app I47M$/ %155+un ?icrosystems, $nc.55GTG Web 3pplication
).)55D<% %http855#a"a.sun.com5#)ee5dtds5web1appY)Y).dtd%X
Uweb1appX
Usecurity1constraintX
Uweb1resource1collectionX
Uweb1resource1nameX+ecureIagesU5web1resource1nameX
UdescriptionX+ecurity constraint for resources in the secure
directoryU5descriptionX
Uurl1patternX5secure5NU5url1patternX
Uhttp1methodXI&+TU5http1methodX
Page 132 of 136
Uhttp1methodX.DTU5http1methodX
U5web1resource1collectionX
Uauth1constraintX
UdescriptionXonly let the admin role access the pages
U5descriptionX
Urole1nameXadminU5role1nameX
U5auth1constraintX
Uuser1data1constraintX
UdescriptionX++M not requiredU5descriptionX
Utransport1guaranteeX<&<DU5transport1guaranteeX
U5user1data1constraintX
U5security1constraintX
Ulogin1configX
Uauth1methodX73+$/U5auth1methodX

Usecurity1roleX
UdescriptionX3 role to access the secured pagesU5descriptionX
Urole1nameXadminU5role1nameX
U5security1roleX
U5web1appX
WD71$<!5weblogic.ml 1 ?ap the admin role to the system user in WebMogic.
UVG&/T-ID weblogic1web1app I47M$/ %1557D3 +ystems, $nc.55GTG Web
3pplication >.E55D<% %http855www.bea.com5ser"ers5wls>EE5dtd5weblogic1web1
#ar.dtd%X
Uweblogic1web1appX
Usecurity1role1assignmentX
Urole1nameXadminU5role1nameX
Uprincipal1nameXsystemU5principal1nameX
U5security1role1assignmentX
U5weblogic1web1appX
)A) What is a ?ultipool used for inside WebMogic?
-ou can thin' of a ?ultipool as a %pool of pools%. WebMogic >. allows you to
create a ?ultipool and ha"e it mapped to a Gata+ource.
?ultipools support two mutually elusi"e algorithms8
1. Moad 7alancing 1 where requests are shared amongst the pools and,
Page 133 of 136
). *igh 3"ailability 1 where the first pool is used until a fatal eception
occurs, then control is passed to the second pool. <ote that transaction
information is not sa"ed in the e"ent of an error.
The client program is un1aware that a ?utlipool is being used, so there are no
coding changes required, it is simply an administration change. ?ultipools wor'
well with database failo"er products such as &racle Iarallel +er"er.
)B)What are the "alid "alues for the +ession Gescriptor inside the weblogic.ml file for
WebMogic >.1?
3 list of "alid parameter names for the +ession Gescriptor in webMogic >.1 are as
follows8
/ache+i(e
/onsole?ain3ttribute
/oo'ie/omment
/oo'ieGomain
/oo'ie?a3ge+ecs
/oo'ie<ame
/oo'ieIath
/oo'iesDnabled
$GMength
$n"alidation$nter"al+ecs
2G7//onnectionTimeout+ecs
Iersistent+tore/oo'ie<ame
Iersistent+toreGir
Iersistent+toreIool
Iersistent+toreType
+wap$nter"al+ecs
Timeout+ecs
Trac'ingDnabled
4CMCewritingDnabled
Dach should be enclosed within a separate Usession1pramX tag as follows8
Usession1descriptorX
Usession1pramX
Upram1nameX4CMCewritingDnabledU5pram1nameX
Upram1"alueXTrueU5pram1"alueX
U5session1pramX
Usession1pramX
Upram1nameX/oo'iesDnabledU5pram1nameX
Upram1"alueXTrueU5pram1"alueX
U5session1pramX
U5session1descriptorX
0E)*ow can $ setup a +tartup /lass in Web+phere 0.=
Page 134 of 136
$7? Web+phere pro"ides the .4$ where the option is there to set wether the
ser"er wants a particular +er"lets is to be in"o'ed upon start up. This will
updated the Q?M as follows8
User"let name=%!ile +er"ing Dnabler% action=%update%X
UdescriptionX3uto1.enerated 1 !ile +er"ing +er"letU5descriptionX
com.ibm.ser"let.engine.webapp.+imple!ile+er"let
Uinit1parameters5X
Uload1at1startupXtrueU5load1at1startupX
Udebug1modeXfalseU5debug1modeX
Uuri1pathsX
Uuri "alue=%5ser"let5%5X
U5uri1pathsX
UenabledXtrueU5enabledX
U5ser"letX
01)/ould you please help me??? What is the difference between Iroduction mode and
Ge"elopment mode in WebMogic >.1?
Ilacing the WebMogic ser"er in Iroduction mode will disable automatic
deployment. This is the feature that allows you to automatically deploy an D27,
W3C or D3C file into the ser"er by placing it into your configuration5applications
directory.
This is turned off in production to reduce the o"erhead of continually polling the
directory for updates.
0))Cetrie"ing user name from inside each bean.
$nside an D27 you may retrie"e the %/aller% name, that is the login id by in"o'ing8
sessionConte%t.getCaller/dentity().get6ame()
where sessionConte%t is the instance of %+ession/ontet%
(setSessionConte%t) passed to the +ession 7ean, or the instance of
%Dntity/ontet% (setEntityConte%t) passed to the Dntity 7ean.
00)*ow can $ use /onnection Iool?
"dditional in!o4
$ am using &racle Bias ser"er. $ ha"e gi"en ma1connections to =E
in data1sources.ml file. 3nd the class i am using is
%oracle.#dbc.pool.&racle/onnection/ache$mpl%. $ ha"e also tried
with &racle/onnectionIoolGata+ource class in data1sources.ml.
7ut i feel that connection pool is not utilised, because in the middle
of the retrie"al, the ser"er hangs as there will no be connections left
for opening...
$n entity beans, $ ha"e created connections in setDntity/ontet and
releasing them in unsetDntity/ontet...
Page 135 of 136
Go not get the connection in the setDntity/ontet. .et the connection only when
you need it.
$f you get the connection in setDntity/ontet with the pool of =E connections and
you retrie"e =E different entity beans each bean will hang on to the connection
and you will hang.
+o, get the connection when you need it and release the connection as soon as
you ha"e no need for it any longer.
There is no reason to get the connection in setDntity/ontet.
06)3re there any tools for porting D27 3pplications from one 3pplication +er"er to another?
$n theory, you should not need any tools for that tas'.
$f you ha"e de"eloped a fully compliant 2)DD application, you will be able to
deploy it on any 3pplication +er"er that follows +un 2)DD +pecifications. That is
one of the biggest ad"antages of using standards and following the
spceifications.
Maybe$ then$ you %ill probably have to spend some time in tuning and !i*ing the
con!iguration o! the speci!ic server#
Page 136 of 136

You might also like