Thursday, February 26, 2009

Why do we need XML parser?

We need XML parser because we do not want to do everything in our application from scratch, and we need some "helper" programs or libraries to do something very low-level but very necessary to us. These low-level but necessary things include checking the well-formedness, validating the document against its DTD or schema (just for validating parsers), resolving character reference, understanding CDATA sections, and so on. XML parsers are just such "helper" programs and they will do all these jobsl. With XML parsers, we are shielded from a lot of these complexicities and we could concentrate ourselves on just programming at high-level through the API's implemented by the parsers, and thus gain programming efficiency.

Use of Java BigDecimal Class


Java BigDecimal Class
If you're in the finance arena and just can't deal with any chance of round off error, consider using the BigDecimal class found in the java.math package. For numbers larger then can be represented by a double or float, the BigDecimal class never rounds off, offering infinite precision.
The first thing you need to know when working with BigInteger is that you can't use the standard math operators like plus (+) or minus (-). Any time you need to do something as simple as adding numbers together, you must call a method of the class.
This brings up the second point of using the class. Created instances are immutable. In other words, once created, you can't change it. So, methods like add or divide return new BigDecimal objects, instead of updating existing ones.
When using BigDecimal, you specify a scale, meaning the number of digits after the decimal point, and all numerical computations return that many significant digits. When rounding must occur, you must specify a rounding constant so the system can determine how you want the system to truncate the last digit.
BigDecimal Rounding Constants:
ROUND_CEILING Round up towards positive infinity
ROUND_DOWN Round towards zero
ROUND_FLOOR Round towards negative infinity
ROUND_HALF_DOWN Round towards nearest neighbor, or zero if equal
ROUND_HALF_EVEN Round towards nearest neighbor, or even if equal
ROUND_HALF_UP Round towards nearest neighbor, or away from zero if equal
ROUND_UNNECESSARY Value can be represented without rounding
ROUND_UP Round away from zero
You can specify the scale for a BigDecimal in one of three ways. When you call the BigDecimal constructor with a String, the number of digits after the decimal place determines the scale. When you call the constructor passing in a BigInteger, you also pass in a scale. And, you can always change it later with setScale.
To demonstrate, the following program calculates how much money you'll have after a year, investing $10,000 in an account with an annual rate of return at 2.25%.
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

public class BigDecSample {
public static void main(String args[]) {
BigDecimal rate =
new BigDecimal(".022500");
BigDecimal months =
new BigDecimal("12");
BigDecimal monthlyRate =
rate.divide(months, BigDecimal.ROUND_HALF_DOWN);
NumberFormat pf =
NumberFormat.getPercentInstance(Locale.US);
pf.setMinimumFractionDigits(4);
System.out.println("Annual rate : "
+ pf.format(rate.doubleValue()));
System.out.println("Monthly rate: "
+ pf.format(monthlyRate.doubleValue()));
BigDecimal balance =
new BigDecimal("10000.0000");
NumberFormat nf =
NumberFormat.getCurrencyInstance();
for (int i=0; i<12; i++) {
BigDecimal interest =
balance.multiply(monthlyRate);
balance = balance.add(interest);
System.out.println("Balance : "
+ nf.format(balance.doubleValue()));
}
}
}
And then running the program generates the following output:
Annual rate : 2.2500%
Monthly rate: 0.1875%
Balance : $10,018.75
Balance : $10,037.54
Balance : $10,056.36
Balance : $10,075.21
Balance : $10,094.10
Balance : $10,113.03
Balance : $10,131.99
Balance : $10,150.99
Balance : $10,170.02
Balance : $10,189.09
Balance : $10,208.19
Balance : $10,227.33
Meaning that you'll get $227.33 back in interest, not $225 as you might expect, since earned interest is compounded, giving you interest on your interest.

Loading Applets in a browser

