Showing posts with label JVM. Show all posts
Showing posts with label JVM. Show all posts

Tuesday, August 12, 2008

How can we access an unreachable object in Java?


Can we access an unreachable object in Java?


Yeah... we can. Sounds strange? But, it's true. We can access an unreachable object in Java.


This can be done by overriding the finalize() method and inside the method we can assign the reference 'this' to some other active reference and this way the unreachable object becomes reachable again which can be accessed like any other object. However this is not a good practice and it's seldom used (if at all).


What's finalization in Java and what's it used for?


In Java it's mainly used for doing the postmortem cleanup activities particularly used for reclaiming native resources or any other non-memory resources which can't directly be recollected by the Garbage Collector.


How the finalization of an object happens internally?


protected void finalize() throws Throwable is the signature of the finalize() method in the Object class and whenever any class overrides this method then an object of that class is internally marked by the JVM as finalizable. If such an object becomes unreachable then the Garbage Collector adds it to the JVM's finalization queue. It also makes sure that all the objects reachable from that object are also retained as it can't be sure what all objects may be accessed from inside the finalize() method. Now the object is dequeued from the finalization queue and the finalize() method is executed on that object. Once the control exits from the finalize() method then the object is considered to be finalized which is again tested by the Garbage Collector and if the GC finds that the finalilzed object is unreachable then it reclaims the memory space occupied by that object and also the spaces occupied by other unreachable objects which were retained simply because they were reachable from the finalizable object.


You can easily deduce that such a lengthy process obviously takes time and consequently slows down the performance. Hence it's always advisable to use (override) the finalize() judiciously.


What if the super class is finalizable but not the sub class?


This is not possible as the sub class will automatically become finalizable by inheriting the finalize() method from the super class. Do consider the consequences thoroughly before making any class finalizable otherwise you may end up with memory renetion problems. For example: if a super class is finalizable and sub class which is not explicitly finalizable is having fields occupying huge memory chunks then reclamation of memory occupied by a sub class instance will be delayed till the associated super class instance gets finalized. How to deal with such a situation? Well... you can use composition in stead of inheritance to avoid this problem. This will make sure that reclaimation of only the field of the finalizable class type gets delayed and not the entire object. You can easily have a method disposing the other fields which otherwise would have kept occupying the precious memory for no real purpose. This approach is quite useful in case you are using a third-party finalizable class.


In case you are writing the class yourself then you may break the class into two class - one having the code which really require finalization (i.e., the code which uses native or other non-memory resources) and the other class which simply uses the former class as a member and other non-finalizable members. Now you only need to make the former class finalizable and not the latter.


The bottom line is that don't make any class finalizable unless you have a very good reason behind it and in case you need to make then also make sure that the finalization process doesn't really cause unnecessary memory-renetion.


Is finalization guaranteed? What's the actual contract?


No... it's not guaranteed that the finalization of all the finalizable objects will happen before they are reclaimed so it obviously doesn't make sense to put any other code except the clean-up code inside the finalize() method. In fact finalizer is mainly used for having clean-up code for non-memory and native resources only.


The JVM doesn't guarantee the actual order in which the finalization of the finalizable objects will take place. All the finalizers either from the application or from the libraries are treated equally with no exception.


The JVM doesn't guarantee which thread will invoke the finalize() method of a particular object and only guarantees that the thread which will invoke the method will not have any user-visible synchronization lock at the time of finalize() invocation.


Grrr... so much of non-determinism involved. Yeah... unfortunately it's like this only. So think twice before making any class finalizable.


What if the finalize() method throws any Exception?


If an uncaught exception is thrown from within the finalize() method then it's simply ignored and the finalization of that object terminates immediately.


Any alternative to Finalization in Java?


One possible alternative is to use weak references instead of finalization. This will ensure that the programmer has a complete control over how to reclaim the resources, how to prioritize the reclaimation process (may be based on the availability of a particular native or non-memory resource), etc. We'll discuss about the weak references and about this approach in some other article.


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.



Share/Save/Bookmark


Tuesday, July 15, 2008

Java architecture, JRE, Java Platform, JVM, JDK


Java architecture, JRE, Java Platform, JVM, JDK


Java Architecture


