Friday 29 July 2011

Java application manipulates

The typical Java application manipulates several types of resources such as files, streams, sockets, and database connections. Such resources must be handled with great care, because they acquire system resources for their operations. Thus, you need to ensure that they get freed even in case of errors. Indeed, incorrect resource management is a common source of failures in production applications, with the usual pitfalls being database connections and file descriptors remaining opened after an exception has occurred somewhere else in the code. This leads to application servers being frequently restarted when resource exhaustion occurs, because operating systems and server applications generally have an upper-bound limit for resources.

Correct practices for the management of resources and exceptions in Java have been well documented. For any resource that was successfully initialized, a corresponding invocation to its close() method is required. This requires disciplined usage of try/catch/finally blocks to ensure that any execution path from a resource opening eventually reaches a call to a method that closes it. Static analysis tools, such as FindBugs, are of great help in identifying such type of errors. Yet often, both inexperienced and experienced developers get resource management code wrong, resulting at best in resource leaks.

However, it should be acknowledged that writing correct code for resources requires lots of boilerplate code in the form of nested try/catch/finally blocks, as we will see. Writing such code correctly quickly becomes a problem of its own. Meanwhile, other programming languages, such as Python and Ruby, have been offering language-level facilities known as automatic resource management to address this issue.

This article presents the Java Platform, Standard Edition (Java SE) 7 answer to the automatic resource management problem in the form of a new language construct proposed as part of Project Coin and called the try-with-resources statement. As we will see, it goes well beyond being just more syntactic sugar, like the enhanced for loops of Java SE 5. Indeed, exceptions can mask each other, making the identification of root problem causes sometimes hard to debug.

The article starts with an overview of resource and exception management before introducing the essentials of the try-with-resources statement from the Java developer point of view. It then shows how a class can be made ready for supporting such statements. Next, it discusses the issues of exception masking and how Java SE 7 evolved to fix them. Finally, it demystifies the syntactic sugar behind the language extension and provides a discussion and a conclusion.

Note: The source code for the examples described in this article can be downloaded here: sources.zip



DIL SE


This is Sandeeep
HI guys how r u,