A common misconception of most newcomers to Java is that security restrictions apply only to applets (Java classes downloaded and executed within a web browser).In fact, security restrictions can apply to all Java classes. (However, they do not apply to classes loaded from the boot classpath.) Before the Java API performs an action that is potentially unsafe, it calls the Java Security Manager to determine whether the action is permitted. Here is a partial list of the actions for which checks take place:Reading, writing, or deleting a fileOpening, waiting for, or accepting a socket connectionModifying a thread attribute (for example, priority)Accessing or updating system propertiesIf the Java Security Manager does not permit the action, the Java API will not allow the action to take place. Now, you might ask, how is my application able to do one of these so-called unsafe calls, such as read or write a file? The answer is that the Java Security Manager is not installed by default; but it can be by calling it within your class or specifying a parameter to the Java command line. To establish the Java Security Manager within code, place the following as the first line in the main() method:System.setSecurityManager( new SecurityManager() );To establish the Java Security Manager via the command line, add the following parameter to the command line:-Djava.security.managerOnce installed, the Java Security Manager checks whether a particular permission is granted to the specific requesting class; it throws a SecurityException if the permission is denied. The Java Security Manager checks by examining the call trace,so if an untrusted piece of code is invoked as part of a call to a secured method, it will fail because of the presence of the untrusted code. The permission is itself an abstract class representing access to a system resource. The permission can optionally contain a name and an action. When specified, these optional attributes further refine the permission being granted. For example, java.io.SocketPermission can be established with a host name of 66.108.43.211:9080 and an action of accept,connect,listen, which will allow the code to accept connections on, connect to, or listen on port 9080 on a host specified by IP address 66.108.43.211.Here is a list of the security restrictions that Java 2 technology environments normally impose on applets running in a browser:An applet can utilize only its own code and is not allowed to load libraries or define native methods.An applet cannot read or write files on the host that is executing it.An applet can make network connections only to the host from which it was downloaded.An applet cannot start any program on the local host.An applet is restricted from reading the system properties.

Stateful Session EJBs