Java is much more than just a popular programming language instead it's a complete architecture. The entire Java archirecture can be broadly categorized into three technologies which work together to make Java a powerful software development architecture. The components of the Java architecture are:-

  • The Java Programming Language - JLS (Java Langauge Specifications) provide the syntax, constructs, grammar, etc. of the Java language.
  • The Java APIs - Java Application Programming Interfaces (APIs) make available plethora of functionalities to the application developers so that they can focus on their core business functionality without bothering about the common tasks including those from the areas - I/O, Network, Language Constructs, Multithreading, Serialization, etc. Many vendors have implemented these APIs including the standard implementation given by Sun Microsystems which is normally used as a benchmark. The Java APIs are simply a collection of Java .class files. A .class file is the bytecode representation of a valid Java program. Bytecodes are a collection operator-operand tuples which are converted into the native machine level instructions by the underlying JVM.
  • The Java Virtual Machine - The JVM is the abstract machine which runs all the bytecodes on a particular machine. JVM converts the bytecodes into native instructions which are executed by the underlying Operating System.


JVM - Java Virtual Machine


This software component is the key to achieve Platform Independence feature of Java. Most of the popular platforms have their own JVM implementations and hence a Java program written and compiled on a Java-compliant platform can be run on any other Java-compliant platform.


JVM is mainly composed of two components - Classloader and Execution Engine. The first component loads the .class files after converting them into the implementation dependent internal data structures. The Execution Engine uses these data structures are converts the bytecode instructions into machine-level instructions for the underlying Operating System which are subsequently executed by the OS.


Java Runtime Environment (JRE) / Java Platform


Both the terms JRE and Java Platform represent the same thing. Java Platform started with the verion 1.2, and it was called The Java 2 Platform. JRE is nothing but a combination of JVM and Java APIs - Java SE APIs as well as Java Web (Deployment) which consists of Java Web App Development/Deployment, Java Web Start, and Applet (plug-in).


Java Development Kit (JDK)


As the name suggest it's a Kit and it contains all the software components used for compiling, documenting, and executing Java programs. It's basically a logical collection of the The Java Programming Language, JRE (JVM + Java APIs), and Tools & Tool APIs, which include java, javac, javadoc, apt, jar, javap, Deploy, Monitoring, Java VisualVM, Scripting, etc.



Share/Save/Bookmark


Wednesday, July 9, 2008

Loading, Linking, & Initialization of Types in Java


Loading, Linking, & Initialization of Types in Java


