Sunday, November 25, 2007
Java Tools Collections
http://javatoolbox.com/categories
For example, if you are looking for some testing tool, but not sure which one to use or from where to get, you can check it here
http://javatoolbox.com/categories/tests
Friday, November 2, 2007
Common causes for memory leaks in Java applications
A very simple example of a memory leak would be a java.util.Collection object (for example, a HashMap) that is acting as a cache but which is growing without any bounds.
public class MyClass {
static HashSet myContainer = new HashSet();
public void leak(int numObjects) {
for (int i = 0; i < numObjects; ++i) {
String leakingUnit = new String("this is leaking object: " + i);
myContainer.add(leakingUnit);
}
}
public static void main(String[] args) throws Exception {
{
MyClass myObj = new MyClass();
myObj.leak(100000); // One hundred thousand }
System.gc();
}
In the above program, there is a class with the name MyClass which has a static reference to HashSet by the name of myContainer. In the main method of the class: MyClass, (in bold text) within which an instance of the class: MyClass is instantiated and its member operation: leak is invoked. This results in the addition of a hundred thousand String objects into the container: myContainer. After the program control exits the subscope, the instance of the MyClass object is garbage collected, because there are no references to that instance of the MyClass object outside that subscope. However, the MyClass class object has a static reference to the member variable called myContainer. Due to this static reference, the myContainer HashSet continues to persist in the Java heap even after the sole instance of the MyClass object has been garbage collected and, along with the HashSet, all the String objects inside the HashSet continue to persist, holding up a significant portion of the Java heap until the program exits the main method.
This program demonstrates a basic memory leaking operation involving an unbounded growth in a cache object. Most caches are implemented using the Singleton pattern involving a static reference to a top level Cache class as shown in this example.
Here is the GC information for you for the above snippet....
[GC 512K->253K(1984K), 0.0018368 secs]
[GC 765K->467K(1984K), 0.0015165 secs]
[GC 979K->682K(1984K), 0.0016116 secs]
[GC 1194K->900K(1984K), 0.0015495 secs]
[GC 1412K->1112K(1984K), 0.0015553 secs]
[GC 1624K->1324K(1984K), 0.0014902 secs]
[GC 1836K->1537K(2112K), 0.0016068 secs]
[Full GC 1537K->1537K(2112K), 0.0120419 secs]
[GC 2047K->1824K(3136K), 0.0019275 secs]
[GC 2336K->2035K(3136K), 0.0016584 secs]
[GC 2547K->2248K(3136K), 0.0015602 secs]
[GC 2760K->2461K(3136K), 0.0015517 secs]
[GC 2973K->2673K(3264K), 0.0015695 secs]
[Full GC 2673K->2673K(3264K), 0.0144533 secs]
[GC 3185K->2886K(5036K), 0.0013183 secs]
[GC 3398K->3098K(5036K), 0.0015822 secs]
[GC 3610K->3461K(5036K), 0.0028318 secs]
[GC 3973K->3673K(5036K), 0.0019273 secs]
[GC 4185K->3885K(5036K), 0.0019377 secs]
[GC 4397K->4097K(5036K), 0.0012906 secs]
[GC 4609K->4309K(5036K), 0.0017647 secs]
[GC 4821K->4521K(5036K), 0.0017731 secs]
[Full GC 4521K->4521K(5036K), 0.0222485 secs]
[GC 4971K->4708K(8012K), 0.0042461 secs]
[GC 5220K->4920K(8012K), 0.0018258 secs]
[GC 5432K->5133K(8012K), 0.0018648 secs]
[GC 5645K->5345K(8012K), 0.0018069 secs]
[GC 5857K->5558K(8012K), 0.0017825 secs]
[GC 6070K->5771K(8012K), 0.0018911 secs]
[GC 6283K->5984K(8012K), 0.0016350 secs]
[GC 6496K->6197K(8012K), 0.0020342 secs]
[GC 6475K->6312K(8012K), 0.0013560 secs]
[Full GC 6312K->6118K(8012K), 0.0341375 secs]
[GC 6886K->6737K(11032K), 0.0045417 secs]
[GC 7505K->7055K(11032K), 0.0027473 secs]
[GC 7823K->7374K(11032K), 0.0028045 secs]
[GC 8142K->7693K(11032K), 0.0029234 secs]
[GC 8461K->8012K(11032K), 0.0027353 secs]
[GC 8780K->8331K(11032K), 0.0027790 secs]
[GC 9099K->8651K(11032K), 0.0028329 secs]
[GC 9419K->8970K(11032K), 0.0027895 secs]
[GC 9738K->9289K(11032K), 0.0028037 secs]
[GC 10057K->9608K(11032K), 0.0028161 secs]
[GC 10376K->9927K(11032K), 0.0028482 secs]
[GC 10695K->10246K(11032K), 0.0028858 secs]
[GC 11014K->10565K(11416K), 0.0029284 secs]
[Full GC 10565K->10565K(11416K), 0.0506198 secs]
[GC 11781K->11071K(18956K), 0.0035594 secs]
[GC 12287K->11577K(18956K), 0.0042315 secs]
[GC 12793K->12082K(18956K), 0.0043194 secs]
[GC 12843K->12390K(18956K), 0.0030633 secs]
[GC 13606K->13494K(18956K), 0.0085937 secs]
[Full GC 13782K->13613K(18956K), 0.0646513 secs]
2) Infinite Loops
Some memory leaks occur due to program errors in which infinite loop in the application code allocates new objects and adds them to a data structure accessible from outside the program loop scope. This type of infinite loops can sometimes occur due to multithreaded access into a shared unsynchronized data structure. These types of memory leaks manifest as fast growing memory leaks, where if the verbose GC data reports a sharp drop in free heap space in a very short time leads to an OutOfMemoryError.
Friends please add more to this post... dying to see more in this post....
Simple performance improvement suggestions.
- Use Boolean.valueOf(b) instead of new Boolean(b)
Note: however, some classes use a flag and rely on new Boolean() object being
different. A bad practice
synchronized(myInRelServFlg) {
myInRelServFlg = new Boolean(theFlg.booleanValue());
}
- Avoid the use of new String(String)
- Avoid the use of a single character String in a string concatenation. Or better
yet use StringBuilder where possible. Most times the synchronization from
StringBuffer is not required. Sun just released StringBuilder in 1.5, an
unsynchronized variant of StringBuffer.
- Avoid the use of StringBuffer().toString() in string concatenation.
- Avoid creating temproary objects to convert to a String or from a String. E.g. new
Integer(int).toString() and new Integer(String).intValue()
- Use constants for zero length arrays rather than creating the dynamically. Note:
however, some classes use zero length array objects for locks. A bad practice
terminationLock = new int[0];
- Avoid the use of loop to copy arrays, use System.arraycopy() instead.
- Avoid creating an instance of a class just to get the classes name. e.g.
(new java.sql.Date(123456)).getClass().getName ()
-About the history of Vector: Vector was in the 1.0 libraries
By the time of 1.2 ArrayList had come along and people were switching to it for
better performance. Vector was synchronised and because of that slower than the
unsynchronised ArrayList.
By the time of 1.4 however the synchronisation mechanism was much much better -
and Vector actually had a slight performance advantage over ArrayList.
-Performance with inner classes: When considering whether to use an inner class,
keep in mind that application startup time and memory footprint are typically
directly proportional to the number of classes you load. The more classes you
create, the longer your program takes to start up and the more memory it will take.
As an application developer one has to balance this with other design constraints
the person may have. I am not suggesting you turn your application into a single
monolithic class in hopes of cutting down startup time and memory footprint — this
would lead to unnecessary headaches and maintenance burdens.
Does anyone have any comments or other suggestions?
Monday, October 29, 2007
Google Tip: Use a Colon
site:URL and search term. As in, site:www.pcmag.com "wireless router." Insiders point out that this modifier is even stronger if you drop the www. You can also drop the domain name entirely and search, for example, only .gov sites.
define:word. This brings up definitions, related phrases, and offers to translate the word.
filetype:file extension and search term. It may be obvious, but this lets you search for files with a certain extension, such as PPT for a PowerPoint presentation on your topic.
Thursday, October 25, 2007
Insufficient memory problem with StringBuffer
Lets have a look of the constructor of string buffer
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
public StringBuffer() {
super(16);
}
Suppose you are creating objects of type StringBuffer in a loop, no of objects may change depnding upon the input. Every time it will create object to store at least 16 characters, you may not need all the 16, in that case remaining space will be unused and cannout be allocated for other purpose.
At some point these unused memory location may lead to Out of memory problem.
Instead of that we can use another constructor
Constructs a string buffer with no characters in it and the specified initial capacity.
public StringBuffer(int capacity) {
super(capacity);
}
Wednesday, October 24, 2007
Java Class Loaders
Further, the J2EE architecture makes uses of the class loaders to the fullest. Almost every component of J2EE is the dynamically loaded by the application server.
In a JVM, each and every class is loaded by some instance of a java.lang.ClassLoader. The ClassLoader class is located in the java.lang package and developers are free to subclass it to add their own functionality to class loading.
JVM creates an instance of java.lang.Class for every data type loaded into memory. The instance of this java.lang.Class is also stored on heap like any other object. Every object in Java contains a reference to this Class object of its data type. The getClass() method can be used to obtain the associated Class object. The getClass() method is inherited from the java.lang.Object hence available in every class.
Lets see an example of Dynamic class loading
public class DynamicLoader
{
public static void main(String[] args) throws Exception
{
Class toRun = Class.forName(args[0]);
String[] newArgs = scrubArgs(args);
Method mainMethod = findMain(toRun);
mainMethod.invoke(null, new Object[] { newArgs });
}
private static String[] scrubArgs(String[] args)
{
String[] toReturn = new String[args.length-1];
for (int i=1; i<args.length; i++)
{
toReturn[i-1] = args[i].toLowerCase();
}
return toReturn;
}
private static Method findMain(Class clazz) throws Exception
{
Method[] methods = clazz.getMethods();
for (int i=0; i<methods.length; i++)
{
if (methods[i].getName().equals("main"))
return methods[i];
}
return null;
}
}
public class Echo
{
public static void main (String args[])
{
for (int i=0; i<args.length; i++)
{
System.out.println("Echo arg"+i+" = "+args[i]);
}
}
}
Running DynamicLoader
>java DynamicLoader ECHO One Two Three
And the output is
Echo arg0 = One
Echo arg1 = Two
Echo arg2 = Three
As you can see, DynamicLoader created an instance of the Echo class, and called its main method, all without having any direct reference to Echo itself. In O-O parlance, this means that DynamicLoader is completely decoupled from Echo; there are no explicit dependencies between these two classes.
Class.forName(). In most of these systems, the code to do the run-time loading comes through the method forName on the class java.lang.Class; its use is demonstrated in the DynamicLoader code, above. Class.forName attempts to load the class whose name is given in its only argument, and returns the Class instance representing that class. In the event that the Class could not be found, resolved, verified, or loaded, Class.forName throws one of several different Exceptions.
CLASS LOADER
Now that we know java.lang.Class, it’s easy to comprehend the class loader of Java, which is a type of java.lang.Classloader (or its sub types).
The purpose of a class loader is to load the byte codes in ".class" file, and build the java.lang.Class object corresponding to the loaded type on JVM heap memory.
The java.lang.Class object is used to create objects requested by the programs.
Java has hierarchy of class loaders linked in a chain of parent-child relationship. Every class loader in Java, except the bootstrap class loader, has a parent class loader. At top of the parent-child chain is the bootstrap class loader.
Most java programs have at least 3 class loaders active behind the scenes. They are as follows
Bootstrap or Primordial Class loader: Class loader is responsible for loading only the core Java API (e.g. classes files from rt.jar). Since the core classes are required to bootstrap any Java program the class loader is called bootstrap class loader. This is root of all the class loader hierarchy in a java application.
Extension Class loader: Class loader responsible for loading classes from the Java extension directory (i.e. classes or jars in jre/lib/ext of the java installation directory). This class loader is responsible for loading the "installed extensions". Bootstrap class loader is the parent of this class loader.
System class loader or Application class loader: Class loader responsible for loading classes from the java class path (i.e. class directories or jars present in CLASSPATH environment variable of the Operating System). Extension class loader is the parent of this class loader. This class loader is by default the parent of all the custom/user defined class loaders in a java application.
The class loader subsystem involves many other parts of the Java virtual machine and several classes from the java.lang library. For example, user-defined class loaders are regular Java objects whose class descends from java.lang.ClassLoader. The methods of class ClassLoader allow Java applications to access the virtual machine's class loading machinery. Also, for every type a Java virtual machine loads, it creates an instance of class java.lang.Class to represent that type. Like all objects, user-defined class loaders and instances of class Class reside on the heap. Data for loaded types resides in the method area.
This use of dynamic runtime loading is the heart of Java Application Servers like the Java2 Enterprise Edition reference implementation, Enterprise JavaBeans, and the Servlet Specification. In each one of these architectures, at the time the application server is compiled, it knows nothing about the code that will be attached to it.
Instead, it simply asks the user for a classname to load, loads the class, creates an instance of the class, and starts making method calls on that instance. (It does so either through Reflection, or by requiring that clients implement a particular interface or class, like GenericServlet in the Servlet spec, or EJBObject in the EJB spec.)
The class loader subsystem is responsible for more than just locating and importing the binary data for classes. It must also verify the correctness of imported classes, allocate and initialize memory for class variables, and assist in the resolution of symbolic references. These activities are performed in a strict order:
1.Loading: finding and importing the binary data for a type
2.Linking: performing verification, preparation, and (optionally) resolution
a. Verification: ensuring the correctness of the imported type
b. Preparation: allocating memory for class variables and
initializing the memory to default values
c. Resolution: transforming symbolic references from the type into direct
references.
3.Initialization: invoking Java code that initializes class variables to their
proper starting values.
Wednesday, October 17, 2007
Custom String Values for Enum
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
-------------
this is one
this is two
Another interesting fact is, once you override toString() method, you in effect turn each element into an anonymous inner class. So after compiling the above enum class, you will see a long list of class files:
MyType.class
MyType$1.class
MyType$2.class
Heroku Custom Trust Store for SSL Handshake
Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...
-
Multi-Tenancy with the SaaS based model does not bring any change on the application layer as multiple services deployment of application w...
-
I have a class which is not serializable. If i will try to serialize the object of it than i am going to get exception "java.io.NotSer...
-
Raspberry Pi is an awesome and interesting . I was totally astonished after knowing about it from one of my friend and colleague "Ale...