Showing posts with label properties. Show all posts
Showing posts with label properties. Show all posts

Saturday, 28 May 2011

Environment variables in java

Unlike C or C++, there is no getEnv() method in Java.

Part of the reason is that Java could conceivably be run on a platform that does not support the concept of environment variables. The expected way to pass environment-variable-like values to a Java application is with the -Dname=value syntax seen a few times in earlier chapters. Using the -D syntax on the java command line effectively adds the specified name and value to the list of system properties. Therefore, if you need to send a system environment variable named SomeEnvVar to your Java code, you can include it on the command line like this:

java -Dsome.env.variable=$SomeEnvVar YourClass (Unix/Linux)

or

java -Dsome.env.variable=%SomeEnvVar% YourClass (Windows) 


Then you access the new system property as follows:

String some_value = System.getProperty ("some.env.variable"); 

Obviously, you can name the system property anything you want.



Sunday, 8 May 2011

How to Access System Properties?

This code example shows how to list all system properties, get/set the value of a system property:

import java.util.Enumeration;
import java.util.Properties;
//some logics....
//prints all the system properties onto the console
public static void listAllSystemProperties() {

//List All System Properties
Properties props = System.getProperties();
Enumeration enumeration = props.keys();
while (enumeration.hasMoreElements()) {
String propName = (String) enumeration.nextElement();
String propValue = (String)props.get(propName);
System.out.println(propName + " = " + propValue);
}


// Set a system property
String previousValue = System.setProperty("myjava.version", "5.0");
//Get a system property
String version = System.getProperty("myjava.version");
System.out.println("myjava.version=" + version);

}


Here is an example to get the working directory (which is the location in the file system from where the java command was invoked):

    String curDir = System.getProperty("user.dir");

A system property can be set or overridden by specifying the -D option to the java command when running your program.

    java -Dmyjava.version="5.0" MyApplication

Monday, 18 April 2011

Finding the current working directory in java

The current directory can be found using getProperty() method.

String curDir = System.getProperty("user.dir");

Sunday, 17 April 2011

Loading Java Properties Files

Java Properties files are amazing resources to add information in Java. Generally these files are used to store static information in key and value pair. Things that you do not want to hard code in your Java code goes into properties files.
Although there are multiple ways of loading properties file, I will be focusing on loading the resource bundle files from class path resources. There are advantages of adding properties files in the classpath:
  1. The properties files became a part of the deployable code (e.g. JAR file) making it easy to manage.
  2. Properties files can be loaded independent of the path of source code.
Let us see the simple way of Loading a property file in Java code. There are two ways of loading properties files in Java.
1. Using ClassLoader.getResourceAsStream()
2. Using Class.getResourceAsStream()
In our example we will use both methods to load a properties file.
Following is the content of sample properties file. The properties file will be in package com.vaani.resources.
com/vaani/resources/config.properties 


hello.world=Hello World
To load properties file using Classloader, use following code:
this.getClass()
.getResourceAsStream("/some/package/config.properties");

The Class.getResourceAsStream(name) returns an Inputstream for a resource with a given name or null if no resource with the given name is found. The name of a resource is a ‘/’-seperated path name that identifies the resource. If the name with a leading “/” indicates the absolute name of the resource is the portion of the name following the ‘/’.
In Class.getResourceAsStream(name), the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object’s class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).
So in our example to load config.properties we will have a method loadProps1().
private Properties configProp = new Properties();
...
public void loadProps1() {
InputStream in = this.getClass().
getResourceAsStream("/com/vaani/resources/config.properties");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}

To load properties file using Classloader, use following code:
this.getClass()
.getClassLoader()
.getResourceAsStream("some/package/config.properties");
The ClassLoader.getResourceAsStream(name) returns an Inputstream for reading the specified resource or null if the resource could not be found. The name of a resource is a ‘/’-seperated path name that identifies the resource. The name no leading ‘/’ (all namea are absolute).
So in our example to load config.properties we will have a method loadProps2().
private Properties configProp = new Properties();
public void loadProps2() {
InputStream in = this.getClass()
.getClassLoader()
.getResourceAsStream
("com/vaani/resources/config.properties");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}

The folder structure of our example code will be:
com/vaani/resources/config/config.properties has property file, and com.vaani.java has our class to
read from property file.