The Java Virtual Machine makes the Types (we'll discuss here the user defined Types - classes and interfaces... built-in types also undergo similar set of phases and they are normally loaded as part of the JVM process start-up) available to a Java program under execution and any Type undergoes the following phases during its entire life cycle:-

  • Loading - this is the process of loacting the bytecodes (.class file) of the correponding Type and bringing that into the JVM memory.
  • Linking - this is the process of incorporating the loaded bytecodes into the Java Runtime System so that the loaded Type can be used by the JVM.
  • Initialization - this is the process of executing the static initializers of the loaded and linked Type.
  • Unloading - this is the process of reclaiming the memory occupied by the Loaded, Linked, and Initialized Type. This happens when there are no references of that Type and hence the Type becomes eligible for garbage collection. It's important to note that garbage collection of objects is different from that of Types. An object of a Type is collected during the next garbage collection cycle soon after it becomes unreachable, but the Type is unloaded only when all the objects of that Type are already garbage collected and the Type doesn't have any other reference to it.

Creation of java.lang.Class instance of a Type


An instance of the class java.lang.Class is created for every Type loaded into the underlying JVM. This instance creation marks the end of the loading phase of the Type. If an application is distributed across multiple JVMs then for the same application one (or more) Types may be required to be loaded multiple times (one per JVM) as a JVM can't use a Type without the corresponding java.lang.Class instance. While loading a Type, the bytecodes (of the .class file) are first converted into a binary stream so that they can be brought into the JVM memory. Once the stream has been successfully brought into JVM memory, the format of the stream is checked to verify if it's as per the specifications or not. This step helps making the Java code very secure as the underlying Security Manager can simply raise an alarm if the loaded binary stream is not havng a valid structure (either tempered accidently or intentionally) and hence it can safely eliminate the possibility of running a malicious and dangerous code on the machine. This is not possible in other languages like C, where the compiled and linked .exe (on Windows) and .out (on Linux) files are directly executed by the underlying Operating Systems as they are composed of native instructions.


But, we know Verification is a part of the Linking phase, so what does the verification done in the Loading phase mean? How are the two verifications different? Well... verification is certainly a part of the Linking phase (it's the first step of the Linking phase), but implementations do use verifications of different type during various other stages as well. This is done to ensure the integrity of the running JVM. The specification clearly says that a loaded Type should not cause the JVM process to hang and if the implementations remove the verification part completely from the Loading phase then a malicious bytecode may cause the JVM to hang (or to perform something unpredictable) while creation of the java.lang.Class instance for the loaded Type.


This java.lang.Class instance is actually the complete representation of the loaded Type built using the implementation dependent internal data structures. This is subsequently used by the various steps of the Linking phase (and also during the Initialization phase). These two phases - Linking and Initialization don't deal with the raw byte stream loaded during the Loading phase.


java.lang.LinkingError - what does it signify & when is it thrown?


The Java Specifications doesn't enforce any restriction on the actual timing of the Loading & Linking phases of a Type (also not on the exact timing of the Unloading phase as that is decided by the garbage collection algorithm), but Initialization phase is required to be done only when the Type gets its first active usage. One thing is very obvious that these phases will be performed in this order only. How will a Type be linked before being loaded otherwise? Without linking how will the initializers be executed otherwise? Most of the implementations do the Loading (and also the Linking in many) in anticipation of the usage of Types and only Initialization is required to be done at first usage of those Types in such cases.


Any problem encountered while any of the three phases is captured by instances of LinkageError class or an appropriate sub class of this class. Most of the JVM implementations normally load the Types much earlier and delay the linking and initialization phase till the first use of the Type. Many others delay only the Initilization till the first use and they perform both Loading and Linking much before the first usage of the Type. Irrespective of whether the any or all the phases are completed just before first use or earlier, any error encountered during any of the phases (captured by the appropriate subclasses of the LinkageError claas) must be thrown only at the time when the Type's first use is encountered not before that. If a Type is never used actively then the captured error is never thrown and the program proceeds normally.


Thus we see that the loading, linking, and initialization of a Type must give an impression that they are done only when the Type is actually used even if Loading and/or Linking phases have already been completed in the particular JVM implementation.


java.lang.LinkageError simply indicates that the loaded class has encountered some problem during Loading, Linking or Initialization phase. The name is misnomer here and as it doesn't only indicate a problem encountered only during the Linking phase (It'll be clear in the next paragraph).


One possible scenario when this error java.lang.LinkageError (or a suitable subclass of this class) may occur:- Suppose we have two classes and one is dependent on the other. Now, after compilation of the dependent class if the other class is changed and compiled then the former class may throw LinkageError while linking - such a situation will actually throw an instance of the subclass of this class named IncompatibleClassChangeError.


java.lang.LinkageError has seven subclasses - all specifying a specific scenario indicating the kind of error encountered while Loading, Linking, or Initialization of a Type. These sub classes are:-

As you can easily notice that the LinkageError doesn't only specify a problem encountered only in the Linking phase, instead it has specific sub classes to capture the potential errors which may occur during any of the three phases - Loading, Linking, and Initialization.


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.



Share/Save/Bookmark


Thursday, June 19, 2008

Runtime.exit() vs Runtime.halt() in Java


Difference between Runtime.exit() and Runtime.halt() in Java

Runtime.exit() - public void exit(int status) - this method causes the shutdown sequence of the underlying JVM to be invoked. This method indicates an abnormal termination of the JVM and the parameter status may be used as a staus code for the various abnormal circumstances which caused the termination of the JVM process.

The shutdown sequence of a JVM is consists of two phases - One, execution of all registered shutdown hooks (read more about them in this article - Shutdown Hooks in Java >>) and Two, execution of all uninvoked finalizers (if finalization-on-exit is enabled) and then halting the JVM process.

If this method is called once the shutdown of the JVM has already started then this method will block indefinitely in case any registered shutdown hook is still under execution. Otherwise, if all the registered shutdown hooks have already completed their execution and if the finalization-on-exit is enabled, then a non-zero status code as the parameter will simply halt the JVM process whereas a zero status code will causes the method to be blocked indefinitely.

This method can be conveniently called by using the more popular System.exit() method as well. Since, System.exit(n) will be internally converted into RunTime.getRuntime().exit(n) only, hence it hardly matters which one of the two you choose. Choosing the former may seem to be little more convenient while the latter will skip the conversion step.

Runtime.halt() - public void halt(int status) - this method terminates the underlying JVM process forcibly. That means the invokation of this method will not initiate the shutdown sequence and hence no shutdown hooks or finalizers will be executed. status as a parameter serves the same purpose as it does in the Runtime.exit() method - it may be used to indicate the status code of the abnormal situation that invoked this Runtime.halt() method.

Difference between Runtime.exit() and Runtime.halt()

You might have noticed so far that the difference between the two methods is that Runtime.exit() invokes the shutdown sequence of the underlying JVM whereas Runtime.halt() forcibly terminates the JVM process. So, Runtime.exit() causes the registered shutdown hooks to be executed and then also lets all the uninvoked finalizers to be executed before the JVM process shuts down whereas Runtime.halt() simply terminates the JVM process immediately and abruptly.



Share/Save/Bookmark


JVM Shutdown & JVM Shutdown Sequence?


When & how does a JVM Shutdown? What's JVM Shutdown Sequence?

The JVM may shut down either normally or it may also be terminated abnormally:-

  • Normal Shutdown - this occurs either when the last non-daemon thread exits OR when Runtime.exit() method (or its equivalent System.exit() method) is invoked. In a normal shutdown the JVM shutdown sequence is invoked. The shutdown sequence of a JVM is consists of two phases - One, execution of all registered shutdown hooks (read more about them in this article - Shutdown Hooks in Java >>) and Two, execution of all uninvoked finalizers (if finalization-on-exit is enabled) and then halting the JVM process.
  • Abnormal Shutdown - this occurs when the JVM is terminated using an user interrupt such as typing Ctrl + C or by logging off or shutting down the machine. In such a case, the underlying operating system may allow the JVM to complete its shutdown within a fixed time frame OR it may halt the JVM process immediately and abriptly using the Runtime.halt() method. If the JVM has only a few quick-running shut down hooks (and only a few uninvoked finalizers if the finalization-on-exit is enabled) then an abnormal shut down may also have the same effect in case the OS gives adequate time for the JVM to complete these tasks. Once the shutdown sequence is already in progress and the OS finds that the allowed time has expired then it may call the Runtime.halt() to abruptly terminate the JVM process.

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.



Share/Save/Bookmark


Shutdown Hooks in Java? How are they used?


Shutdown Hooks in Java

public void addShutdownHook(Thread hook) - this method of the class java.lang.Runtime is used to register a new shutdown hook for the underlying JVM. A Shut Down Hook is an initialized thread which has not been started so far. When the JVM starts shutting down then it starts all the registered shutdown hooks in some unspecified order and all the shutdown hooks start running concurrently.

Are they guaranteed to complete execution?

It's not guaranteed that all (or even a single) the shutdown hooks registered with the JVM will complete their execution during the JVM shut down process. In some (though very rare) circumstances JVM may simply abort and may shut down abruptly. Such a situation may arise when the underlying operating system forces the JVM to stop immediately. For example, the SIGKILL signal on an Unix machine or the TerminateProcess call on a Windows machine can lead to such a situation. There may few other reasons for the JVM to abort itself forcibly - it does so if it identifies that a native method is not running as expected.

How to stop a running Hook? What should not they be used for?

Most of the operating systems require the JVM to shut down within a specified time frame. Therefore the JVM may call Runtime.halt() method to abruptly terminate all the pending jobs including abort of all the non-terminated shutdown hooks. Once a shutdown hook starts its execution, only Runtime.halt() can forcibly terminate it. Even in the above mentioned rare scenarios, the JVM uses Runtime.halt() method only to abort the still-executing shutdown hooks. Since, an OS may have a maximum allowed time limit for JVM shut down, hence the shutdown hooks should not be used for long running tasks or for those tasks which involve user interaction.

What happens if a Shutdown Hook throws an Uncaught Exception?

No special treatment for Shutdown Hooks in this regard. They are treated like normal threads only. An uncaught exception invokes uncaughtException method of the thread's ThreadGroup object, which by default writes the stack trace to System.err and then simply terminates the thread.

What happens if you try to register/de-register hooks during shutdown?

An attempt to register or de-register shutdown hooks while the JVM shutdown process is already in progress will cause an IllegalStateException to be thrown.

Caution to be taken while writing Shutdown Hooks

Since they are expected to complete their execution very quickly, so we should avoid putting code which may require (even in some cases) a longer time to complete. These hooks should be thread-safe and they should not cause any deadlock to happen. It's better not to use those services in a shutdown hook which have got their own shutdown hooks registered because they themselves may be in the process of shutting down.


Update[June 23, 2008]: Read more on Shutdown Hooks - Common Questions on Shutdown Hooks 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.



Share/Save/Bookmark


Sunday, June 1, 2008

Classloaders in Java? How do they work?


Classloaders in Java

Classloaders are the Java program(s) i.e., Java classes that are responsible for loading classes into the underlying JVM. Any class before being used, should first be available and accessible to the classloader, which will load the class into the memory and then only the JVM can perform any task on it. Having said that we see that all the classes in Java are first loaded into the memory by a classloader (normally the default classloader) and then only the class can be used in any possible way. Right? We just said that classloaders are also Java classes only. Now, who loads this classloader classes then? Good pick, if you really picked it :-) The answer to this question is - the bootstrap classloader. Ohh... again a classloader. Yeah, it is, but different from what we discussed above. It's a native classloader and not written in Java. This bootstrap classloader is platform dependent (of course, that's why we called it native) and it's normally written in C.

