Tuesday, October 7, 2014

How To Resolve "Java compiler level does not match the version of the installed Java project facet." Issue in Eclipse, STS tool or Eclipse Based Tools

                  I have faced this issue during the Java 7 upgrade from Java 6 into one of our application. You will face this issue suppose if your application or project built on lower versions of Java (in my case it is Java 1.6) and you are trying to upgrade it to the Higher versions of Java (in My case it is Java 1.7), then Eclipse will throw this error in the tool. You will face this error even after changing the compiler version from build path. To fix this issue Follow the Below Mentioned Steps.


1.  Open the 'Markers' Tab at the bottom of the eclipse or STS tool beside the 'Properties' Tab. (as shown in the below figure)




2. Right Click on the Error as mentioned in the below figure. in The context menu click on the 'Quick Fix' item as shown below in the figure.



3. Select the correct Java Project Facet from the 'Quick Fix' Window. and click on the 'Finish' Button.



4.  After Clicking on 'Finish' button you cannot see the error. Please check the figure below for the result.



That's it. It is that simple...?


Saturday, October 4, 2014

Java Important Links

Java Performance Checklist

Specify the required performance.
  • Ensure performance objectives are clear.
  • Specify target response times for as much of the system as possible.
  • Specify all variations in benchmarks, including expected response ranges (e.g., 80% of responses for X must fall within 3 seconds).
  • Include benchmarks for the full range of scaling expected (e.g., low to high numbers of users, data, files, file sizes, objects, etc.).
  • Specify and use a benchmark suite based on real user behavior. This is particularly important for multi-user benchmarks.
  • Agree on all target times with users, customers, managers, etc., before tuning.


Make your benchmarks long enough: over five seconds is a good target.
  • Use elapsed time (wall-clock time) for the primary time measurements.
  • Ensure the benchmark harness does not interfere with the performance of the application.
  • Run benchmarks before starting tuning, and again after each tuning exercise.
  • Take care that you are not measuring artificial situations, such as full caches containing exactly the data needed for the test.


Break down distributed application measurements into components, transfer layers, and network transfer times.

Tune systematically: understand what affects the performance; define targets; tune; monitor and redefine targets when necessary.
  • Approach tuning scientifically: measure performance; identify bottlenecks; hypothesize on causes; test hypothesis; make changes; measure improved performance.
  • Determine which resources are limiting performance: CPU, memory, or I/O.
  • Accurately identify the causes of the performance problems before trying to tune them.
  • Use the strategy of identifying the main bottlenecks, fixing the easiest, then repeating.
  • Don't tune what does not need tuning. Avoid "fixing" non-bottlenecked parts of the application.
  • Measure that the tuning exercise has improved speed.
  • Target one bottleneck at a time. The application running characteristics can change after each alteration.
  • Improve a CPU limitation with faster code and better algorithms, and fewer short-lived objects.
  • Improve a system-memory limitation by using fewer objects or smaller long-lived objects.
  • Improve I/O limitations by targeted redesigns or speeding up I/O, perhaps by multi-threading the I/O.


Work with user expectations to provide the appearance of better performance.
  • Hold back releasing tuning improvements until there is at least a 20% improvement in response times.
  • Avoid giving users a false expectation that a task will be finished sooner than it will.
  • Reduce the variation in response times. Bear in mind that users perceive the mean response time as the actual 90th percentile value of the response times.
  • Keep the user interface responsive at all times.
  • Aim to always give user feedback. The interface should not be dead for more than two seconds when carrying out tasks.
  • Provide the ability to abort or carry on alternative tasks.
  • Provide user-selectable tuning parameters where this makes sense.
  • Use threads to separate out potentially blocking functions.
  • Calculate "look-ahead" possibilities while the user response is awaited.
  • Provide partial data for viewing as soon as possible, without waiting for all requested data to be received.
  • Cache locally items that may be looked at again or recalculated.


Quality-test the application after any optimizations have been made.


• Document optimizations fully in the code. Retain old code in comments.

Be-Aware of the Performance of the String Concatenation...

                 The string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.

For example, consider the following method that constructs a string representation of a billing statement by repeatedly concatenating a line for each item:


// In-appropriate use of string concatenation - Hits Performance drastically!

public String statement() {
     String res = "";
     for (int i = 0; i < numOfItems(); i++)
      res += lineOfItem(i); // String concatenation
      return res;
}

                 This method performs very slow if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. (The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete.)