The full Java code for testing:
package com.vaani.java;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
public class LoadPropertiesExample {
private Properties configProp = new Properties();
public static void main(String[] args) {
LoadPropertiesExample sample = new LoadPropertiesExample();
sample.loadProps2();
sample.sayHello();
}
public void loadProps1() {
InputStream in = this.getClass()
.getResourceAsStream
("/com/vaani/resources/config.properties");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadProps2() {
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream
("com/vaani/resources/config.properties");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sayHello() {
System.out.println(configProp.getProperty("hello.world"));
}
}

Monday, 11 April 2011

Simple Guide To Understand Resource Profile of Java Application

Synopsis

This note describes a few simple commands on how to view the RAM and CPU usage of your Java process. It provides brief pointers on how to identify the influencing parameters and how to tweak it.

Memory

Java Heap

The heap size of your Java process can be controlled by using a combination of –Xmx and –Xms.
The heap size being used at any point of time, and the behavior of the garbage collections can be understood by analyzing the output of the –verbose:gc argument to the JVM.
Please see:
http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html (Section 3.2)

Native Memory

This is the RAM that the java process consumes on the native system.
On Solaris, a simple command will provide this information.

ps -eo "user pid rss time comm"  | grep java
(RSS – The “resident set size” of the process, in kilobytes)
e.g. – In our scenario, we realized that while the maximum heap in java had been set to 64M (-Xmx), the RAM utilized on Solaris was ~120M.
There are instances where the RAM consumed by the Java process is upto 6 times the specified Java heap size for different flavours of Unix.
Please see:
man ps
http://en.wikipedia.org/wiki/Resident_set_size

CPU

In a long running java process, you’d be interested in the cumulative CPU time consumed.

ps -eo "user pid rss time comm"  | grep java
Here “time” will show you the cumulative CPU time consumed since the process started.
This can be run at regular intervals or as required , to understand the CPU usage when the java process is used/invoked.
(This will be especially important in scenarios when you are migrating to Java, when Java comes across as CPU hungry when compared to C/ C++).

Java tools

There are several tools bundled with Java. Some that can be easily used to assist you are:

JStack

jstack prints Java stack traces of Java threads for a given Java process.
You can use this to get an idea of what’s going in you java process, which java classes are being loaded and so on.
Please see:
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstack.html
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jps.html

Jmap

Jmap shows you the native libraries used in your Java process.
Please see:
http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jmap.html

Others

Please see the list of Java tools at http://java.sun.com/j2se/1.5.0/docs/tooldocs/
(Please see the section on “Monitoring and Management Tools” and “Troubleshooting Tools” )

JVM options

There are several JVM options available. For a complete listing:
Please see:
http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp
The only options discussed here are “–server “ & “-client”.
In our scenario, we saw an improvement of roughly 33% in the usage of RAM and CPU when we used “-client” over “–server” option.
However, which option to use will depend upon your specific scenario. Points to consider include the size of the component, libraries in use, usage characteristics (e.g. – long running as in a daemon, or one time use as a client). It could also come about by trial and error as you use or simulate the component’s working environment.
Roughly the theory about using either of the two is:
The –client option is optimized to start the java process quickly. It executes the application as bytecode.
The –server option is optimized to best use the resources available on a server grade machine. With respect to the application, it notes the usage and eventually compiles the bytecode to native executable. Thus surpassing the –client performance benchmark in the long run.
So for quick startup and fewer resources use the –client option. If more resources are available and better performance required in long run, use the –server option.
That’s the theory, but you’ll have to verify the behavior yourself for your application.
Please see the discussion on
http://www.velocityreviews.com/forums/t130082-difference-between-client-server-classic-and-hotspot-jvms.html

Factors Influencing the Resource Usage

Some examples are provided for factors affecting these parameters.
  • As we’ve seen above, the CPU and RAM utilised differs considerably depending on the JVM parameters used.
  • The libraries used. e.g. – we noticed a fair difference between use of a type 2 and type 4 driver to connect to the database. (The type 2 driver was more expensive both in terms of CPU and RAM)
  • Naturally, operations that are performed by the application. In our case, we noted that IO to the file system took up a huge amount of CPU. (In this case writing to the log file. If you are able to redirect the standard output to the log file instead, the CPU for this activity doesn’t get attributed to your component :) )
  • Very interestingly, even an idle java process will consume CPU. Please see an interesting note on this. http://blogs.sun.com/nickstephen/entry/java_why_does_my_jvm

Summary

After you’re through tweaking and tuning your Java application within the JVM, you still need to concern yourself with how it performs on the native (Unix ) environment. This note attempts to give some pointers on where to begin from and what to look out for. Hope it will be helpful.

Thursday, 21 October 2010

Using Properties to Manage Program Attributes

An attribute has two parts: a name and a value. For example, "os.name" is the name for one of the Java platform's system attributes; its value contains the name of the current operating system, such as "Solaris".
The Properties class in the java.util package manages a set of key/value pairs. A key/value pair is like a dictionary entry: The key is the word, and the value is the definition. This is a perfect match for managing the names and values of attributes. Each Properties key contains the name of a system attribute, and its corresponding Properties value is the current value of that attribute.
The System class uses a Properties object for managing system properties. Any Java program can use a Properties object to manage its program attributes. The Properties class itself provides methods for the following:
  • Loading key/value pairs into a Properties object from a stream
  • Retrieving a value from its key
  • Listing the keys and their values
  • Enumerating over the keys
  • Saving the properties to a stream
Properties extends the HashtableProperties class and inherits methods from it for doing the following:
  • Testing to see if a particular key or value is in the Properties object
  • Getting the current number of key/value pairs
  • Removing a key and its value
  • Adding a key/value pair to the Properties list
  • Enumerating over the values or the keys
  • Retrieving a value by its key
  • Finding out if the Properties object is empty

The Life Cycle of a Program's Properties

There are 3 phases in program's properties life cycle :
  • Starting up - where properties are loaded
  • Running - where properties are get and set
  • Exiting - saving the properties
Now dealing with these phases one by one.


Starting Up
The actions given in the first three boxes occur when the program is starting up. First, the program loads the default properties from a well-known location into a Properties object. Normally, the default properties are stored in a file on disk along with the .class and other resource files for the program. Next, the program creates another Properties object and loads the properties that were saved from the last time the program was run. Many applications store properties on a per-user basis, so the properties loaded in this step are usually in a specific file in a particular directory maintained by this application in the user's home directory. Finally, the program uses the default and remembered properties to initialize itself. The key here is consistency. The application must always load and save properties to the same location so that it can find them the next time it's executed.

Running


During the execution of the program, the user may change some settings, perhaps in a Preferences window, and the Properties object is updated to reflect these changes. For them to have a permanent effect, they must be saved.

Exiting
Upon exiting, the program saves the properties to its well-known location, to be loaded again when the program is next started up.

Setting Up Your Properties Object

The following Java code performs the first two steps described in the previous section: loading the default properties and loading the remembered properties:
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();

// create program properties with default
Properties applicationProps = new Properties(defaultProps);

// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
First, the application sets up a default Properties object. This object contains the set of properties to use if values are not explicitly set elsewhere. Then the load method reads the default values from a file on disk named defaultProperties. Next, the application uses a different constructor to create a second Properties object, applicationProps, whose default values are contained in defaultProps. The defaults come into play when a property is being retrieved. If the property can't be found in applicationProps, then its default list is searched.

Finally, the code loads a set of properties into applicationProps from a file named appProperties. The properties in this file are those that were saved from the program the last time it was invoked (the next section shows you how this was done).

Saving Properties

The following example writes out the application properties from the previous example using Properties's save method. The default properties don't need to be saved each time because they never change.
FileOutputStream out = new FileOutputStream("appProperties");
applicationProps.save(out, "---No Comment---");
out.close();
The save method needs a stream to write to, as well as a string that it uses as a comment at the top of the output.

Getting Property Information

Once you've set up your Properties object, you can query it for information about various keys/values that it contains. An application gets information from a Properties object after start up so that it can initialize itself based on choices made by the user. The Properties class has several methods for getting property information:
  • contains(Object value)
    containsKey(Object key)

    Returns true if the value or the key is in the Properties object. Properties inherits these methods from Hashtable. Thus they accept Object arguments. 
  • You should pass in Strings to get property.
    getProperty(String key)
    getProperty(String key, String default)

    Returns the value for the specified property. The second version allows you to provide a default value. If the key is not found, the default is returned.
  •  list(PrintStream s)
    list(PrintWriter w)

    Writes all of the properties to the specified stream or writer. This is useful for debugging.
  • elements()
    keys()
    propertyNames()

    Returns an Enumeration containing the keys or values (as indicated by the method name) contained in the Properties object.
  • size()
    Returns the current number of key/value pairs.
  • Setting Properties
    A user's interaction with a program during its execution may impact property settings. These changes should be reflected in the Properties object so that they are saved when the program exits (and calls the save method). You can use the following methods to change the properties in a Properties object:
    put(Object key, Object value)

    Puts the key/value pair in the Properties object.
  • remove(Object key)
    Removes the key/value pair associated with key.
    Both put and remove come from Hashtable and thus take Objects. You should pass in Strings.