How the Class-loading mechanism work in Java?

Whenever you try to execute a Java program by invoking the 'java' command then a native Java launcher program is first invoked. This launcher program is 'native' and hence platform dependent. Well... quite obvious, isn't it? Now, on a successful invokation of this launcher program, it calls the bootstrap classloader program. This bootstrap loader program then loads the Core Java classes (classes belonging to the packages starting with 'java.') and then loads two other classloaders - extension classloader and application classloader. That's it. The job of the bootstrap classloader is done once it completes these three tasks - One, loading Core Java classes; Two, loading extension classloader; Three, loading application classloader.

The bootstrap classloader transfer the control to the extension classloader, which then loads the extension classes into the memory. What are extension classes in Java? They are classes belonging to all the packages starting with 'javax.' OR the classes present in the 'ext' directory of the underlying JRE. You may like to go through the post Extension Mechanism in Java for more details.

Finally the control is transferred to the application classloader, which loads the classes of the current application.

One interesting point to note here is that all the three classloaders follow the delegation model i.e., if the application classloader requires to load a class, it'll first delegate a request for the same class to the extension classloader, which will in turn send a request to the bootstrap classloader for the same class. Now, the bootstrap classloader will check if that class is a Core Java class or not. If yes, then it'll make that available to the extension classloader in response to its request and finally the extension classloader will make that available to application classloader. If the bootstrap classloader discovers that the requested class if not a Core Java class, it notifies the same to the extension classloader. Now the extension classloader checks if this class is an extension class or not. If it discoveres that it's an extension class, it makes that available to the application classloader otherwise it notifies the application classloader that the requested class is not even an extension class. The application classloader itself loads a class in this case (when it has got notifications that the requested class is neither a Core Java class nor an extension class).