public String statement() {
      StringBuilder sb = new StringBuilder(numItems() * LINE_WIDTH);
      for (int i = 0; i < numOfItems(); i++)
       sb.append(lineOfItem(i));
      return sb.toString();
}

                The difference in performance is dramatic. If numOfItems returns 100 and lineOfItem returns a constant 80-character string, the second method is 85 times faster than the first on my machine. Because the first method is quadratic in the number of items and the second is linear, the performance difference is even more dramatic for larger numbers of items. Note that the second method pre-allocates a StringBuilder large enough to hold the result. Even if it is retuned to use a default-sized StringBuilder, it is still fifty times faster.

                The moral is simple: don’t use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuilder’s append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.

Saturday, September 27, 2014

Some Important Facts About Core Java

  1. There are 4 important OOPS concepts in Java : Inheritance, Abstraction, Encapsulation and Polymorphism.
  2. There are two types of variables in Java : Primitive types and Object Types
  3. The default value of Boolean is false (the same applies for the Wrapper class too).
  4. Marker interface is the one which doesn't contains any methods, it is like empty interface.
  5. You cannot override the 'main' method of the Java, even-though if you try to do so it will not give any exception, program compiles and executes fine. The reason is : 'main' method is of type static. Static methods are class level methods. Even-though it looks like method overriding, it is not overriding. These are two different method with respect to the corresponding class.
  6. You can Overload the 'main' method of Java, it is valid in Java.
  7. You can have only one 'Public' class and any number of non-public classes in any java source file.
  8. Inheritance is an example for IS-A relationship.
  9. Composition is an example for HAS-A relationship.
  10. You can have abstract class without any abstract methods.
  11. The use of abstract class without any abstract method : a) Whenever you  don't want to direct instantiation of the class, b) Whenever you want to add abstract future at later point of time which you are not aware currently, Otherwise I don't see any usage of such class.
  12. String class is immutable and thread-safe. The reason is , whenever we create String object mentioning some string literal either inside the constructor or direct literal, first it checks in the String constant pool whether that string literal is available or not. If available then it will not create the new instance inside the constant pool instead it points reference to the same string constant. In this case this string might be referenced by many different reference variables. Suppose you make changes to this string value it will alter all the referenced string variables by breaking the actual behavior. Because of this reason String class implemented as Final & Immutable one.
  13. If you want to update your string frequently and dynamically, in case you need to modify your string based on some scenario then you can either go With StringBuffer or StringBuilder based on either for Multithreaded application or Single threaded application. StringBuffer and StringBuilder both classes are same in behavior and functionality except the fact that, StringBuffer class is Synchronized and StringBuilder class non-synchronized.
  14. The efficient way of creating String object is : String str="abcd";, the reason is it creates instance only String Constant Pool and refer it through the reference variable 'str'. On other case, whenever you create String object using 'new' operator as : String str=new String("abcd");, in this case instance will be created in the heap and as well as in the String constant pool if the same string doesn't exist already, else it refers the existing string instance from the pool.

Still There are many to add, I will be updating this post in coming days....

Thursday, September 25, 2014

Rules for Overloading the Method in Java

  1. You can overload a method by changing its signature. method signature is made of number of arguments, type of arguments and order of arguments.
  2. Return type is not a part of method signature, so changing method return type means no overloading unless you change argument with return type.
  3. A method can be overloaded in the same class or in a subclass. if class A defines a display(float i) method, the subclass B could define a display(String s) method without overriding the super-class version that takes an int. So two methods with the same name but in different classes can still be considered overloaded, if the subclass inherits one version of the method and then declares another overloaded version in its class definition.

Rules for Overriding the Method in Java

  1. The argument list must exactly same that of the overridden method. If they don't match, you can end up with an overloaded method.
  2. The return type must be the same as, or a sub-type of, the return type declared in the original overridden method in the super-class (also called co-variant return type).
  3. Instance methods can be overridden only if they are inherited by the subclass.
  4. A subclass within the same package as the instance's super-class can override any super-class method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).
  5. The overriding method can throw any unchecked (run-time) exception, regardless of whether the overridden method declares the exception.
  6. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-run-time exception unless it's a subclass of FileNotFoundException.
  7. You cannot override a method marked final.
  8. You cannot override a method marked static.
  9. If a class is not inherited, you cannot override its methods.

Wednesday, September 24, 2014

How To Increase PermGenSpace Of Eclipse ?

If you see java.lang.OutOfMemoryError: PermGen space errors, you need to increase the permanent generation space available to Eclipse.
PermGen is the permanent generation of objects in the VM (Class names, internalized strings, objects that will never get garbage-collected). An easy, if somewhat memory-hungry fix is to enlarge the maximum space for these objects by adding,

“-XX:MaxPermSize=128M”

as an argument to the JVM when starting Eclipse. The recommended way to do this is via your eclipse.ini file.
Alternatively, you can invoke the Eclipse executable with command-line arguments directly, as in

