My Collection

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View My Collection as PDF for free.

More details

  • Words: 4,335
  • Pages: 12
My Collection Iterator vs Enumeration The Iterator interface differs from the Enumeration interface in that: 1. Iterator interface adds the remove() by which you can safely delete an element off the collection as you iterate thru it. 2. Iterator implementations in the Java Collections Framework throw ConcurrentModificationException when another thread/method attempts to structurally modify(i.e. adds or removes items) the collection externally when it is under iteration. This prevent the Iterator from iterating over a stale collection of items. 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. Fail fast Iterators 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. HttpServlet is a class where as Servlet is an interface

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. The difference between this method and ServletContext.getRequestDispatcher(java.lang.String) is that this method can take a relative path.

public class IdentityHashMap extends AbstractMap implements Map, Serializable, Cloneable This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged. This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This class provides constant-time performance for the basic operations (get and put), assuming the system identity hash function (System.identityHashCode(Object)) disperses elements properly among the buckets. This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so

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. public class WeakHashMap extends AbstractMap implements Map A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing. The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive

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. What is difference between procedure and function? Procedures and functions are similar except that procedures can’t return a value whereas function can. Types Of JDBC Drivers 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. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress. Types of JDBC drivers 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.

Can I call destroy method of servlet locally? Yes

To execute external process in Java RunTime rt = RunTime.getRunTime(); Process pro = rt.exec(“C:/abc.exe“); BufferedReader br = new BufferedReader(pp.getInputStreamReader());

What is Interrupt Vector Table 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.

Inter Process Communication Inter-Process Communication (IPC) is a set of techniques for the exchange of data between two or more threads in one or more processes. Processes may be running on one computer or on two or more computers connected by a network. IPC techniques are divided into methods for message passing, synchronization, shared memory, and remote procedure calls (RPC). The method of IPC used may vary based on the bandwidth and latency of communication between the threads, and the type of data being communicated. IPC may also be referred to as inter-thread communication and inter-application communication. Table of IPC Methods: Method ---------File Signal Socket Pipe Named pipe Semaphore Shared memory Memory map Message queue Mailbox

Provided by (Operating Systems or other environments) --------------------------------------------------------------------------All operating systems All operating systems Most operating systems All POSIX systems All POSIX systems All POSIX systems All POSIX systems Message passing (shared nothing) Used in MPI paradigm, Java RMI, CORBA and others All POSIX systems; may carry race condition risk if a temporary file is used Most operating systems Some operating systems

Thread synchronization (semaphore/lock/monitor) process and thread fragmentation and defragmentation types of fragmentation SCM Difference between pop and oop

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. Multithreading is a popular programming and execution model that allows multiple threads to exist within the context of a single process, sharing the process' resources but able to execute independently. The threaded programming model provides developers with a useful abstraction of concurrent execution. However, perhaps the most interesting application of the technology is when it is applied to a single process to enable parallel execution on a multiprocessor system. This advantage of a multi-threaded program allows it to operate faster on computer systems that have multiple CPUs, CPUs with multiple cores, or across a cluster of machines. This is because the threads of the program naturally lend themselves for truly concurrent execution. In such a case, the programmer needs to be careful to avoid race conditions, and other non-intuitive behaviors. In order for data to be correctly manipulated, threads will often need to rendezvous in time in order to process the data in the correct order. Threads may also require atomic operations (often implemented using semaphores) in order to prevent common data from being simultaneously modified, or read while in the process of being modified. Careless use of such primitives can lead to deadlocks. Operating systems generally implement threads in one of two ways: preemptive multithreading, or cooperative multithreading. Preemptive multithreading is generally considered the superior implementation, as it allows the operating system to determine when a context switch should occur. Cooperative multithreading, on the other hand, relies on the threads themselves to relinquish control once they are at a stopping point. This can create problems if a thread is waiting for a resource to become available. The disadvantage to preemptive multithreading is that the system may make a context switch at an inappropriate time, causing priority inversion or other bad effects which may be avoided by cooperative multithreading. 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.

Definition: A thread is a single sequential flow of control within a program. Forward forward is performed internally by the servlet the browser is completely unaware that it has taken place, so its original URL remains intact any browser reload will simple repeat the original request, with the original URL Redirect redirect is a two step process, where the server sends back a HTTP response status 302 to the browser to fetch a second URL, which differs from the original. A browser reload of the second URL will not repeat the original request, but will rather fetch the second URL

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"; } produces the output: true true true true false true This example illustrates six points: • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1). • Literal strings within different classes in the same package represent references to the same String object. • Literal strings within different classes in different packages likewise represent references to the same String object. • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. • Strings computed by concatenation at run time are newly created and therefore distinct.

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.

Thread safety of variables and attributes A servlet developer has to be aware of the effect of multiple threads on variables and attributes stored in different scopes. Local variables Local variables are always thread safe because each servlet has its own copy of these variables, so they cannot be used to share data between threads because their scope is limited to the method in which they are declared. Instance variables

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.

JSP Life cycle 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

Related Documents

My Collection
November 2019 18
My Collection
November 2019 12
My Collection
May 2020 10