Share/Save/Bookmark


Classloading for Web Apps or EJBs on an Apps Svr


Question: How does the classloading happen for Web Apps or EJBs?

Answer: Usually all the popular application servers provide separate class-loaders for all the Web Applications and EJBs, which have been deployed separately on that application server. However, if you package more than one Web Apps and/or EJBs in an EAR - Enterprise Archive and deploy that EAR file on the application server, then the application server will provide only one class-loader. The idea is to provide one class-loader for each separate deployment.

The class-loader(s) provided by the application server are loaded into the memory by the default Application Classloader provided by Java. In fact, the classloaders provided by the application servers derive the same default Java-supplied Application Classloader. Once loaded, these apps server supplied classloaders take the responsibility of loading all the classes (which are not part of the Core Java classes - already loaded by the Java-supplied Bootstrap classloader OR part of the Extension classes - already loaded by the Java-supplied Extension Classloader) of the Web App(s) and/or EJB(s).

This feature makes the deployement process of the applications on the underlying Application Server faster as all the application-specific classloaders (Apps Server supplied) load the classes of the corresponding applications concurrently.



Share/Save/Bookmark


Make a class available to all apps on an Apps Server


Question: How would you make a single class available to all applications on an Application Server? What are the advantages and disadvantages of this approach?

Answer: Simply by getting the class loaded by a top-level Classloader. For example, if you want to make an application specific class available to all the applications, you just need to add that class to the CLASSPATH of your application server. All the classes of the CLASSPATH are loaded by the time Java-supplied Application Classloader transfers the control to the application specific Apps Server supplied classloaders and hence every class, which is a part of the CLASSPATH will be available to all the application specific classloaders.