Purpose of Stateful Session EJBs
An Stateful Session EJB is a server-side object designed to hold data on behalf of a particular client. SFSBs should be used to store session-oriented data. Session-oriented data is used to track a multi-request sequence, ordering, or any associated data that is part of a sequence. SFSBs, however, have a limited lifespan and are not intended to survive server crashes. SFSBs are the only type of EJB that can receive callback notifications about the lifecycle of transactions that the bean participates in.When SFSBs shouldn't be usedSFSBs are not server-side data caches. Yes, they do hold data in the server on behalf of the client, but that does not make them an in-memory, persistent store data cache. Yes, SFSBs are allowed to access a database and load data into memory, but the act of cacheing persistent data lies within the responsibilities of entity beans. A primary requirement for a data cache is that multiple clients should be able to access the same data concurrently based upon locking rules dictated by the developer. SFSBs are not designed to be shared resources to intuitively allow for this type of concurrent access. In the EJB 1.1 specification, concurrent client access of SFSBs was strictly prohibited. In EJB 2.0, a container vendor's implementation may permit concurrent client access of a single SFSB. Despite this new capability in EJB 2.0, SFSBs should not be used in a design that calls for multiple client concurrent access because they make it easy for a developer to code a deadlock.The only data that should be cached within an SFSB is data pertaining to tracking the sequence that the SFSB is managing. I've seen too many clients take 30 minutes to build an SFSB with persistent data and then spend 30 days trying to architect a solution that converts the bean into a transaction-aware data cache. Just don't do it -- you are setting yourself up for guaranteed failure.Part of this misperception about SFSBs comes from the wording within the EJB specification itself! The EJB specification suggests that a shopping cart for an e-commerce system could be implemented with SFSBs. This is perfectly acceptable if that shopping cart is only intended to be an in-memory implementation that does not need to survive a server crash. In reality, however, most implementations of shopping carts are required to survive server crashes; the data contained within the shopping cart needs to be persistent and transactional -- with an in-memory data cache.Developers may be confused because if you read the EJB specification incorrectly it could be interpreted as saying all shopping cart implementations can be implemented with SFSBs. That simply isn't true. All in-memory shopping cart implementations can be implemented with SFSBs, but if you need to implement a persistent, crash-friendly shopping cart, you need to use entity EJBs.SFSBs are not distributed data stores. Yes, many application servers provide SFSB replication of state to allow for failover of requests to provide a higher level of availability. SFSB replication is just that: a replication mechanism to resist failures of instances on a single machine. SFSB replication is not designed to resist cluster-wide failures nor is it designed to cache data across an entire cluster. If a cluster has SFSB replication and all of the servers hosting a particular SFSB crash, that SFSB is permanently lost. This will happen, even if there are other servers that are still active. This is perfectly acceptable and should be accounted for when using SFSBs. If an SFSB is only used as a session-oriented component, the worst-case scenario that occurs is that the sequence is restarted from scratch when all copies of a particular SFSB are destroyed.When SFSBs should be used in non-web systemsFor systems that do not have a servlet/JSP front-end, SFSBs should be used to track session-oriented state similar to the way a web-based system would use an HttpSession object. This was the primary intent of SFSBs when they were created.When SFSBs should be used in web systemsSystems that have JSP/servlet front-ends should use HttpSession objects to store session-oriented state on behalf of a client. Applications that manage an HttpSession object and an SFSB for a single client wind up duplicating effort that does not need to be duplicated. There are two reasons to use an SFSB in conjunction with an HttpSession object:Your application server does not provide cache management of HttpSession instances and your system is expected to have a large number of concurrent clients. Containers for SFSBs can activate and "passivate" the state of instances to and from a secondary store. This allows a container to create an upper limit to the number of instances that will exist in memory at any given point in time. The number of concurrent clients can exceed the limit of SFSB instances in memory because the container can swap idle instances to and from the secondary store. The container will never allow more than the limit of SFSB instances to exist in memory, subsequently placing all additional instances into the secondary store. This provides a greater level of scalability to the system through effective memory management.Many application servers provide similar cache management of HttpSession objects. Because HttpSession objects are similar to SFSBs, they can also be made passive and active. Cache management behavior of HttpSession objects is not required as part of J2EE and is considered a vendor value-add. If your application server does not support HttpSession cache management -- and you need to control the total number of session-oriented instances in memory at any given time -- you should place the bulk of your session-oriented data in an SFSB instead of an HttpSession object. You will still need to maintain an HttpSession for each client, but the only item in the HttpSession should be a reference to the SFSB for that client. If the only item in the HttpSession object is a reference to the SFSB, the amount of memory consumed by each HttpSession object is minimal and cache management of these instances is not needed. The bulk of memory consumption will occur within the SFSBs, which have a standardized strategy for allowing a container to perform cache management.Your session-oriented objects need to receive notifications on the lifecycle of the transactions they participate in. SFSBs can implement the SessionSynchronization interface. The SessionSynchronization interface contains three methods that a container invokes as a transaction migrates through the lifecycle the SFSB is participating in. An SFSB might implement the SessionSynchronization interface as a way to return the data of the SFSB to its original state whenever there is a transaction rollback. HttpSession instances do not have a mechanism that allows them to receive transaction notifications. This means that any data that is modified in an HttpSession during a transaction will not be reverted if the current transaction is rolled back. All changes to data in an HttpSession object are always durable despite the outcome of any executing transactions. If this behavior is not appropriate for your system, placing all data into an SFSB instance that implements SessionSynchronization will give you the appropriate behavior.

What is Aspect-oriented programming?

Aspect-oriented programming (AOP) is a programming paradigm that increases modularity by allowing the separation of cross-cutting concerns.Separation of concerns entails breaking down a program into distinct parts (so-called concerns, cohesive areas of functionality). All programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing new abstractions (e.g. procedures, modules, classes, methods) that can be used to represent these concerns. But some concerns defy these forms of encapsulation and are called crosscutting concerns because they "cut across" multiple abstractions in a program.Logging an the archetypal example of a crosscutting concern because a logging strategy necessarily affects every single logged part of the system. Logging thereby crosscuts all logged classes and methods.All AOP implementations have some crosscutting expressions that encapsulate each concern in one place. The difference between implementations lies in the power, safety, and usability of the constructs provided. For example, interceptors that specify the methods to intercept express a limited form of crosscutting, without much support for type-safety or debugging. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter the behavior of the base code (the non-aspect part of a program) by applying advice (additional behavior) at various join points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches). An aspect can also make binary-compatible structural changes to other classes, like adding members or parents.

