Professional Documents
Culture Documents
Iterator vs Enumeration
1. Iterator interface adds the remove() by which you can safely delete an element off the
collection as you iterate thru it.
This feature becomes quite essential when ure writing multi-threaded code but this is not
supported by most implementations of the Enumeration interface.
Most of the collection classes in the Java Collection Framework only support the Iterator
and it is a recommended practice by Sun to prefer Iterator over Enumeration.
The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is
structurally modified at any time after the iterator is created, in any way except through
the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the
iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior
at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally
speaking, impossible to make any hard guarantees in the presence of unsynchronized
concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a
best-effort basis. Therefore, it would be wrong to write a program that depended on this
exception for its correctness: the fail-fast behavior of iterators should be used only to
detect bugs.
javax.servlet
Interface ServletRequest
getRequestDispatcher
1
public RequestDispatcher getRequestDispatcher(java.lang.String path)Returns a
RequestDispatcher object that acts as a wrapper for the resource located at the given
path. A RequestDispatcher object can be used to forward a request to the resource or to
include the resource in a response. The resource can be dynamic or static.
The pathname specified may be relative, although it cannot extend outside the current
servlet context. If the path begins with a "/" it is interpreted as relative to the current
context root. This method returns null if the servlet container cannot return a
RequestDispatcher.
2
it pays not to set the expected maximum size too high if you are especially concerned
with iteration performance or memory usage.
Note that this implementation is not synchronized. If multiple threads access this
map concurrently, and at least one of the threads modifies the map structurally, it must
be synchronized externally. (A structural modification is any operation that adds or
deletes one or more mappings; merely changing the value associated with a key that an
instance already contains is not a structural modification.) This is typically accomplished
by synchronizing on some object that naturally encapsulates the map. If no such object
exists, the map should be "wrapped" using the Collections.synchronizedMap method.
This is best done at creation time, to prevent accidental unsynchronized access to the
map:
Map m = Collections.synchronizedMap(new HashMap(...));
The iterators returned by all of this class's "collection view methods" are fail-fast: if the
map is structurally modified at any time after the iterator is created, in any way except
through the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the
iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior
at an undetermined time in the future.
3
examinations of the key set, the value set, and the entry set to yield successively smaller
numbers of elements.
Each key object in a WeakHashMap is stored indirectly as the referent of a weak
reference. Therefore a key will automatically be removed only after the weak references
to it, both inside and outside of the map, have been cleared by the garbage collector.
Implementation note: The value objects in a WeakHashMap are held by ordinary
strong references. Thus care should be taken to ensure that value objects do not
strongly refer to their own keys, either directly or indirectly, since that will prevent the
keys from being discarded. Note that a value object may refer indirectly to its key via the
WeakHashMap itself; that is, a value object may strongly refer to some other key object
whose associated value object, in turn, strongly refers to the key of the first value object.
One way to deal with this is to wrap values themselves within WeakReferences before
inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon
each get.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally
speaking, impossible to make any hard guarantees in the presence of unsynchronized
concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a
best-effort basis. Therefore, it would be wrong to write a program that depended on this
exception for its correctness: the fail-fast behavior of iterators should be used only to
detect bugs.
When you are creating an HTML FORM for posting data, the contentType of the request
is application/x-www-form-urlencoded by default.
Procedures and functions are similar except that procedures can’t return a value
whereas function can.
A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note
that some ODBC native code and in many cases native database client code must be
loaded on each client machine that uses this type of driver. Hence, this kind of driver is
generally most appropriate when automatic installation and downloading of a Java
technology application is not important. For information on the JDBC-ODBC bridge
driver provided by Sun, see JDBC-ODBC Bridge Driver.
A native-API partly Java technology-enabled driver converts JDBC calls into calls on
the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the
bridge driver, this style of driver requires that some binary code be loaded on each client
machine.
4
A net-protocol fully Java technology-enabled driver translates JDBC API calls into a
DBMS-independent net protocol which is then translated to a DBMS protocol by a
server. This net server middleware is able to connect all of its Java technology-based
clients to many different databases. The specific protocol used depends on the vendor.
In general, this is the most flexible JDBC API alternative. It is likely that all vendors of
this solution will provide products suitable for Intranet use. In order for these products to
also support Internet access they must handle the additional requirements for security,
access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC
technology-based drivers to their existing database middleware products.
This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types
are used to categorize the technology used to connect to the database. A JDBC driver
vendor uses these types to describe how their product operates. Some JDBC driver
types are better suited for some applications than others.
Type 1
Type 1 drivers are "bridge" drivers. They use another technology such as Open
Database Connectivity (ODBC) to communicate with a database. This is an advantage
because ODBC drivers exist for many Relational Database Management System
(RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from
the JDBC driver.
A Type 1 driver needs to have the bridge driver installed and configured before JDBC
can be used with it. This can be a serious drawback for a production application. Type 1
drivers cannot be used in an applet since applets cannot load native code.
Type 2
Type 2 drivers use a native API to communicate with a database system. Java native
methods are used to invoke the API functions that perform database operations. Type 2
drivers are generally faster than Type 1 drivers.
Type 2 drivers need native binary code installed and configured to work. A Type 2 driver
also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load
native code. A Type 2 JDBC driver may require some Database Management System
(DBMS) networking software to be installed.
The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.
Type 3
These drivers use a networking protocol and middleware to communicate with a server.
The server then translates the protocol to DBMS function calls specific to DBMS.
5
Type 3 JDBC drivers are the most flexible JDBC solution because they do not require
any native binary code on the client. A Type 3 driver does not need any client installation.
Type 4
A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the
protocols are usually proprietary, DBMS vendors are generally the only companies
providing a Type 4 JDBC driver.
Type 4 drivers are all Java drivers. This means that there is no client installation or
configuration. However, a Type 4 driver may not be suitable for some applications if the
underlying protocol does not handle issues such as security and network connectivity
well.
RunTime rt = RunTime.getRunTime();
A table of interrupt vectors (pointers to routines that handle interrupts). On PCs, the
interrupt vector table consists of 256 4-byte pointers, and resides in the first 1 K of
addressable memory. Each interrupt number is reserved for a specific purpose. For
example, 16 of the vectors are reserved for the 16 IRQ lines.
Page fault
An interrupt that occurs when a program requests data that is not currently in real
memory. The interrupt triggers the operating system to fetch the data from a virtual
memory and load it into RAM.
6
An invalid page fault or page fault error occurs when the operating system cannot find
the data in virtual memory. This usually happens when the virtual memory area, or the
table that maps virtual addresses to real addresses, becomes corrupt.
7
Threads are distinguished from traditional multi-tasking operating system processes in
that processes are typically independent, carry considerable state information, have
separate address spaces, and interact only through system-provided inter-process
communication mechanisms. Multiple threads, on the other hand, typically share the
state information of a single process, and share memory and other resources directly.
Context switching between threads in the same process is typically faster than context
switching between processes. Systems like Windows NT and OS/2 are said to have
"cheap" threads and "expensive" processes, while in other operating systems there is
not so big a difference.
Traditional mainstream computing hardware did not have much support for
multithreading as switching between threads was generally already quicker than full
process context switches. Processors in embedded systems, which have higher
requirements for real-time behaviors, might support multithreading by decreasing the
thread switch time, perhaps by allocating a dedicated register file for each thread instead
8
of saving/restoring a common register file. In the late 1990s, the idea of executing
instructions from multiple threads simultaneously has become known as simultaneous
multithreading. This feature was introduced in Intel's Pentium 4 processor, with the name
Hyper-threading.
[edit]
Processes, threads, and fibers
The concept of a process, thread, and fiber are interrelated by a sense of "ownership"
and of containment.
A process is the "heaviest" unit of kernel scheduling. Processes own resources allocated
by the operating system. Resources include memory, file handles, sockets, device
handles, and windows. Processes do not share address spaces or file resources except
through explicit methods such as inheriting file handles or shared memory segments, or
mapping the same file in a shared way. Processes are typically pre-emptively
multitasked. However, Windows 3.1 and older versions of Mac OS used co-operative or
non-preemptive multitasking.
A thread is the "lightest" unit of kernel scheduling. At least one thread exists within each
process. If multiple threads can exist within a process, then they share the same
memory and file resources. Threads are pre-emptively multitasked if the operating
system's process scheduler is pre-emptive. Threads do not own resources except for a
stack and a copy of the registers including the program counter.
In some situations, there is a distinction between "kernel threads" and "user threads" --
the former are managed and scheduled by the kernel, whereas the latter are managed
and scheduled in userspace. In this article, the term "thread" is used to refer to kernel
threads, whereas "fiber" is used to refer to user threads. Fibers are co-operatively
scheduled: a running fiber must explicitly "yield" to allow another fiber to run. A fiber can
be scheduled to run in any thread in the same process.
Forward
9
redirect is always slower than a forward, since it requires a second browser request
beans placed in the original request scope are not available to the second request
Strings intern
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }
10
Thread Safety in servlets
Multi-threaded model
The multi-threaded model, which is used by default, causes the container to use only
one instance per servlet declaration. By using a separate thread for each request,
efficient processing of client requests is achieved.
SingleThreadModel interface
A very convenient way of ensuring that no two threads will execute concurrently in
the servlet's service() method is to make the servlet implement the
SingleThreadModel interface. The SingleThreadModel interface does not
define any methods. The servlet container guarantees this by either synchronizing
access to a single instance of the servlet or by maintaining a pool of servlet
instances and dispatching each new request to a free servlet.
11
Instance variables are not thread safe in the case of the multi-threaded servlet
model. In the case of servlets implementing SingleThreadModel, instance
variables are accessed only by one thread at a time.
Static variables
Static variables are never thread safe. These variables are at class level, so they are
shared between all instances. Hence these variables are not thread safe even if the
servlet is implementing the SingleThreadModel interface. That is why they are
usually used to store only constant/read-only data.
Context scope
The ServletContext object is shared by all the servlets of a Web application, so
multiple threads can set and get attributes simultaneously from this object.
Implementing the SingleThreadModel interface does not make any difference in
this case. Thus the context attributes are not thread safe.
Session scope
The HttpSession object is shared by multiple threads that service requests
belonging to the same session, so the session attributes are also not thread safe.
Just as the case with context attributes, the threading model has no impact on this
behavior.
Request scope
The ServletRequest object is thread safe because it is accessible only locally
within the service() method, so the request attributes are safe, irrespective of the
threading model used.
During the page translation phase of a JSP page life-cycle, the JSP page is parsed and
a Java file containing the corresponding servlet is created. The servlet created will
contain the declared jspInit() overriding the default jspInit() method which is declared in a
vendor-specific JSP page base class.
The Java file is compiled during the JSP page compilation phase then an instance of the
servlet is created and initialised when the container makes a call to jspInit().
_jspService() is called by the container for each client request and finally the container
makes a call to jspDestroy() when it decides to take the servlet out of service.
-------the action JSP tag provides request-time instructions to the JSP engine
- jsp:plugin instructs the JSP engine to generate appropriate HTML code for
embedding applets on a web page. Custom tags (taglibs) allow user-defined
actions to be created.
--- the only standard action types are jsp:include, jsp:forward, jsp:useBean,
jsp:setProperty, jsp:getProperty, and jsp:plugin
12