Advantages/Disadvantages of this approach

The obvious advantage of this approach is that you don't need to load the same class more than once, but it comes with at least two disadvantages as well, which are:-

  • You can not unload this class as it would be loaded by a Java-supplied classloader, which doesn't have the capability of unloading a loaded class unlike the Application Server supplied classloaders which have this capability as well.
  • If you require to modify this class then you will need to restart the server to get the changes reflected as Java-supplied classloders don't have the capability of re-loading the classes unlike Apps Server supplied classloaders.



Share/Save/Bookmark


Monday, May 26, 2008

Extension Mechanism in Java. What, How, etc.


Extensions in Java


Extension are nothing but a set of packages or classes or related resources all bundled into a Java Archive (JAR) file and stored at (or referenced from) a specified location. You can have two types of extensions in Java based on whether you store the JAR at a specified location OR reference the JAR from a specified location. These are:

  • Installed Extension: If you store the JAR file in a particular directory (inside the current Java Runtime Environment), which is especially meant to store Java extensions then such extensions are named installed extensions.
  • Download Extenssion: If you specify the JAR file from the manifest file of another JAR file (accessible to the application) then in this case the extensions are named download extensions.


Installed Extensions


The special directory used to keep the installed extensions is jdk<version>/jre/lib/ext. These installed extensions become part of the Core API of the underlying Java platform, so they will be visible and hence available in all the processes running in the current Java Runtime Environment, so do take care of the directory structure of the classes in the JAR file before bundling them. It should be similar to what we have for the other standard APIs in Java.


Java 6 goes one step further and allows you to store the installed extensions at an independent location and all the JREs installed on a particular system can share the same extensions. Prior to Java 6, the extensions were looked only in ../jre/lib/ext directory, but from Java 6 they will be looked in a series of directories staring with this directory. So, the first directory of that series will always be .../jre/lib/ext and maybe you can have the independent location as the second entry. Currently this independent location is independent only to the JREs installed on a system, but fixed for a particular Operating System. Like, this directory should be SystemRoot\Sun\Java\lib\ext for MS Windows OS, /usr/jdk/packages/lib/ext for Solaris OS, and /usr/java/packages/lib/ext for Linux OS.



Download Extensions


In this case the extension JAR files are referenced from the manifest file of any other JAR of the current JRE. The JAR file referring to the download extension need to be itself an extension. It can be a normal JAR file somehow reachable to the application (i.e., the directory having this JAR file should be there somewhere in the CLASSPATH). There are two ways of referring to an external JAR file in a manifest file: One, by using a Class-Path header and Two, by using an Extension-List header. A maximum of one of each of the headers is allowed in a manifest file. But, one header can refer any number of extension JARs.


The difference between the two ways is that the download extensions referred by a Class-Path header are downloaded only for the lifetime of the application which downloads them. For example, a Web Browser running an Applet may require certain functionalities to be shipped via download extensions for the smooth execution of the Applet in the browser window. The advantage of using this approach is that you don't need to install anything on the clinet machine. The clinet machine should be capable of running a Web Browser. That's it. The disadvantage is also quite clear - you download it every time you need. Download extentions referred by an Extension-List header cause the extensions to be downloaded the first time they are needed and they are directly installed in the .../jre/lib/ext directory of the underlying JRE that time only. So, they become similar to an installed extension afterwards. This is the advantage that you need to download them only once, but the disadvantage is that the deployment of Extension-List header based download extentions is complex as compared to Class-Path header based download extensions.




Share/Save/Bookmark


Sunday, May 25, 2008

Properties and System Properties in Java


One of our visitors, Ran Vijay posted the following two questions:-

  • What are System Properties in Java?
  • What is the difference between loading a JDBC Driver using System Properties and loading it using Class.forName()?