Garbage collection Performance Considerations

There are two primary measures of garbage collection performance. Throughput is the percentage of total time not spent in garbage collection, considered over long periods of time. Throughput includes time spent in allocation (but tuning for speed of allocation is generally not needed.) Pauses are the times when an application appears unresponsive because garbage collection is occurring. Users have different requirements of garbage collection. For example, some consider the right metric for a web server to be throughput, since pauses during garbage collection may be tolerable, or simply obscured by network latencies. However, in an interactive graphics program even short pauses may negatively affect the user experience. Some users are sensitive to other considerations. Footprint is the working set of a process, measured in pages and cache lines. On systems with limited physical memory or many processes, footprint may dictate scalability. Promptness is the time between when an object becomes dead and when the memory becomes available, an important consideration for distributed systems, including remote method invocation (RMI). In general, a particular generation sizing chooses a trade-off between these considerations. For example, a very large young generation may maximize throughput, but does so at the expense of footprint, promptness, and pause times. young generation pauses can be minimized by using a small young generation at the expense of throughput. To a first approximation, the sizing of one generation does not affect the collection frequency and pause times for another generation.There is no one right way to size generations. The best choice is determined by the way the application uses memory as well as user requirements. For this reason the virtual machine's default garbage collectior may not be optimal, and may be overridden by the user in the form of command line options, described below.

Garbage collections Introduction

IntroductionThe Java 2 Platform, Standard Edition (J2SE platform) is used for a wide variety of applications from small applets on desktops to web services on large servers. In the J2SE platform version 1.4.1 two new garbage collectors were introduced to make a total of four garbage collectors from which to choose. How should that choice be made and what are the consequences of that choice? This document will describe some of the general features shared by all the garbage collectors. It will then discuss tuning options to take the best advantage of those features in the context of the default single-threaded, stop-the-world collector. Finally, it will discuss the specific features of the three other collectors, and discuss the criteria for choosing one of the four collectors.When does garbage collection performance matter to the user? For many applications it doesn't. That is, the application can perform within its specifications in the presence of garbage collection with pauses of modest frequency and duration. An example where this is not the case (when the default collector is used) would be a large application that scales well to large number of threads, processors, sockets, and a large amount of memory.Amdahl observed that most workloads cannot be perfectly parallelized; some portion is always sequential and does not benefit from parallelism. This is also true for the J2SE platform. In particular, virtual machines for the Java platform up to and including version 1.3.1 do not have parallel garbage collection, so the impact of garbage collection on a multiprocessor system grows relative to an otherwise parallel application.This shows that negligible speed issues when developing on small systems may become principal bottlenecks when scaling up to large systems. However, small improvements in reducing such a bottleneck can produce large gains in performance. For a sufficiently large system it becomes well worthwhile to tune the garbage collector.The default collector should be the first choice for garbage collection and will be adequate for the majority of applications. Each of the other collectors have some added overhead and/or complexity, which is the price for specialized behavior. If the application doesn't need the specialized behavior of the alternate collectors, use the default collector. The exception to this rule is large applications that are heavily threaded and run on hardware with a large amount of memory and a large number of processors. For such applications, first try the aggressive heap option (-XX:+AggressiveHeap) described below.This document was written using the J2SE platform, version 1.4.2, on the Solaris Operating Environment (SPARC Platform Edition) as the base platform, because it provides the most scalable hardware and software for the J2SE platform. However, the descriptive text applies to other supported platforms, including Linux, Microsoft Windows, and the Solaris Operating Environment (x86 Platform Edition), to the extent that scalable hardware is available. Although command line options are consistent across platforms, some platforms may have defaults different than those described here.