“eclipse [normal arguments] -vmargs -XX:PermSize=64M -XX:MaxPermSize=128M [more VM args]”

Note: The arguments after -vmargs are directly passed to the VM. Run java -X for the list of options your VM accepts. Options starting with -X are implementation-specific and may not be applicable to all JVMs (although they do work with the Sun/Oracle JVMs).

Eclipse and Sun VMs on Windows


Eclipse 3.3 and above supports an argument to the launcher: --launcher.XXMaxPermSize. On Windows, Eclipse ships with the following lines in the eclipse.ini file:
    
          “--launcher.XXMaxPermSize=256m”

With the above arguments, if the VM being used is a Sun VM and there is not already a -XX:MaxPermSize= VM argument, then the launcher will automatically add -XX:MaxPermSize=256m to the list of VM arguments being used. The Eclipse launcher is only capable of identifying Sun VMs on Windows.
The option --launcher.XXMaxPermSize is something that the launcher reads (not the JVM); it tells the launcher to automatically size the JVM's perm gen if it (the launcher) detects a Sun JVM that supports that option. This alleviates the need to put it under -vmargs (where non-Sun JVM's could fail because they don't understand that option).

Note: Eclipse 3.6 and below on Windows has a bug with Oracle/Sun JDK 1.6.0_21 (July 2010) where the launcher cannot detect an Oracle/Sun VM, and therefore does not use the correct PermGen size. If you are using either of this version, add the -XX flag to the eclipse.ini as described above.

Note: Eclipse 3.3.1 has a bug where the launcher cannot detect a Sun VM, and therefore does not use the correct PermGen size. It seems this may have been a known bug on Mac OS X for 3.3.0 as well. If you are using either of these platform combinations, add the -XX flag to the eclipse.ini as described above.

Sorting the list of objects in Java

This article will explain about sorting the collection of objects. The document will explain how to sort list or set of objects placed in a collection and also what are the pre-requisites to sort any list or set which is having the list of objects.

You can sort List collections using the java.util.Collections.sort() method. You can sort these two types of List's.

1.   List
2.   LinkedList

Sorting Objects by their Natural Order


To sort a List you do this:


List list = new ArrayList();
//add elements to the list
Collections.sort(list);

When sorting a list like this the elements are ordered according to their "natural order". For objects to have a natural order they must implement the interface java.lang.Comparable. In other words, the objects must be comparable to determine their order. Here is how the Comparable interface looks:

public interface Comparable<T> {
  int compareTo(T o);
}

The compareTo() method should compare this object to another object, return an int value. Here are the rules for that int value:


  • Return a negative value if this object is smaller than the other object
  • Return 0 (zero) if this object is equal to the other object.
  • Return a positive value if this object is larger than the other object.

There are a few more specific rules to obey in the implementation, but the above is the primary requirements. Check out the JavaDoc for the details.

Let's say you are sorting a List of String elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the compareTo() method.

When you implement the compareTo() method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.

Sorting Objects Using a Comparator

Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a Comparator instead. Here is how you sort a list using a Comparator:

List list = new ArrayList();
//add elements to the list
Comparator comparator = new SomeComparator();
Collections.sort(list, comparator);

Notice how the Collections.sort() method now takes a java.util.Comparator as parameter in addition to the List. This Comparator compares the elements in the list two by two. Here is how the Comparator interface looks:

public interface Comparator<T> {
    int compare(T object1, T object2);
}

The compare() method compares two objects to each other and should:
  • Return a negative value if object1 is smaller than object2
  • Return 0 (zero) if objec1 is equal to object2.
  • Return a positive value if object1 is larger than object2.

There are a few more requirements to the implementation of the compare() method, but these are the primary requirements. Check out the JavaDoc for more specific details.

Here is an example Comparator that compares two fictive Employee objects:


public class MyComparator<Employee> implements Comparator<Employee> {
    public int compare(Employee emp1, Employee emp2){
       if(emp1.getSalary() <  emp2.getSalary()) return -1;
       if(emp1.getSalary() == emp2.getSalary()) return 0;
       return 1;
    }
}

A shorter way to write the comparison would be like this:


public class MyComparator<Employee> implements Comparator<Employee> {
    public int compare(Employee emp1, Employee emp2){
       return emp1.getSalary() - emp2.getSalary();
    }
}

By subtracting one salary from the other, the resulting value is automatically either negative, 0 or positive.

If you want to compare objects by more than one factor, start by comparing by the first factor (e.g. first name). Then, if the first factors are equal, compare by the second factor (e.g. last name, or salary) etc.