Let's first discuss Properties in Java and then we'll move on to System Properties and finally to the second question, which is regarding loading of JDBC Drivers.

Properties in Java

In Java, Properties are actually configuration values which are managed as the traditional key-value pairs. Both the Key and the Value in every pair will be String values only. As the name suggests, the Key will be used to retrieve the corresponding Value and hence it must be unique in a properties file. These files are plain text files and by convention we give them ".properties" extension. To manage properties in Java, we need to create instance of java.util.Properties class
. This class contains all the methods required to manage and access the properties file. The properties files are used quite frequently in Java applications for storing and managing the configuration value which your application may require during various phases of its execution. For Example, you may have a property named "DBURL" and you can simply use the value associated with this key to fetch the Database URL you would like to use at run time. The advantage of using this approach is that if you want to change the DBURL then you don't need to touch the code now. The all you need is to go and change the Value associated with the "DBURL" Key in the properties file being accessed in your application. This will make your application far more flexible and maintainable. If a user (say a tester) doesn't know Java then it'll be difficult for him/her to change the URL in the Java code, but changing the value in a text-file will be easy for everyone and hence such an approach will enhance the usability of your application as well.

getProperty(String key) and getProperty(String key, String defaultValueifkeyNotFound) are the methods used to read the properties. Similarly, setProperty(String key, String value) is the method to add another Key-Value pair to the Properties object.

Caution: Access to a properties file requires approval from the current security manager of the running application. So, you may not like to put any such code inside an applet as the browser, your code will run into, may not have enough priviledges to access a file on the local disk. Moreover, it's hard to assume that the property you require in your applet will be there in the properties file (or even a file with that name will exist) on the local disk.


System Properties in Java

The way we use custom proprties file to maintain the configuration details of our application, the Java platform also uses a Properties object to maintain the configuration details of the current runtime environment. This object is called System Properties and it stores hell lot of Key-Value pairs for different properties the Java runtime environment uses to maintain the execution environment. Some of these properties store the Current User, Version of the Java Runtime Env, Path Separator character, OS Name, OS Version, User's Working Directory, User's Home Directory, JDBC Drivers, etc. Many of these System Properties are standard, but few additional platform dependent System Properties may also exist.

Reading/Writing to the System Properties

Reading is pretty simple. You just need to use 'System.getProperty()' method. This method has two variants. One, which requires only one String argument. Two, which requires two String arguments. For the one which requires only one argument, you need to give the name of the System Property you're trying to get the value of. This method returns 'null' if the property with that name doesn't exist. The second variant of this method requires you to specify the second String argument as the value you would like to be returned (instead of 'null') in case a property with the name given as the first argument doesn't exist.

Writing to the System Properties is not quite similar to what we use to write to a normal Properties onject. We use 'System.setProperties()' method, which requires a Propereties object. You need to set this object with all the required Key-value pairs. Beware, it replaces the entire set of system properties with those represented by the passed properties object. The changes made by this method will last only for the current run time environment and the Java run time system re-initializes the system properties each time it starts up. If you want to make the changes permanent then you need to write the value to some file before shutting down the application and load and set the System Properties each time the application starts up.

Caution: Read/Write access to the System Properties is also governed by the current Security Manager of the running application, so you may be denied the access in various situation - most common of them being 'accessing them in Applets'.


Difference between loading the JDBC Drivers through System Properties and through Class.forName()?


Well... no real difference in the functioning of the drivers. It's just the time of loading and instantiating the drivers that gets different in these two cases. In case of loading the drivers through System Properties, they get loaded and instantiated during the start up of the Java Runtime Environment itself while loading them through Class.forName() will cause the loading and instantiating of the driver during the execution of this Java statement. You may like to read the article 'Role of DriverManager Class and Driver Interface in Java' for more details.




Share/Save/Bookmark


Saturday, May 24, 2008

Why Java does not have Clear Screen functionality?


Why Java does not have Clear Screen functionality?


Clear Screen functionality has not been implemented in Java as it's simply not possible without sacrificing Platform Independence. So, how to handle a situation asking this? Well... Java has not been designed to develop applications requiring a direct console based interaction. You may think of using Swing or AWT based GUI instead. It's not impossible to have such a functionality in Java, but certainly not portable and hence not preferrable. We do have few platform dependent workarounds to achieve it in Java and the best among the lot still remains the same - using JNI.


