Conditional compilation & Conditional loading/initialization of a class
How can one conditionally compile some code in a class?
It's very simple. One possible way is to use a static final boolean variable and assign that variable a value 'false' during declaration. Since it's a final variable, so the compiler knows that the value is not going to change any further. Since the variable is static, so the compiler knows that the variable is a class variable and will remain the same for all the instances.
Now, if we put some code inside a block which tests the value of the static final variable in a conditional statement then the compiler is wise enough to know that the part included inside the conditional statement will never be executed and hence it'll not compile that at all.
Similarly, we may use any such condition which will invariably be false at compile time (or true in which case we may use '!' operator before that expression to convert that into false) to conditionally compile a set of statements put inside a block having that expression as its condition expression. The bottom line is that a Java compiler will NOT compile a block of code which won't be executed.
Unreachable Code vs Non-Compiled Code
Unreachable Code and Non-Compiled Code are completely different. The former results in a compile time error whereas the latter refers to a block of code which is not compiled, but the compilation of the program completes successfully. Don't mix both. Unreachable code refers to a block of code where the control can never reach during execution. For example:- if you write something after an infinite loop then that block will be unreachable as the runtime system will keep running the infinite loop until the stack overflows (or JVM process is terminated by some external interruption). So, Unreachable code is supposed to be a flaw in the program whereas Non-compiled code is something which is not required in the present scenario and hence won't be compiled. So it's kind of compile time optimization.
Example: conditional compilation of a block of code
package test;
public class TestCondCompilation {
public static void main(String[] args) {
TestCondCompilation testCondCompilation = new TestCondCompilatio();
(new CondCompilation()).testMethod();
}
}
class CondCompilation{
public static final boolean COND_COMPILATION = false;
public void testMethod(){
if(COND_COMPILATION){
System.out.println("Never Compiled unless value of COND_COMPILATION is set to true");
}
System.out.println("Compiled");
}
Output:-
Compiled
The above approach can be used to conditionally compile the assertion code in Java. Read more about assertions in this article - Assertions? Assertions vs Exception, Usage, etc. >>. So, this approach can be used effectively to reduce the size of the .class files (by not allowing compilation of assertion code) in case the size is so critical.
Conditional Loading/Initialization of a Class
We can use assertions to implement conditional loading/initialization of class. As we know that assertions can either be enabled or disabled (by default they are disabled), hence we can use that information effectively to achieve this objective.
Example: one popular example of conditional loading/initialization of a class using assertions
class SomeClass{
static{
boolean isAssertionEnabled = false;
assert isAssertionEnabled = true;
if (!isAssertionEnabled)
throw new AssertionError("Class not Loaded as Assertion NOT Enabled!");
}
...
...
}
In the above class we have a static initializer which gets executed first while loading of the class. It first sets a boolean variable isAssertionEnabled to false. The second line simply uses the assert statement which sets the same boolean variable to true. Since, this is an assert statement hence it'll be executed only if the assertion is enabled. So, the boolean variable will continue to have the same value 'false' in case assertion is not enabled. Now, the next if statement checks the value of the boolean variable isAssertionEnabled and it throws an AssertionError object in case the value of the boolean variable is still false (which will be the case only if the assertion is not enabled).
Notice that we can't have an assert statement in place of the 'throw new AssertionError()' as the assert will not be executed in case the assertion is not enabled and if it's enabled then the if statement condition will return false and thus the class will be loaded irrespective of whether assertion is enabled or not. So, it's mandatory to throw AssertionError eplicitily. Of course, we can throw some other Unchecked Exception (like RuntimeException) as well. Can you throw a checked exception like IOException here? Think about it. Not a difficult question ... right?
Saturday, June 28, 2008
Conditional compilation & Conditional loading of a class
Asserions in Java? Assertions vs Exception? Its usage?
Asserions in Java? Assertions vs Exception? Where to Use & Where NOT?
Assertion in Java
An assertion is a special statement which contains one boolean expression and if that boolean expression returns 'false' then the program throws an AssertionError which is an unchecked exception and it normally terminates the current program/application.
This boolean expression is normally used to verify our assumptions which we used while designing our application. Thus, assertions can be used to write correct programs i.e., the programs which run in accordance with their specifications. Assertions can be easily enabled or disabled (by defauly they are disabled) and this greatly helps improving the maintainability of the application.
An assertion statement can have two forms in Java:-
Where assertions should NOT be used?
Assertions should never be a part of the implementation of some functionality of the application. They should only be used to verify the assumptions - just to be sure that whatever we assumed while desinging the solution is actually valid in practical as well. Below are few situations where you may get tempted to use assertions, but you should NOT use them:-
Where to use Assertions?
As we know that assertions should be used to test the assumptions so that we can guarantee a correct program. Hence, they should be used at the places where the execution assumes something and proceeds accordingly. Few of such scenarios are:-
Assertion vs Exception
We just discussed that assertions should be used to verify the assumptions so that we can guarantee that the application always executes complying with the specifications. Thus we see that assertion is basically a mechanism which helps us writing correct programs. Whereas Exception is a mechanism of checking if the implementation is executing without any expected or unexpected errors or not. So, we see that exceptions are basically used for handling even the unforseen conditions during the execution of an application in a better way and hence using exceptions effectively results into a robust application.
Just visualize the difference between something being correct and something being robust. 'correct' obviously means that whenever the application runs, it runs correctly in accordance with specs whereas 'robust' means whenever the application encounters an error condition either expected in case of checked expection OR unexpected in case of unchecked exceptions, it always handles the execution in a controlled way - either by ignroing the exception or by handling the exception (maybe by saving the state and terminating gracefully).
Therefore, we see that assertions and exceptions are not rivals. In fact they are complimentary to each other and an effective combination of both can ensure the development of a correct and robust application.
Free 2/3-column XML Skins/Templates for Blogger
Free 2-column/3-column XML Skins/Templates for Blogger
Download & Apply the theme used by this blog
After emailing the XML skin of my blog quite a few times, I thought it would be better to share it on the blog itself so that people interested in it can download it directly from here instead of requesting that via email.
Credits for the XML theme that this blog uses
As you can see from the 'Credits' section of the blog that the main credit of this template goes to Charm Skins and Blogger. I thank all those who're directly or indirectly involved in the design and development of the base template. I just modified it a bit to suit my needs. Similarly, you may also change it as per your requirements. Let me know in case you get any errors while modifying the skin. I will try to rectify them. You probably won't need any help as modifying an XML skin is quite easy in most of the cases.
Structure of this XML Skin
This XML Blogger template can be categorized into four main areas, which are:-
Charm Skins has made this skin especially for using Google AdSense advertising on it. Simple HTML/JavaScript elements can be added to put Google AdSense Ad codes in the side-bar region. The side bar section can be further divided into two sections (as you can see on my blog where the top portion is a single wide column whereas the bottom is composed of two columns). Based on whether you want to put the Google AdSense Ad code in the one-column section section of the sidebar-region OR in the tw-column section of the sidebar-region, you may choose AdSense Ads of sizes 336X280 (large rectangle) and 160x600 (skyscraper) respectively. Of course, you may put Ads of other sizes as well, but this template looks to be optimized for these two sizes.
In addition, you may put a large rectangle Ad in the beginning of the post (what I've on my blog) and also horizontal Ad Links can follow that Ad rectangle. Don't know how to insert Ad in the post body? Read this article - Inserting AdSense Ads in post body >>
How can use this XML Blogger Template for your site/blog?
Caution: applying a new template will not cause any loss to your posted articles, but if your blog has some other custom Javascript elements added then you will lose them. If you've a long running blog/site then please don't rush into applying a new template. It's always better to choose the right templete in the beginning itself and afterwards modifying the existing one is probably a better approach unless you're too adventurous.
Not comfortable with applying a new XML theme? It's a very easy process involving three simple steps. Find below the steps (click the image to open it in a new tab):-
Find below links to download more blogger themes from CharmSkins. You can modify them as per your needs.
Tech Blogger XML Skin/Template - very similar to the above one
Inserting AdSense Ads in Post Body, Sidebar, etc..
Inserting Google AdSense Ads in Post Body, Sidebar, Footer, etc.
Inserting Google AdSense Ads to Post Body
Find below few simple steps to insert Google AdSense Ads in the post body. You just need to parse your AdSense Ad code before inserting it into the template. If you don't have a HTML parser then use this Online HTML Parser.
Once you have got the parsed HTML AdSense Ad code, follow the below steps to find the particular places in the template code to insert your parsed Ad code:-
Not all of my Google AdSense are being displayed - why?
You would definitely be knowing that at the max you can have 3 content AdSense Ads and 3 link AdSense Ads being displayed on any web page. So, based on your configuration of the maximum number of posts being displayed on your home page, you may not see Google AdSense Ads embedded in all the displayed articles on the home page. Remember, post-body Ads normally take higher precedence than those configured to be shown in the Sidebar-region OR footer-region… probably because the page is rendered in that order – first header, then body and then sidebar/footer. Google AdSense Ads will of course be displayed in that order only and hence Header (I assume you’ve not added 3 content and/or 3 link Ads in this section itself) and Body Ads may cause Sidebar Ads NOT to be displayed for home page (or for any other page based on how many Ads have you added to these sections).
Adding Google AdSense Ads to Sidebar region OR Footer region
It's very easy. Just click 'Add a Page Element' in the respective regions and Select HTML/Javascript element. Put your Google AdSense Ad code in the body of the element. Save and you're done! You don't even need to parse your AdSense Ad code in this case as the element type allows you to have HTML and/or Javascript code.
Just click the link 'Add a Page Element' in the section you want your AdSense Ad to be displayed.
Adding Google AdSense Ads to the Header region
You may follow the same steps as you did for inserting AdSense Ads in the Post body. This time you need to locate the element which renders the Header (the way you located the element which renders body of the articles for inserting Ads to Body). I personally didn't like having any Header Ad for my existing template.
Wednesday, June 25, 2008
Do Interfaces really inherit the Object class in Java?
Do Interfaces really inherit the class Object in Java (the cosmic sperclass)?
Well... the answer is NO. An interface can't inherit from a class in Java, not at least directly. So, we can safely say that interfaces don't inherit from the Object class. Okay... so how can they do that indirectly? We know that interfaces can have classes declared as members as well just like they can have constants. Such a class is called a member class and like constants all the member classes of an interface would be static and public. And that static member class (like any other class in java) inherits Object class.
But, how are we able to compile code having Object method calls on the references of an interface type in Java? We all know that the object of the implementing class (and hence its type) will be assigned to only at run time and we can compile a code only if the compiler finds a method of that signature in the declared type (either declared directly or inherited from superclasses). This is absolutely correct for classes in Java, but only partially correct for interfaces in Java. Surprised? Let's try to understand what internally happens in case of interfaces.
Is this Inheritance of Object methods by the Interfaces?
No. This can not be termed as 'Object methods being inherited by the Interfaces'. This is just a special treatment given to the interfaces in Java.
In this case all the qualified (public instance) Object class methods are declared as public abstract, which is not inheritance. Right? In inheritance we get the definition of the method as well and the non-abstract methods are not inherited as 'abstract'. But an interface in Java can't have any of these two - definition or non-abstract method. Hence, the designers of Java had to think of an alternative.
Moreover, only public instance methods are implicitly declared in the interfaces and what about other methods - for example, protected Object clone() and protected void finalize()? In case of inheritance they are also inherited by the subclasses.
Thus, we see that it's not exactly inheritance of the Object class by the interfaces. An interface can't inherit a class for the simple reason that interfaces can only have abstract methods (i.e., they can't have body). Please don't say that we can have an abstract class having only abstract methods which can be inherited safely by interfaces :-) We will better have an interface in that case.
Example: a simple Java program showing Object method access on interface ref type
package test;
public class TestInterfaceDemo{
public static void main(String[] args) {
TestInterface testInterface = new TestInterfaceImpl();
//... calling Object class method - toString - OK
System.out.println(testInterface.toString());
//... calling the interface method - testMethod - OK
testInterface.testMethod();
//... calling the implementing class method - implClassMethod - ERROR
//testInterface.implClassMethod();
//... calling the same method after casting the reference - OK
((TestInterfaceImpl)testInterface).implClassMethod();
}
}
package test;
public class TestInterfaceImpl implements TestInterface{
public void testMethod(){
System.out.println("Test Method if the Interface");
}
public void implClassMethod(){
System.out.println("Test Interface Impl Class Method");
}
}
Output:-
Test Method if the Interface
Test Interface Impl Class Method
If we uncomment the line '//testInterface.implClassMethod();' for accessing a method of the implementing class which is not a member of the interface type then expectedly we get a compiler error:-
Error(14,23): method implClassMethod() not found in interface test.TestInterface
As at the compiler doesn't know the type of the assigned object and hence can't resolve the signature of the method call on the declared reference type during compilation and therefore report an error.
One of our visitors, Martin raised this point in response to the article - Differences between Interfaces & Abstract Classes >> Thanks Martin for raising such an important point. Keep contributing!
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Tuesday, June 24, 2008
Error/Exception Handling in JSP - using JSPs or Servlets
Error/Exception Handling in JSP - using JSPs or Servlets
An unrecoverable error while executing a JSP page can be handled by specifying the error JSP pages. These error JSP pages can either be specified in the Deployment Descriptor (web.xml) OR a JSP can have its own error page specified with the errorPage attribute of the page directive. The specifed error pages must have isErrorPage attribute of the page directive set to 'true'. This causes the Web Container to declare a new implicit variable 'exception' which can be used in these error pages (using either scriptlets or custom tages) to display the cause of the error/exception on that error page.
If an error page is specified for a type of exception in the Deployment Descriptor and the page throwing that exception has also got an error page specified then the specified error page takes precedence.
Example: entries in Deployement Descriptor for error handling in JSP
<!-- Reporting an error using a JSP page -->
<error-page>
<exception-type>Fully Qualifies Exception Class</exception-type>
<location>/HandlerJSP.jsp</location>
</error-page>
...
The error JSP page uses isErrorPage attribute so that it can use 'exception' implicit object inside the scriptlets or in custom tags to know about the captured error/exception.
<%@page isErrorPage="true" %>
<HTML>
<HEAD>
<TITLE>Some Error</TITLE>
...
say if the error JSP page wants to know the name of the captured exception class, it can use the following scriptlet for that:-
<%= exception.getClass().getName() %>
Servlets and custom tags may access the captured exception object by calling the method PageContext.getError().
How are the Exceptions Reported?
When an exception is received by the underlying Web Container then it first checks if the JSP page raising that exception has any error page mentioned or not (of course if the exception is raised inside a try-catch block in a JSP the corresponding catch blocks would be examined first). If an error page is specified for the JSP, the 'exception' implicit object is passed to that error page. We'll see later in this article how this object is passed.
If the JSP page doesn't specify any error page and if none of the available catch blocks are able to handle the raised exception (if the exception is raised in try block) then the Web Container starts looking for an error page for that exception in the Deployment Descriptor. If no error page is found for that exception then the Container looks an error page for the exception's superclass and this continue until the Container finds an appropriate error page or until it reaches Throwable class (the topmost superclass of the entire exception handling mechanism in Java).
Can we use Servlets as error handles as well?
Yeah... the syntax is same as what we have for the JSP error pages. One sample entry in the Deployment Descriptor may look like:-
<!-- redirecting an error to a servlet -->
<error-page>
<error-code>404</error-code>
<location>/errorServlet</location>
</error-page>
...
Both the elements <error-code> and <exception-type> can be used with any Web resource (JSP/Servlet) in the application. The element <error-code> specifies the HTML error codes. Thus we see that the errros can be identified either by the Java exception type or by the HTML error codes.
Question: why do we have the implcit object 'exception' of type Throwable and not of the type Exception? (Question raised by one of our regular visitors Lavnish in response to the article - Implicit Objects in JSP >>. Thanks Lavnish for your contribution.)
Answer: Because the JSP page may throw exceptions of type Error as the root cause (though very rarely - may be due to JVM failure, error in a native method, etc.) as well and if we have the type of the implicit object as Exception (instead of Throwable), we would not have been able to capture such an error.
How the implicit object 'exception' is passed?
All the JSP exceptions passed to an error handler (JSP/Servlet) are actually passed via request after being saved by the Web Container in an attribute of the request named "javax.servlet.jsp.jspException". The saved exceptions are of the type javax.servlet.jsp.JspException. The constructors of the class JspException are:-
- public JspException(java.lang.String msg) - normally for writing a custom message to the server log or maybe for displaying that to the user.
- public JspException(java.lang.String message, java.lang.Throwable rootCause) - if the 'exception' implicit object is not-null then that is passed as the rootCause parameter.
- public JspException(java.lang.Throwable rootCause) - a not-null 'exception' implicit object is passed as the parameter.
It's quite evident that the JspException constructor is capable of accepting Throwable type parameter as the rootCause and hence keeping the type of the 'exception' implicit object as 'Exception' will not allow the exceptions of type 'Error' to be specified as the root cause.
Okay... why don't the exceptions are thrown directly? Why do we need to wrap them in a JspException object?
Well... I can think of few probable reasons. One, it gives us a flexibility of creating (and hence throwing) an exception without the occurrence of any error/exception condition. We can use the first constructor of JspException class which requires just a String message and we can use this approach for writing some message to a log or may be to display that message to the user or something of that sort.
Another possible reason to wrap the exceptions in a JspException is to facilitate additional text about the error condition. We may specify some custom message for the exception before throwing that to make the user comprehend the error in a better way. But, you may say that we can specify a detailed message to the constructor of the particular exception class (as Throwable and all its sub types conventionally have a constructor accepting a String parameter). Yeah... we can certainly specify the message that way also. But, the JspException constructor may provide extra details relevant to the particular page as the same exception may have different reasons on different JSPs OR may be in the different sections of a single JSP. The bottom line is that it just gives little extra flexibility :-)
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Field Hiding in Java - fields are only hidden not overridden
Field Hiding in Java - fields are only hidden not overridden
Field in Java are only hidden and not actually overridden (that doesn't mean that we'll get a compilet time error while trying this, instead they are not overridden in its true sense). Overriding means the member should be invoked based on the run time type of the object and not based on the declared type. But binding for fields in Java is always static and hence it's based on the declared type of the object reference only. Read more about Static Binding in this article - Dynamic Binding vs Static Binding >>
In case of methods, only those methods are overriden which are inherited and hence static methods are also not overridden but hidden only and they follow Static Binding only. private members (methods or fields both) are neither hidden nor overridden. They also follow Static Binding and they can not be accessed directly from any other class (including sub classes) except the class which have them. Remember, Hidden doesn't mean here we can't access the members from the subclass. So, don't confuse with being not accessible (in case of private members - fields or methods) and being hidden.
static -> non-static, narrowing visibility, diff return type - all allowed
We have much more luxury with Field Hiding as compared to what we have with static method hiding in Java. Even a static field can be hidden with a non-static field with the same name in the sub class. Field Hiding doesn't care about the return type as well. You can even narrow the visibility of a hidden member, which you can't do with methods. For example, a 'public' field in the super class can be hidden with a 'protected' field in the sub class. If we club all these luxuries then we may say that a 'public static String' type field can be hidden with a 'protected int' field in the sub class (notice the changes: static -> non-static, public -> protected, String -> int).
Example: a demo example highlighting Field Hiding in Java
package test;
class FieldHiding {
public String InstanceField = "Instance Field in SuperClass";
public static String StaticField = "Static Field in SuperClass";
public static int StaticIntField = 1;
}
public class FieldHidingDemo extends FieldHiding {
public String InstanceField = "Instance Field in SubClass";
public String StaticField = "Static Field changed to Instance Field in SubClass";
protected String StaticIntField = "public static int in super class -> protected String in subclass";
public static void main(String[] args) {
FieldHiding fieldHiding1 = new FieldHiding();
FieldHiding fieldHiding2 = new FieldHidingDemo();
FieldHidingDemo fhd = new FieldHidingDemo();
System.out.println(fieldHiding1.InstanceField);
System.out.println(fieldHiding1.StaticField);
System.out.println(FieldHiding.StaticField);
System.out.println(fieldHiding1.StaticIntField);
System.out.println(FieldHiding.StaticIntField);
System.out.println(fieldHiding2.InstanceField);
System.out.println(fieldHiding2.StaticField);
System.out.println(fieldHiding2.StaticIntField);
System.out.println(fhd.InstanceField);
System.out.println(fhd.StaticField);
System.out.println(fhd.StaticIntField);
}
}
Output:-
Instance Field in SuperClass
Static Field in SuperClass
Static Field in SuperClass
1
1
Instance Field in SuperClass
Static Field in SuperClass
1
Instance Field in SubClass
Static Field changed to Instance Field in SubClass
public static int in super class -> protected String in subclass
Notice the output in red to see how a field declared static can be hidden with a non-static field in the sub class and how can we narrow the visibility of hidden fields which we can't do for hidden methods in Java.
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Monday, June 23, 2008
Automating user input for GUI programs in Java - How?
How can you automate user input for GUI programs in Java?
How to automate GUI programs in Java? Or, How to automate User Inputs from KeyBoard/Mouse for an AWT or Swing based GUI application?
Suppose we want to create a small GUI based demo application which requires automated user input events (which we would have provided by using Keyboard/Mouse). JDK 1.3 introduced a new class named java.awt.Robot, which can be used to automate user input events. We can programmatically create equivalent of user input events by using this class.
This Robot class is primarily used for automated testing of Java platform implementations. This class ctually generates native system instructions for the user events and the execution of these instructions give the end users the same look and feel (and affect as well) what they get by using Keyboard/Mouse for the corresponding actions. For example: the method 'void mouseMove(int x, int y)' of the Robot class when called will not only generate the corresponding mouse move user input event, but it will also move the mouse cursor to the specified co-ordinates.
As we have just discussed that the method calls of this Root class actually results into the corresponding set of native system instructions and hence the platforms which don't allow such low-level input control with the current configuraions and privileges then we'll get an AWTException while trying to instantiate Robot objects.
Example: sample code snippet to use this Robot class
...
Robot robot = new Robot();
//... storing some key strokes
int keyInput[] ={KeyEvent.VK_A,KeyEvent.VK_B,...KeyEvent.VK_F};
//... a delay of 2 seconds
robot.delay(2000);
...
//... pressing SHIFT for Capital Letter entry
robot.keyPress(KeyEvent.VK_SHIFT);
...
//...pressing one of the input keys from the array
robot.keyPress(keyInput[1]);
...
//... releasing any key (say SHIFT) & pressing the ENTER key
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_ENTER);
...
We can easily observe that for all possible user input events we can easily build the corresponding set of statements using the methods of this Robot class.
Detecting the Shutdown of a JVM programmatically
How can you detect the Shutdown of a JVM programmatically?
One possible way of doing it by adding a Shudown Hook to the JVM (Is there any other way?). Of course I'm not considering the case where a new process would be launched just to kill the JVM. It should be normal JVM Shutdown - without interference of an external interrupt by any user process.
OKay... so let's discuss how can we write and add a Shutdown Hook for detecting the Shutdown of the JVM. Read more about Shutdown Hooks in this article - Shutdown Hooks in Java & their uses >>
As we know that a shutdown hook is just another Java Thread registered with the JVM, which is started (and hopefully completes execution) during the JVM Shutdown. Since, the hook(s) may not get enough time to finish their execution, hence it's always a better idea NOT to keep long running code inside a Shutdown Hook. Many Operating Systems allow only a fixed time for the entire JVM process to shut down and in case the Shutdown Hooks don't complete their execution within that time they are forcibly terminated using Runtime.halt() method.
Example: writing and adding a simle Shutdown Hook in Java
...
class CustomShutdownHook extends Thread {
...
public void run(){
...
System.out.println("Shutdown of JVM detected!");
//... do some tasks quickly in response to Shutdown
...
}
...
}
public class CustomShutdownHookDemo {
...
public static void main(String[] args){
...
//... creating a shutdown hook
CustomShutdownHook customShutDownHook = new CustomShutdownHook();
...
//... registering a shutdown hook
Runtime.getRuntime().addShutdownHook(customShutdownHook);
...
}
}
On JVM shutdown the CustomShutdownHook thread will be started and executed and therefore it'll print "Shutdown of JVM detected!" on System.out and execute other statements written in the run() method of the CustomShutdownHook thread.
Why would you need to detect the JVM Shutdown Programmatically?
There may be quite a few reasons including - you may like to clear some cache, realse some previously held important resources, or may be for the simple purpose of logging the time of the Shutdown, closing a log file, etc. But as you know Shutdown Hooks are not guaranteed to run everytime as the JVM process may be terminated abruptly (maybe by the underlying OS due to an error in some native code), hence you should avoid putting some code in a shutdown hook, which may cause the state of your application to become inconsistent in such a case.
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Common Questions on Shutdown Hooks in Java
Common Questions on Shutdown Hooks in Java
If you like to refresh your understanding of Shutdown Hooks then read this article first - Shutdown Hooks in Java >>
Question: Why doesn't Java provide infomation as to why the JVM is shutting down?
Answer: Because it can not be done in a portable way. There are certain platforms which have capabilities of notifying the potential causes of a JVM shutdown such as power failure, shut down or restart of the OS, etc., but there are some platforms where such information is not available and hence this functionality can't be implemented in a platform independent way.
Question: Will Shutdown hooks run if the JVM crashes?
Answer: No guarantee if the crash is due to an error occured while executing some native system code.
Question: Can't we do the same with the method runFinalizersOnExit?
Answer: No... runFinalizersOnExit will only be executed if the JVM shuts down due to exit and not for those termination-triggered shutdowns of the Java Virtual Machine. BTW, runFinalizersOnExit is already a deprecated method due as it's claimed to be inherently unsafe. Sun Javadoc says that this method may result in finalizers being called on live objects while other threads are concurrently manipulating them and hence this method may cause erratic behavior or a possible deadlock.
Question: Can you force an ordered execution of Shutdown Hooks in Java?
Answer: Yes, but only indirectly... as we can have the same effect by doing some manipulation (synchronizing them), but we can certainly not force an order of execution of the registered Shutdown Hooks explicitly. The Shutdown Hooks in Java are by default executed in some unspecified order, but we can synchronize the actions internally to force a particular order of execution of all those shutdown actions.
Question: Can an untrusted applet register a Shutdown Hook?
Answer: No... provided a Security Manager is installed. Both the methods - addShutdownHook and removeShutdownHook first check the permissions granted to the caller of these methods and these methods are executed only if the caller's security context permits RuntimePermission("shutdownHooks") otherwise the call raises a SecurityException. In case of an untrusted applet, we'll get this exception only as 'untrusted' means that applet doesn't have permissions.
Question: What is done if the Shutdown Hooks cause a deadlock OR if they start taking too much time to complete?
Answer: Runtime.halt() method is used in such cases to abort all the pending/running Shutdown Hooks and the JVM terminates immediately.
Question: Why the finalizers are run after all the registered Shutdown Hooks?
Answer: Because a Shutdown Hook may need to access some live objects which might have been finalized pre-maturely by the finalizers in case they run before the registered Shutdown Hooks. Remember that runFinalizersOnExit is an inherently unsafe method and enabling finalizers may result in calling finalizers on live objects as well.
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Overruling uncaught exceptions in Java - how to?
Overruling uncaught exceptions in Java - how to do?
An uncaught exception normally propagates until the default handler (or some other intermediate handler if found on the way) handles it. The default handler prints the detailes message with the exception name and also the stack trace before exiting the process.
Is there a way to nullify the effect of an uncaught exception without handling it? Yes... we can have a finally block with control transfer statements like return or maybe a labelled break. Read more - finally in Java - common uses, ques, etc. >>
Example: overruling an uncaught exception using labelled break in finally
package test;
import java.io.IOException;
public class TestFinally {
public static void main(String[] args) {
tryBlock:
try{
System.out.println("Inside Try Block");
throw new IOException();
}catch(IOException ioe){
System.out.println("Inside Catch Block");
//... throwing unchecked exceptions - we should not do
throw new RuntimeException();
}
finally{
System.out.println("Inside Finally");
break tryBlock;
}
outsideTryBlock:
System.out.println("Inside main - Outside tryBlock");
}
}
Outout:
Inside Try Block
Inside Catch Block
Inside Finally
Inside main - Outside tryBlock
This approach can be used to nullify an uncaught exception in void methods. For non-void methods, we will similarly follow the other possible approach to nullify an uncaught exception - using a return statement. In this approach we will simply return a default value and the uncaught exception (raised either in the try block or in the catch block while handling the exception raised in the try block) will be overruled.
We can use these two approaches to nullify unchecked exceptions as well (as we can see in the above example where an uncaught RuntimeException in the catch block is also being nullified), but we should avoid doing that as it'll defeat the very purpose of unchecked exception. They are supposed to be program bugs (or design bugs) and they should be treated and not nullified :-)
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
finally explained - common questions, uses, etc.
finally block - is it guaranteed to run?
Yeah... the finally block is always executed irrespective of whether the try block executes normally or throws an exception and also irrespetcive of whether the catch block (if found any) hanldes the exception normally or throws an exception itself. Whatever be the case, the finally block is always guaranteed to be executed i.e., if the control has entered a try block it's corresponding finally block will always be executed. All the uncaught exceptions are propagated after the execution of the finally block.
what if finally block throws an exception?
If the finally block itself throws an exception then all other uncaught exceptions are overruled with this exception and this exception is propagated like any other uncaught exception.
finally with control transfer statements - return or break
If the finally block doesn't have any control transfer statement then a complete execution of the finally block causes the program to proceed based on whether try block completed normally or not, catch block found or not, catch block completed normally or not, etc.
But, a finally with a control transfer statement like a return or a break will simply overrule everything and the control is transferred as specified with such a control transfer stamenet in the finally block. Find below few probable scenarios:-
Using finally to nullify uncaught exceptions in Java
We can use the control transfer statements in the finally block to overrule uncaught exceptions. We need to follow two different approaches: One, for void method and Two, for non-void methods. These are:-
Though, we can use these two approaches to nullify unchecked exceptions as well, but we should avoid such a practice as unchecked exceptions are actually program bugs or design bugs and they should be removed.
[Update: 12-Nov-2008]: Suppose we have a 'return' statement in try (and in catch, if we have a matching catch block). Now as we know that finally gets executed before the 'return' statement (of try or catch as the case might be), but Java Specifications say that a 'return' (or any other control transfer statement for that matter) in try (or catch) is evaluated and kept in a pending state until the 'finally' block gets executed. If the Runtime System finds any 'return' (control transfer statement) in the 'finally' block then the previously kept 'return' (either of try block or of catch block) in the pending state is forgotten and the one in the 'finally' block gets executed. The pending statement is executed only if 'finally' doesn't have any control transfer statement. Refer to this article for a deeper understanding how try-catch-finally gets executed in various possible cases - programming scenarios for finally >>
Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.
Saturday, June 21, 2008
Difference between forward and sendRedirect
Difference between forward and sendRedirect
forward - public void forward(ServletRequest request ServletResponse response) - it forwards a request from one servlet to another respource - dynamic/static (the resource can be another servlet, JSP, or a static HTML file). In such a case, the calling servlet only does the preliminary work for the request processing and doesn't usually write anything on the response object. Writing anything on the response object in the calling servlet will result into an IllegalStateException for the forward() call if the output is flushed already otherwise the uncommitted response buffer is cleared before the forward() call. This action is performed internally by the Servlet (or JSP which actually converts into a Servlet only) and the client browser is not at all involved in it. Client browser is simply unaware of it and the URL remain intact. Hence, any refresh/reload in the client browser will simply repeat the same request. This is the reason why a forward should not be used for serving a request involving some data modification as an accidental refresh/reload of the browser may duplicate that change. forward() is usually preferred in the cases where we simply read the data i.e., in the cases where we use SELECT operation.
The same request and response objects are passed as parameters to the forward() call hence the called resource can use all the objects defined in the request scope of the previous request. Passed response object gets cleared (if the calling servlet has written something before the forward() call) and hence it remains empty for the new resource and the called resource builds the response object which it ultimately sends to the client.
We can specify the resource with a relative URL only for a forward action. forward() called on a RequestDispatcher obtained from an objet of the class implementing ServletRequest interface accepts an URL relative either to the underlying request or to the underlying servlet context. Whereas forward() called on an RequestDispatcher obtained from a ServletContext implementation will require you to specify an URL only relative to the underlying context. Read more about this - RequestDispatcher of ServletRequest & ServletContext >>. We can NOT specify an absolute URL in forward() method.
sendRedirect - public void sendRedirect(java.lang.String location) - in this case first the request is intercepted/processed by the server and then a new URL is built and sent back to the client (this new URL is built using the URL what we specify in the sendRedirect method). We can specify either a relative URL or an absolute URL. If a relative URL if specified without a leading '/' then the Container interprets it as being relative to the current request whereas a relative URL with a leading '/' is interpreted as being relative to the underlying context. The Container interprets the relative URL and converts it into an absolute URL before sending it back to the client. Now the newly constructed URL is again requested from the client. This URL change is quite visible in the client browser.
Thus we see that sendRedirect is basically a two phase process and hence it's slightly slower than forward() method. Since, the new URL is requested as an altogether new request hence the objects placed in the previous request scope can't be accessed in the new request.
Unlike the forward() method, an accidental (or intentional) refresh/reload of browser window will not repeat the original request. Only the new URL will be requested in this case as the browser's address bar is already updated with the new URL. Hence, the operation involving modification should prefer sendRedirect() over forward() to avoid any accidental duplicacy.
Example: affect of accidental refresh/reload on forward() and sendRedirect()
Suppose the first request takes you to a page requesting you to transfer some funds online and then the second resource just notifies whether the transfer was done successfully or not. In case of a forward() call, an accidental refresh/reload of the browser window will execute the original request of transferring the fund again (as the browser has still the original URL) and then the status page will be shown. That means both the resources will again be executed and you may ned up transferring the fund twice :-) In case of sendRedirect(), the processing of the original transfer request will redirect the status URL to the client browser and hence an accidental (or maybe intentional) refresh/reload will only execute the resource (maybe a JSP) showing you the status of the previous transfer and that's what you would probably like to have. sendRedirect() avoids the execution of the original request again because in this case the browser's address bar is already updated with the new URL.
Difference between forward() and sendRedirect()