Wednesday, January 06, 2010

Invoking a JSP error page from a servlet



protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
try {
//try block
}
catch(Exception ex) {
req.setAttribute("javax.servlet.ex",ex);//store exception as request attribute.
ServletConfig sConfig = getServletConfig();
ServletContext sContext = sConfig.getServletContext();
sContext.getRequestDispatcher("/jsp/ErrorPage.jsp").forward(req, resp);

/*request with the exception stored as an attribute forwaded to the "ErrorPage.jsp".
*/
ex.printStackTrace();
}
}

Monday, December 28, 2009

Using Closeable Interface


static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}



The stream fields (in and out) are initialized to null and set to the new streams as soon as they are created. The finally block closes the stream referred to by each field if it is non-null. An error during the copy would cause an IOException, but the finally block would still execute before the method returns. What could go wrong?

Yes...
The problem resides in finally block
The close method can throw an IOException too. If this happens when in.close is called, the exception prevents out.close from getting called, and the output stream remains open.

The solution would be to wrap each call to close in a nested try block

} finally {

if (in != null) {

try {

in.close();

} catch (IOException ex) {

// There is nothing we can do if close fails

}

}



if (out != null) {

try {

out.close();

} catch (IOException ex) {

// Again, there is nothing we can do if close fails

}

}

}



Closeable interface comes to your rescue, helping you to abstract it at one routine
like this


} finally {

closeIgnoringException(in);

closeIgnoringException(out);

}



private static void closeIgnoringException(Closeable c) {

if (c != null) {

try {

c.close();

} catch (IOException ex) {

// ignore if you dont have any thing to do here
}

}

}


And finally

A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding.

Wednesday, December 16, 2009

PermGen space

The memory in the Virtual Machine is divided into a number of regions. One of these regions is PermGen. It's an area of memory that is used to (among other things) load class files. The size of this memory region is fixed, i.e. it does not change when the VM is running. You can specify the size of this region with a commandline switch: -XX:MaxPermSize . The default is 64 Mb on the Sun VMs.

If there's a problem with garbage collecting classes and if you keep loading new classes, the VM will run out of space in that memory region, even if there's plenty of memory available on the heap. Setting the -Xmx parameter will not help: this parameter only specifies the size of the total heap and does not affect the size of the PermGen region.

Free up log4j memory usage at context unload

public class ApplicationLifecycleListener implements ServletContextListener{
public void contextDestroyed(final ServletContextEvent sce) {
LogFactory.release(Thread.currentThread().getContextClassLoader());
}
public void contextInitialized(final ServletContextEvent sce)
{}
}

NIO- New I/O

The new I/O (NIO) classes added in Java 1.4 introduced a new way of performing I/O based on channels and buffers.
As well as I/O buffers backed by memory on the Java heap, NIO added support for direct ByteBuffers (allocated using the java.nio.ByteBuffer.allocateDirect() method) that are backed by native memory rather than Java heap. DirectByteBuffers can be passed directly to native OS library functions for performing I/O — making them significantly faster in some scenarios because they can avoid copying data between Java heap and native heap.
It's easy to become confused about where direct ByteBuffer data is being stored. The application still uses an object on the Java heap to orchestrate I/O operations, but the buffer that holds the data is held in native memory — the Java heap object only contains a reference to the native heap buffer. A non-direct ByteBuffer holds its data in a byte[] array on the Java heap. Figure 4 shows the difference between direct and non-direct ByteBuffer objects:


Direct ByteBuffer objects clean up their native buffers automatically but can only do so as part of Java heap GC — so they do not automatically respond to pressure on the native heap. GC occurs only when the Java heap becomes so full it can't service a heap-allocation request or if the Java application explicitly requests it (not recommended because it causes performance problems).
The pathological case would be that the native heap becomes full and one or more direct ByteBuffers are eligible for GC (and could be freed to make some space on the native heap), but the Java heap is mostly empty so GC doesn't occur.

Semantic Versioning Specs

1> Software using Semantic Versioning must declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it should be precise and comprehensive.
2> A version number takes the form X.Y.Z where X, Y, and Z are integers. X is the major version, Y is the minor version, and Z is the patch version. Each element increases numerically such that version 1.0.10 follows 1.0.9.

