tag:blogger.com,1999:blog-368814982024-02-20T05:49:26.232-08:00Very Small Javasmalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.comBlogger19125tag:blogger.com,1999:blog-36881498.post-2136272658847526672010-01-06T12:04:00.000-08:002010-01-06T12:08:23.434-08:00Invoking a JSP error page from a servlet<pre><br /><br />protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws<br />ServletException, IOException {<br />try {<br /> //try block<br />}<br />catch(Exception ex) {<br /> req.setAttribute("javax.servlet.ex",ex);//store exception as request attribute.<br /> ServletConfig sConfig = getServletConfig();<br /> ServletContext sContext = sConfig.getServletContext();<br /> sContext.getRequestDispatcher("/jsp/ErrorPage.jsp").forward(req, resp);<br /><br /> /*request with the exception stored as an attribute forwaded to the "ErrorPage.jsp".<br /> */<br /> ex.printStackTrace();<br />}<br />}<br /></pre>krishnahttp://www.blogger.com/profile/17593541035941835521noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-39041814670489848612009-12-28T10:40:00.000-08:002009-12-28T10:50:13.315-08:00Using Closeable Interface<span style="font-family:Georgia;"></span><pre><br /> static void copy(String src, String dest) throws IOException {<br /> InputStream in = null;<br /> OutputStream out = null;<br /> try { <br /> in = new FileInputStream(src); <br /> out = new FileOutputStream(dest); <br /> byte[] buf = new byte[1024];<br /> int n;<br /> while ((n = in.read(buf)) >= 0)<br /> out.write(buf, 0, n);<br /> } finally {<br /> if (in != null) in.close();<br /> if (out != null) out.close();<br /> }<br /> }<br /><br /></pre><br /><br />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?<br /><br />Yes...<br />The problem resides in finally block<br />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.<br /><br />The solution would be to wrap each call to close in a nested try block<br /><pre><br />} finally {<br /><br /> if (in != null) {<br /><br /> try {<br /><br /> in.close();<br /><br /> } catch (IOException ex) {<br /><br /> // There is nothing we can do if close fails<br /><br /> }<br /><br /> }<br /><br /> <br /><br /> if (out != null) {<br /><br /> try {<br /><br /> out.close();<br /><br /> } catch (IOException ex) {<br /><br /> // Again, there is nothing we can do if close fails<br /><br /> }<br /><br /> }<br /><br />}<br /><br /></pre><br /><br /><strong>Closeable </strong>interface comes to your rescue, helping you to abstract it at one routine<br />like this<br /><pre><br /><br />} finally {<br /><br /> closeIgnoringException(in);<br /><br /> closeIgnoringException(out);<br /><br />}<br /><br /><br /><br />private static void closeIgnoringException(Closeable c) {<br /><br /> if (c != null) {<br /><br /> try {<br /><br /> c.close();<br /><br /> } catch (IOException ex) {<br /><br /> // ignore if you dont have any thing to do here<br /> }<br /><br /> }<br /><br />}<br /></pre><br /><br />And finally<br /><br /><em>A <strong>Closeable </strong>is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding.</em>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-30178896170140289202009-12-16T12:00:00.000-08:002009-12-16T12:01:33.052-08:00PermGen spaceThe memory in the Virtual Machine is divided into a number of regions. One of these regions is <strong>PermGen</strong>. 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: <em>-XX:MaxPermSize</em> . The default is 64 Mb on the Sun VMs.<br /><br />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 <em>-Xmx</em> parameter will not help: this parameter only specifies the size of the total heap and does not affect the size of the PermGen region.smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-24407846562822152382009-12-16T11:54:00.000-08:002009-12-16T11:56:01.032-08:00Free up log4j memory usage at context unloadpublic class ApplicationLifecycleListener implements ServletContextListener{<br /> public void contextDestroyed(final ServletContextEvent sce) {<br /> LogFactory.release(Thread.currentThread().getContextClassLoader());<br /> }<br /> public void contextInitialized(final ServletContextEvent sce)<br /> {}<br />}smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-57936191403780945082009-12-16T11:22:00.000-08:002009-12-16T11:24:49.053-08:00NIO- New I/OThe new I/O (NIO) classes added in Java 1.4 introduced a new way of performing I/O based on channels and buffers.<br />As well as I/O buffers backed by memory on the Java heap, NIO added support for <strong>direct</strong> ByteBuffers (allocated using the <strong>java.nio.ByteBuffer.allocateDirect()</strong> 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.<br />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:<br /><br /><br />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).<br />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.smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-84800863310367593482009-12-16T11:08:00.000-08:002009-12-16T11:10:43.224-08:00Semantic Versioning Specs1> 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.<br />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.<br /><br />3> When tagging releases in a version control system, the tag for a version MUST be "vX.Y.Z" e.g. "v3.1.0".<br />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.<br />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.<br />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.<br />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.<br />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.<br />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.smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-54554849872006237182008-05-06T11:42:00.002-07:002008-05-06T12:00:05.070-07:00Superpackages in Java 7Motivation of the change(Defects of Packages)<br />• Package names are hierarchical<br />• Package membership is not hierarchical<br />> A type defined in package P.Q is not in package P<br />• Package visibility is not hierarchical<br />> Code in P.Q cannot access package-visible members in P<br />• Result: Too much is declared public<br /><br /><br />Superpackages<br />• Aim: Language-level modules, independent of<br />deployment mechanism<br /><br /><strong>super package java {<br /><br />member java.util;<br />member java.io;<br />member sun misc; // Impl detail<br />export java.util.*;// Public API<br />export java.io.*;<br /><br />}</strong>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-62337880963256429142008-05-06T11:42:00.001-07:002008-05-06T11:54:00.510-07:00Java 7 FeaturesTentative JDK 7 Language Themes<br />• Modularity<br />> Packages++<br /><br /> • Abstraction<br />> Anonymous classes++<br /> <br />• Consistency<br />> Erase erasuresmalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-28688944317175668012008-05-06T11:42:00.000-07:002008-05-06T11:48:57.489-07:00Advantages to running applications on Java SE 61)Applications run faster on the desktop and servers <br />2)New 'Dynamic Attach' diagnostics simplify troubleshooting <br />3)Expanded Solaris DTrace support provides additional value on Solaris <br />4)Improved 'native' look and feel across Solaris, Linux, and Windows <br />5)First Java platform with full support for Windows Vista <br /><br /><strong>Benefits in upgrading developer environments to Sun's Java SE 6 </strong><br />1)JavaScript integrated and included with the platform <br />2)Scripting languages framework extends support for Ruby, Python, and other languages <br />3)Complete light-weight platform for web services, right out of the box <br />4)Simplified GUI design and expanded native platform support <br />5)Full JDBC4 implementation providing improved XML support for Databases <br />6)Java DB included with the JDK, a free to use and deploy Java Database <br />7)Full support by NetBeans IDE 5.5 <br /><br />--------------------------------------------------------------------------------smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-44349315319171960412007-01-17T03:39:00.000-08:002007-01-17T04:27:00.497-08:00What's so special about Java 'Mustang' ?Sun Microsystems latest Java version is JSE6 (Java Platform, Standard Edition 6), code named "Project Mustang." <br /><br />Features:<br /> Expanded scripting language and Web services support:<br /> Java SE 6 software is clearly emerging as the next-generation platform for Web 2.0 applications and services.<br /> 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.<br /><br />The new JavaScript engine and javax.script API are based on the Mozilla Foundation's open-source Rhino implementation of JavaScript. <br /><br />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). <br /><br />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.smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-36149116047362889052007-01-17T03:30:00.000-08:002007-01-17T03:33:19.715-08:00Knowing Java Release Code Names-------------------------------------------------------------------------<br /><br />Java 5 Tiger<br />Java 6 Mustang<br />Java 7 Dolphin<br /><br />--------------------------------------------------------------------------smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-30187212365895794802007-01-10T00:23:00.000-08:002007-01-10T00:49:09.235-08:00Adding Plugins to a Java ApplicationJust comming ----smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-79755191696862192452006-11-27T03:25:00.000-08:002006-11-27T04:21:24.168-08:00Listing the File System RootsUNIX file systems have a single root, `<code>/</code>'. On Windows, each drive is a root. For example the C drive is represented by the root <code>C:\</code>.<br /><br /> <br /> File[] filerots = File.listRoots();<br /> for (int i=0; i <code>< </code> filerots.length; i++) {<br /> process(roots[i]);<br /> }smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-19482035374523946132006-11-27T03:15:00.000-08:002006-11-27T03:16:58.618-08:00Catching all Errors and ExceptionsAll errors and exceptions extend from <code>Throwable</code>. By catching <code>Throwable</code>, it is possible to handle all unexpected conditions.<br /><br />There are several scenarios where it is good practice to catch <code>Throwable</code>. For example, in a server application, the threads that handle requests should catch <code>Throwable</code> 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 <code>Throwable</code>, log any errors or exceptions, and then continue functioning.<br /><br />It is rarely good practice for a method in a library to catch <code>Throwable</code>. In general, errors and exceptions should not be masked from the caller.<br /><br />This example demonstrates a long-running thread that catches <code>Throwable</code> and logs the exception.<br /><br /><pre> class BgThread extends Thread {<br /> // Create a logger. For more information on the logging api's,<br /> Logger logger = Logger.getLogger(<span style="color:#0066ff;"><i>"com.mycompany.mypackage"</i></span>);<br /> <br /> BgThread() {<br /> // As a daemon thread, this thread won't prevent the application from exiting<br /> setDaemon(true);<br /> }<br /> <br /> // Set to true to shut down this thread<br /> boolean stop = false;<br /> <br /> public void run() {<br /> while (!stop) {<br /> try {<br /> // Perform work here<br /> } catch (Throwable t) {<br /> // Log the exception and continue<br /> logger.log(Level.SEVERE, "Unexception exception", t);<br /> }<br /> }<br /> }<br /> }<br /></pre>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-23148631560332725622006-11-27T02:07:00.000-08:002006-11-27T02:09:15.344-08:00Finding When your Application Is About to ExitWhen an application is terminated normally, the application first starts any registered <span style="color:#0066ff;"><i>shutdown threads</i></span>, waits for them to complete and then finally exits. <br /><br />Normal termination can be caused by a call to <code>System.exit()</code>, the completion of the last non-daemon thread, or the interruption of the application (control-C) by the user.<br /><br /> 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.<br /><br /><pre> // Register a shutdown thread<br /> Runtime.getRuntime().addShutdownHook(new Thread() {<br /> // This method is called during shutdown<br /> public void run() {<br /> // Do shutdown work ...<br /> }<br /> });</pre>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-8720288158854444922006-11-27T02:05:00.000-08:002006-11-27T02:06:25.513-08:00Loading Native Code<pre><br />On Windows, <code>loadLibrary("s")</code> loads <code>s.dll</code>. On Solaris, it loads<br /><code>s.so</code>.<br /><br /><br />System.loadLibrary(<span style="color:#0066ff;"><i>"libraryName"</i></span>);</pre>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-176069279305889622006-11-23T03:35:00.000-08:002006-11-23T03:42:11.137-08:00Creating a ThreadWhen a thread is created, it must be permanently bound to an object with a <code>run()</code> method. When the thread is started, it will invoke the object's <code>run()</code> method.<br /><br />There are two ways to create a thread.<br /><br /> The first is to declare a class that extends <code>Thread</code>. When the class is instantiated, the thread and object are created together and the object is automatically bound to the thread. By calling the object's <code>start()</code> method, the thread is started and immediately calls the object's <code>run()</code> method. Here is some code to demonstrate this method.<br /><pre> // This class extends Thread<br /> class <span style="color:#0066ff;"><i>BasicThread1</i></span> extends Thread {<br /> // This method is called when the thread runs<br /> public void run() {<br /> }<br /> }<br /></pre> <pre> // Create and start the thread<br /> Thread thread = new <span style="color:#0066ff;"><i>BasicThread1</i></span>();<br /> thread.start();<br /></pre><br />The second way is to create the thread and supply it an object with a <code>run()</code> method.<br />This object will be permanently associated with the thread. The object's <code>run()</code> method will be invoked when the thread is started.<br /> This method of thread creation is useful if you want many threads sharing an object.<br /> Here is an example that creates a <code>Runnable</code> object and then creates a thread with the object.<br /><br /><pre> class <span style="color:#0066ff;"><i>BasicThread2</i></span> implements Runnable {<br /> // This method is called when the thread runs<br /> public void run() {<br /> }<br /> }<br /></pre> <pre> // Create the object with the run() method<br /> Runnable runnable = new <span style="color:#0066ff;"><i>BasicThread2()</i></span>;<br /> <br /> // Create the thread supplying it with the runnable object<br /> Thread thread = new Thread(runnable);<br /> <br /> // Start the thread<br /><br /><br /> thread.start();<br /></pre>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-1162284043213407522006-10-31T00:29:00.000-08:002006-10-31T00:54:11.436-08:00The Java Virtual Machine HistoryThe <span style="font-weight: bold;">Java virtual machine</span> is the cornerstone of the Java and Java 2 platforms. It is the component of the technology responsible for its hardware- and operating system- independence, the small size of its compiled code, and its ability to protect users from malicious programs.<br /><br />The<span style="font-weight: bold;"> Java virtual machine</span> is an abstract computing machine. Like a real computing machine, it has an instruction set and manipulates various memory areas at run time. It is reasonably common to implement a programming language using a virtual machine; the best-known virtual machine may be the P-Code machine of UCSD Pascal.<br /><br />The first prototype implementation of the Java virtual machine, done at Sun Microsystems, Inc., emulated the Java virtual machine instruction set in software hosted by a handheld device that resembled a contemporary Personal Digital Assistant (PDA). Sun's current Java virtual machine implementations, components of its Java<sup><span style="">TM</span></sup> 2 SDK and Java<sup><span style="">TM</span></sup> 2 Runtime Environment products, emulate the Java virtual machine on Win32 and Solaris hosts in much more sophisticated ways. However, the Java virtual machine does not assume any particular implementation technology, host hardware, or host operating system. It is not inherently interpreted, but can just as well be implemented by compiling its instruction set to that of a silicon CPU. It may also be implemented in microcode or directly in silicon.<br /><br />The Java virtual machine knows nothing of the Java programming language, only of a particular binary format, the <code>class</code> file format. A <code>class</code> file contains Java virtual machine instructions (or <i>bytecodes</i>) and a symbol table, as well as other ancillary information.<br /><br />For the sake of security, the Java virtual machine imposes strong format and structural constraints on the code in a <code>class</code> file. However, any language with functionality that can be expressed in terms of a valid <code>class</code> file can be hosted by the Java virtual machine. Attracted by a generally available, machine-independent platform, implementors of other languages are turning to the Java virtual machine as a delivery vehicle for their languages.<br /><br />Taken From: http://java.sun.com/docs/books/vmspecsmalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0tag:blogger.com,1999:blog-36881498.post-1162282574584317982006-10-31T00:13:00.000-08:002006-10-31T00:16:14.590-08:00How to get Java Memory Heap Size// Get current size of heap in bytes <br /><br /><span style="font-weight: bold;">long heapSize = Runtime.getRuntime().totalMemory();</span><br /><br /> // Get maximum size of heap in bytes. The heap cannot grow beyond this size.<br /> // Any attempt will result in an OutOfMemoryException.<br /><br /><span style="font-weight: bold;">long heapMaxSize = Runtime.getRuntime().maxMemory(); </span><br /><br />// Get amount of free memory within the heap in bytes. This size will increase<br /> // after garbage collection and decrease as new objects are created.<br /><br /><span style="font-weight: bold;"> long heapFreeSize = Runtime.getRuntime().freeMemory(); <br /><br /><br /></span>smalljavahttp://www.blogger.com/profile/09094882320546560978noreply@blogger.com0