In Java, we don't have the concept of a typical console as we have in C/C++. Instead all I/O in Java is stream-based. I don't think Clear Screen can be implemented for a stream as the steam may point to a file, a printer (it will be a really challenging scenario, isn't it?), or may be to a console on certain platforms. Since, you never know what this stream would be pointing to at run time, you can't assume it to be a console in all the cases and hence can not have that functionality. Clear Screen will obviously make sense only for clearing the console and not for a file (logs etc.).


System.out.println() is far more easier to implement in all environments maintaining platform independence as irrespective of what the stream points to at runtime, it can always be written on. This holds true for C/C++ as well. And probably this is the reason why 'printf()' works fine in all environments in case of C/C++ (Now in Java also ... Java 5.0 onwards) and not 'clrscr()'.


C++ also has the concept of Streams similar to that in Java and I think Clear Screen function is not a part of any class based on streams. It's a separate method altogether and it has a specific implementation only for those environments which have the concept of Console. For different platforms we may need to look for different vendor specific extension to have that functionality even in case of C/C++. For instance, Turbo C/C++ has the function 'clrscr()' in the vendor specific header file 'conio.h'. We don't have that header file available for Linux platform.


Similar explanation can be given for other platform dependent tasks such as 'accepting input without ENTER being pressed - a functionality getch() provides in C/C++', 'applying font color, background color, etc. on the console', and so on. Such tasks have not been implemented consistently across all platforms even in C/C++, so forget about Java. The goals of Java will probably never allow such tasks to be implemented not at least by using standard library functions. You got to use platform-dependent vendor specific packages to achive them unless of course, all the environments start following the same standards for console and other related stuff.


I thank Lavnish (one of our regular visitors) for raising this point in response to the post on 'Limitations of Java Language'. He runs a blog and writes frequently on Java. You can find his post on the Clear Screen functionality here. I hope our visitors will continue chipping in with their valuable comments and making this place better and better for us.


Update from Java 6.0


Java 6.0 has gone C/C++ way to facilitate better interaction with character-based console devices by using standard library functions. It seems that it wasn't possible for them to have such features for traditional Java Streams and hence they created a new Java Class named java.io.Console. This Class is mainly for reading from and writing to the Console and not for clearing it (as of now).


The Sun Java Doc of this class clearly says that the class contains methods to access the character-based console device, if any, associated with the current JVM. We can obviously see a compromise with Platform Independence here as the code written using this Class can never be guaranteed to behave uniformly across all platforms and hence not portable. System.console() method simply returns 'null' on the platforms which doesn't have an associated Console with the underlying JVM.


On the platforms where it finds a Console, it probably uses JNI internally to get the task done. We always have such solutions provided by third party vendors and the only good thing about the addition of this new class is probably that it's now a part of the standard library and it might be having little more efficient code than the code supplied by the third party vendors.


BTW, the center of our discussion 'Clear Screen functionality' is still not there in this class. Let's see if at all they provide that also in the newer releases of Java.


The bottom line remains the same - we would probably never have any such functionality without compromising Platform Independence and in most of the cases the APIs would probably be using JNI only. A true Java solution to this problem still remains a topic of research.




Share/Save/Bookmark


Wednesday, May 14, 2008

How can you force Garbage Collection?


You can’t force it to run. You can only request. This request can be made by calling ‘System.gc()’ API. GC is never guaranteed by the JVM to be started immediately after placing the request. Based on the particular implementation of the JVM, it may prioritize the next cycle of GC. That’s it.



Share/Save/Bookmark


Write Once Run Anywhere – what does it actually mean?


In Java, all programs are compiled into bytecodes in form of .class files. These bytecodes can run on any platform.

Bytecodes are special kind of representation for the instructions, which are interpreted by the native JVM. It contains the instructions in a standard format and doesn’t include any platform specific stuff. The native JVM is responsible for converting those instructions into native instructions, which the underlying OS can understand and execute.

This extra layering enables that the Java programs written once can run anywhere. Java Compiler is not a platform dependent entity, so irrespective of the platform you used for writing you Java program, you can use the standard Java Compiler ‘javac’ on any platform of your choice to compile the code. Or, you can simply ship the compiled ‘.class’ file to the system you want to run the code on.



Share/Save/Bookmark