3> When tagging releases in a version control system, the tag for a version MUST be "vX.Y.Z" e.g. "v3.1.0".
4> Once a versioned package has been released, the contents of that version MUST never be modified. Any modifications MUST be released as a new version.
5> Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable.
6> Version 1.0.0 defines the public API. The way in which the version number is incremented is now dependent on this public API and how it changes.
7> Patch version Z (x.y.Z x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.
8> Minor version Y (x.Y.z x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes.
9> Major version X (X.y.z X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. It MAY include minor and patch level changes.

Tuesday, May 06, 2008

Superpackages in Java 7

Motivation of the change(Defects of Packages)
• Package names are hierarchical
• Package membership is not hierarchical
> A type defined in package P.Q is not in package P
• Package visibility is not hierarchical
> Code in P.Q cannot access package-visible members in P
• Result: Too much is declared public


Superpackages
• Aim: Language-level modules, independent of
deployment mechanism

super package java {

member java.util;
member java.io;
member sun misc; // Impl detail
export java.util.*;// Public API
export java.io.*;

}

Java 7 Features

Tentative JDK 7 Language Themes
• Modularity
> Packages++

• Abstraction
> Anonymous classes++

• Consistency
> Erase erasure

Advantages to running applications on Java SE 6

1)Applications run faster on the desktop and servers
2)New 'Dynamic Attach' diagnostics simplify troubleshooting
3)Expanded Solaris DTrace support provides additional value on Solaris
4)Improved 'native' look and feel across Solaris, Linux, and Windows
5)First Java platform with full support for Windows Vista

Benefits in upgrading developer environments to Sun's Java SE 6
1)JavaScript integrated and included with the platform
2)Scripting languages framework extends support for Ruby, Python, and other languages
3)Complete light-weight platform for web services, right out of the box
4)Simplified GUI design and expanded native platform support
5)Full JDBC4 implementation providing improved XML support for Databases
6)Java DB included with the JDK, a free to use and deploy Java Database
7)Full support by NetBeans IDE 5.5

--------------------------------------------------------------------------------

Wednesday, January 17, 2007

What's so special about Java 'Mustang' ?

Sun Microsystems latest Java version is JSE6 (Java Platform, Standard Edition 6), code named "Project Mustang."

Features:
Expanded scripting language and Web services support:
Java SE 6 software is clearly emerging as the next-generation platform for Web 2.0 applications and services.
JSE6 software includes a new framework for scripting languages, such as PHP and JavaScript technology, which should make JSE easier to use with those languages.

The new JavaScript engine and javax.script API are based on the Mozilla Foundation's open-source Rhino implementation of JavaScript.

The new JSE6 also provides expanded tools for diagnosing, managing and monitoring applications. This includes better support for Sun's DTrace, open-source dynamic tracing framework for Solaris, and tool interface updates for JVMs (Java virtual machine) and the JDBA (Java Platform Debugger Architecture).

Sun has also tried to improve JSE's integration with the desktop in this edition. The company claims that with tighter integration with native desktop facilities, Java applications will be better able to emulate native platform look and feel, text printing, drag-and-drop capabilities and table display and manipulation.

Knowing Java Release Code Names

-------------------------------------------------------------------------

Java 5 Tiger
Java 6 Mustang
Java 7 Dolphin

--------------------------------------------------------------------------

Wednesday, January 10, 2007

Monday, November 27, 2006

Listing the File System Roots

UNIX file systems have a single root, `/'. On Windows, each drive is a root. For example the C drive is represented by the root C:\.


File[] filerots = File.listRoots();
for (int i=0; i < filerots.length; i++) {
process(roots[i]);
}

Catching all Errors and Exceptions

All errors and exceptions extend from Throwable. By catching Throwable, it is possible to handle all unexpected conditions.

There are several scenarios where it is good practice to catch Throwable. For example, in a server application, the threads that handle requests should catch Throwable and relay any errors or exceptions to the client. Another scenario is a long-running thread that performs some background activity. Such threads should catch Throwable, log any errors or exceptions, and then continue functioning.

It is rarely good practice for a method in a library to catch Throwable. In general, errors and exceptions should not be masked from the caller.

This example demonstrates a long-running thread that catches Throwable and logs the exception.

    class BgThread extends Thread {
// Create a logger. For more information on the logging api's,
Logger logger = Logger.getLogger("com.mycompany.mypackage");

BgThread() {
// As a daemon thread, this thread won't prevent the application from exiting
setDaemon(true);
}

// Set to true to shut down this thread
boolean stop = false;

public void run() {
while (!stop) {
try {
// Perform work here
} catch (Throwable t) {
// Log the exception and continue
logger.log(Level.SEVERE, "Unexception exception", t);
}
}
}
}

Finding When your Application Is About to Exit

When an application is terminated normally, the application first starts any registered shutdown threads, waits for them to complete and then finally exits.

Normal termination can be caused by a call to System.exit(), the completion of the last non-daemon thread, or the interruption of the application (control-C) by the user.

Abnormal termination (which does not cause the shutdown threads to be started) is caused some major fault in the Java virtual machine or native library.

    // Register a shutdown thread
Runtime.getRuntime().addShutdownHook(new Thread() {
// This method is called during shutdown
public void run() {
// Do shutdown work ...
}
});

Loading Native Code


On Windows, loadLibrary("s") loads s.dll. On Solaris, it loads
s.so.


System.loadLibrary("libraryName");