Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, January 2, 2014

org.osgi.framework.BundleException: Exception in org.eclipse.core.resources.ResourcesPlugin.start()

Today morning, one of my colleague was reported that, his eclipse is not launching and It throws below error.

MESSAGE An error occurred while automatically activating bundle
org.eclipse.core.resources (26).
!STACK 0
org.osgi.framework.BundleException: Exception in
org.eclipse.core.resources.ResourcesPlugin.start() of bundle org.eclipse.core.resources.
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.s tartActivator
(BundleContextImpl.java:1028)

I have verified all the plugins, and could not see any issue with them. So where is the problem then?

I could solve the problem with Option (2).

Option 1: Try launching eclipse in clean mode. This did not work in my case, it was throwing an error before it asks for workspace selection.
> eclipse -clean

Option 2: Delete .metadata/.plugins/org.eclipse.core.resources/.snap file workspace directory.

Option 3: Most of the time option (2) will work, if it's not working, try to delete all files from .metadata/  folder.

After launching your eclipse, you will not find your old projects and workspace preference settings, you need to re-import into eclipse workspace and need to configure eclipse preferences.
  
Why this would have happened?
As per my understanding, this happens if you closed your eclipse forcefully, shutdown the system forcefully before eclipse closes or some files in workspace metadata would have been modified.
  
What is this .snap files contain ?
*.snap files represent the changes in workspace state of the IDE during the runtime. This is mostly for eclipse crash recovery plan. When a crash happens these files are used to recover the state of eclipse workspace.

While Eclipse is running, information about what has changed in the workspace is incrementally logged into various "snapshot" files (including .snap). On normal Eclipse shutdown, the complete workspace state is saved and the .snap files are deleted. When Eclipse crashes, the snapshot files are used during the next startup to recover from the crash.





Enable Eclipse verbose for troubleshooting

Have you ever wanted to trace what happens when you start an eclipse, or wanted to check what are the classes are loading during start up or while performing certain action.

Just to mention my use case, I was facing the below problem,

java.lang.LinkageError: loader constraint violation: when resolving method "com.kk.MUtils.logDebug(Lorg/apache/log4j/Logger;Ljava/lang/String;)V" the class loader (instance of java/net/FactoryURLClassLoader) of the current class, com/kk/common/KHttpServletRequestWrapper, and the class loader (instance of org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader) for resolved class, com/kk/MUtils, have different Class objects for the type com.kk.MUtils.logDebug(Lorg/apache/log4j/Logger;Ljava/lang/String;)V used in the signature


From the above error, we can understand that Logger class is the issue, it was loaded multiple times by different class loaders and they could not link each other since both of them are loaded by different class loaders.

My call request involves multiples plug-ins, I wanted to check which of the plugins are loading Logger class to identify a root cause of the problem.

To get all that info, we can make use of java verbose vm parameter.

so how do we enable that ?

By default, eclipse launches with javaw.exe process, since it's a window thread so you will not be able to see any verbose messages.

Step 1:  Add below VM parameter in eclipse.ini file. By default, eclipse will have javaw.exe, modify it to java.exe
-vm
C:/KK/jdk1.6.0_32/bin/java.exe

Step 2: Pass verbose parameter during the eclipse launch.
> eclipse -verbose

This will open up a console window to display all log messages.

Write it to a file:
To write log messages to a file, use below command.
>eclipse -verbose  >mytracelog.txt

You can find this file in eclipse root directory.

You can also provide complete file system path, if required.
>eclipse -verbose  >C:\kk\logs\mytracelog.txt

You can also add verbose parameter in eclipse.ini vm parameters.
Example:
-vm
C:/KK/jdk1.6.0_32/bin/java.exe
-vmargs
-Xms128m
-Xmx512m
-verbose




Java Decompiler

Decompiler is to convert java .class files into java source files. This would be useful, If you don't have source code of a particular jar file, but you wanted to check the source of it. 

I am using below Java decompiler for last few years, and it was very much useful to me.

You can directly download:

If you are working with eclipse, please find the update site below.


Thursday, December 26, 2013

JStack - Generating stack dump


This would be useful to analyze a root cause, when an application has suddenly stopped working or not responding . There could be a some kind of deadlock or waiting processes or something else. 
JStack would help in getting the stack dump to a currently running java process.

JStack comes along with JDK kit, need not to install separately.

Go to command prompt, type below command with java process id.

>jstack <pid>

To identify the java process id, you can 'jps' command.

>jps  => this will list out the all java process id's.
Output:
5730 main  => this is my java process id.
10800 jps
8732

To get more details about which process ID belongs to which process use below command
> jps -ml

To get the additional information about the locks.
>jps  -l  <pid>

Jstack can also be used to get the thread dump for remotely running processes.
>jps  <remote host name/ip address>

To write stack dump to a file:
>jstack -l 7840 >  D:\Test\kklog.txt

">" is important to write into a file.


Some useful resources on this.
http://www.ibm.com/developerworks/library/j-5things8/
http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstack.html


Monday, December 9, 2013

UseCompressedOops flag with java

Recently one of colleague was unable to launch eclipse, it says ‘Java returned with exit code =1’ , we have tried lot of options by increasing heap memory and all, but finally what worked out for him was by setting a  UseCompressedOops flag in eclipse configuration file.

He was using 64 bit machine and 64 bit JVM.

Here is the story, what compressed flag does.

The -XX:+UseCompressedOops option can improve performance of the 64-bit JRE when the Java object heap is less than 32 gigabytes in size. In this case, HotSpot compresses object references to 32 bits, reducing the amount of data that it must process.

Compressed oops is supported and enabled by default in Java SE 6u23 and later. In Java SE 7, use of compressed oops is the default for 64-bit JVM processes when -Xmx isn't specified and for values of -Xmx less than 32 gigabytes. For JDK 6 before the 6u23 release, use the -XX:+UseCompressedOops flag with the java command to enable the feature.

In summary:
Java version <6u23 - use command to set it.
Java version >=6u23 - by default enabled.
JDK7 - if -xmx not specified or -xmx <32GB => configured bydefault

You might have a question how does 64 bit pointer fits into 32 bit pointer, how it will be compressed. Please go through below link to understand more about it.

This is how JRocket JVM is compressing it, this will give us some understanding.





Java code to Java Heap

This is an excellent article which describes how Java 32 bit and 64 bit processes works with various primitives and objects in Java.

http://www.ibm.com/developerworks/opensource/library/j-codetoheap/index.html

Comparing 2 files


If you wanted to know whether 2 files is having same content or not, you need not to compare two files line by line, instead you can compare checksums of each file.

For this, you need to use Apache common-codec_1.7.jar file.




Example:


package com.kk;

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.codec.digest.DigestUtils;

public class CompareFiles {

public static boolean compare(String oldFile, String newFile) throws IOException {
FileInputStream fis1 = new FileInputStream(oldFile);
String oldmd5 = DigestUtils.md5Hex(fis1);// old file checksum
FileInputStream fis = new FileInputStream(newFile);
String latestmd5 = DigestUtils.md5Hex(fis); // new file checksum
return oldmd5.equals(latestmd5);
}
public static void main(String[] args) {
String oldFile = "D:\\Work\\test\\js\\kklibrary.js";
String newFile = "D:\\Work\\test\\kklibrary.js";
try {
boolean compare = compare(oldFile, newFile);
System.out.println("Both files are: "+ compare);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Thursday, October 24, 2013

Reading Windows registry values using java


This can be done using JNA(Java Native Access) library.

Use this link to download @ https://github.com/twall/jna#readme

Required jars: 

Piece of code to test:

Here I am trying to read Android installation path from windows registry.


public static void main(String[] args) {

try {
Map<String, Object> values = Advapi32Util.registryGetValues(HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Android SDK Tools");
for (String value : values.keySet()) {
System.out.println(value + "   " + values.get(value));

}
} catch (Exception e) {
e.printStackTrace();
}

}

public static void main(String[] args) {

try {
Map<String, Object> values = Advapi32Util.registryGetValues(HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Android SDK Tools");
for (String value : values.keySet()) {
System.out.println(value + "   " + values.get(value));

}
} catch (Exception e) {
e.printStackTrace();
}

}


Output:
Path   D:\Work\Android\adt-bundle-windows-x86-20130522\adt-bundle-windows-x86-20130522

Friday, October 18, 2013

Java VM PermGen space

The Java VM memory is split up to 3 memory spaces:

  • The Java Heap. Applicable for all JVM vendors, usually split between YoungGen (nursery) & OldGen (tenured) spaces.
  • The PermGen (permanent generation). Applicable to the Sun HotSpot VM only (PermGen space will be removed in future Java 7 or Java 8 updates)
  • The Native Heap (C-Heap). Applicable for all JVM vendors.

The Java HotSpot VM permanent generation space is the JVM storage used mainly to store your Java Class objects.  The Java Heap is the primary storage that is storing the actual short and long term instances of your PermGen Class objects.

The PermGen space is fairly static by nature unless using third party tool and/or Java Reflection API which relies heavily on dynamic class loading.
It is important to note that this memory storage is applicable only for a Java HotSpot VM; other JVM vendors such as IBM and Oracle JRockit do not have such fixed and configurable PermGen storage and are using other techniques to manage the non Java Heap memory (native memory).

Below diagram showcases various heap memories and how we can configure them using vm arguments.




Finding java process id's

Go to command prompt and type jps, this will provide the currently running java process id's in your system.




Troubleshooting Memory Leaks

http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-VM/html/memleaks.html


Meaning of OutOfMemoryError

One common indication of a memory leak is the java.lang.OutOfMemoryError error. This error is thrown when there is insufficient space to allocate an object in the Java heap or in a particular area of the heap. The garbage collector cannot make any further space available to accommodate a new object, and the heap cannot be expanded further.
When the java.lang.OutOfMemoryError error is thrown, a stack trace is printed also.
java.lang.OutOfMemoryError can also be thrown by native library code when a native allocation cannot be satisfied, for example, if swap space is low.
An early step to diagnose an OutOfMemoryError is to determine what the error means. Does it mean that the Java heap is full, or does it mean that the native heap is full? To help you answer this question, the following subsections explain some of the possible error messages, with reference to the detail part of the message:

Sizing the Java heap


Size your Java heap so that your application runs with a minimum heap usage of 40%, and a maximum heap usage of 70%.
Introduction
An incorrectly sized Java heap can lead to OutOfMemoryError exceptions or to a reduction in the performance of the Java application.
If the Java heap is smaller than the memory requirements of the application, OutOfMemoryError exceptions are generated because of Java heap exhaustion. If the Java heap is slightly larger than the requirements of the application, garbage collection runs very frequently and affects the performance of the application.
You must correctly size the Java heap based on the real memory usage of the Java application.
Sizing the heap based on application memory utilization
Set the maximum Java heap size, using the -Xmx command-line option, to a value that allows the application to run with 70% occupancy of the Java heap.
The Java heap occupancy often varies over time as the load applied to the application varies. For applications where occupancy varies, set the maximum Java heap size so that there is 70% occupancy at the highest point, and set the minimum heap size, using the -Xms command line option, so that the Java heap is 40% occupied at its lowest memory usage. If these values are set, the Java memory management algortihms can modify the heap size over time according to the application load, while maintaining usage in the optimal area of between 40% and 70% occupancy.
Maximum possible heap size and maximum recommended heap size (32-bit Java)
The memory space provided by the operating system to the Java process varies by operating system and is used for two separate memory areas: the Java heap and the native heap. Because a finite amount of memory is provided by the operating system, and that memory is shared between the two heaps, the larger the amount of memory that is allocated to the Java heap, using the -Xmx setting, the smaller the native heap becomes. If the native heap is too small, an OutOfMemoryError occurs when it is exhausted, in the same way as for the Java heap.
PlatformAdditional optionsMaximum heap sizeRecommended heap size limitAdditional notes
AIXNone3.25 GB2.5 GBMaximum heap size is not required to be, but should ideally be, a multiple of 256 MB
LinuxNone2 GB1.5 GB
Hugemem Kernel3 GB2.5 GB
WindowsNone1.8 GB1.5 GB
/3GB1.8 GB1.8 GB
The table shows both the maximum Java heap possible and a recommended limit for the maximum Java heap size setting. The use of a maximum Java heap setting up to the recommended limit is unlikely to reduce the native heap size to a point that the native heap is exhausted.
Before setting a Java heap size greater than the recommended limit, you must understand the level of usage of the native heap, to ensure that the native heap does not become exhausted.
If you are running an application that has particularly high numbers of threads or makes heavy use of Java Native Interface (JNI) code, for example, Type 2 JDBC drivers, you might experience problems relating to the native heap with smaller Java heap sizes than the recommended limit.
Maximum possible heap size and maximum recommended heap size (64-bit Java)
When running 64-bit Java, the memory space provided by the operating system to the Java process is very large. You can therefore assume that no limit is imposed on the maximum size of the Java heap because of the contention of memory resource between the Java heap and the native heap.
Java heap size and amount of physical memory available
It is important to have more physical memory than is required by all of the processes on the machine combined to prevent paging or swapping. Paging reduces the performance of the system and affects the performance of the Java memory management system.
When increasing the Java heap size, ensure that enough unused physical memory is available on the machine to cover the increase. If sufficient physical memory is not available, either install additional memory or take into account the effect on overall performance that occurs.
This requirement does not apply to operating systems running on System z.

Size your Java heap so that your application runs with a minimum heap usage of 40%, and a maximum heap usage of 70%.



Understanding 32-bit vs. 64-bit systems with Java Heap

Tuesday, October 15, 2013

toArray Dynamic behaviour

public class ToArrayTest {

public static void main(String[] args) {

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");

//what happens here??, since I have allocated new String[0] for single element, will it return single element or all elements ??
String[] array = arrayList.toArray(new String[0]); 
System.out.println(array.length);

}
}


Output:  4


As per spec, it's going to create a new array, if it does not fit in.
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. 

Saturday, October 5, 2013

JProfiler could not detect java process id's

Reason could be very simple, as i mentioned in my previous post http://exploreeclipse.blogspot.in/2013/10/where-does-java-process-idspid-are.html

It looks for 'hsperfdata_<systemLoginName>'  folder in C:\Users\KK1205\AppData\Local\Temp\  directory.

If you could not find this file, just create a new directory with this name.

If you found it, but it's not in the format of what i have mentioned above, then you can rename it.

Other important thing here is, system login name(ex:KK1205 is correct, kk1205 is incorrect) should be in capital letters(That is what i have observerd it!)


Saturday, September 7, 2013

Three rules for effective exception handling in java

If we are dealing with exceptions basically it has to tell you the following things.

1. What went wrong ?
2. Where did it go wrong ?
3. Why did it go wrong ?

so, to address above points we need follow 3 golden rules of exception handling.

1.  Be specific on exception type  -> It should tell what went wrong, ex: file not found, connection not found

2. Throw early - > ex: if you are passing null file name to FileInputStream it throws null pointer exception, but this is not sufficient to the user, instead check whether it is null or not ,then throw an exception that "File name can't be empty".

3. Catch late- > Catch where you want to show it the user immediately. Don't log and catch at the API level or lower level, instead throw from api or lower level and catch at the UI layer or at the top layer.


https://today.java.net/pub/a/today/2003/12/04/exceptions.html




Monday, August 5, 2013

ObjectOutputSteam -reset() - OutOfMemory Issues

Have you ever faced heap memory issue with ObjectOutputSteam?  Then article would be very much useful to understand the internals and resolve the issue.

When you construct an ObjectOutputStream and an ObjectInputStream, they each contain a cache of objects that have already been sent across this stream. The cache relies on object identity, rather than the traditional hashing function. It is more similar to a java.util.IdentityHashMap than a normal java.util.HashMap. So, if you resend the same object, only a pointer to the object is sent across the network. This is very clever, and saves network bandwidth. However, the ObjectOutputStream cannot detect whether your object was changed internally or not, resulting in the Receiver just seeing the same object over and over again

In other way, If you send the different object every time, this will keep on storing in the cache handle and it will be keep growing, and at one point of time we might come across the heap memory issue since cache is huge and never cleared cache on the both the ends.

To avoid these kind of issues, we need to reset() the ObjectOutputStream, and this will clear the cache on the both ends. But, again this is a costly operation so we need to do it with some constrains. That will be mentioned below.

  ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
  oos.writeObject("my object data");
  oos.reset();

This will discard the state of any objects already written to the stream. The state is reset to be the same as a new ObjectOutputStream

Please go through the below java specialist article on this. Considering they might modify/delete from there site and so I have coped entire content here for my reference.

Article @ http://www.javaspecialists.eu/archive/Issue088.html

Same article content below.

Resetting ObjectOutputStream

A class with many mysteries is java.io.ObjectOutputStream. For instance, when and why should you reset the stream?
Let's look at an example. First we have class Person, which is the class that we want to send over the network:
public class Person implements java.io.Serializable {
  private final String firstName;
  private final String surname;
  private int age;

  public Person(String firstName, String surname, int age) {
    this.firstName = firstName;
    this.surname = surname;
    this.age = age;
  }

  public String toString() {
    return firstName + " " + surname + ", " + age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}
  
Next we have the code that Receives lots of Person objects and code that Sends them:
import java.net.*;
import java.io.*;

public class Receiver {
  public static void main(String[] args) throws Exception {
    ServerSocket ss = new ServerSocket(7000);
    Socket socket = ss.accept();
    ObjectInputStream ois = new ObjectInputStream(
        socket.getInputStream());
    int count=0;
    while(true) {
      Person p = (Person) ois.readObject();
      if (count++ % 1000 == 0) {
        System.out.println(p);
      }
    }
  }
}


import java.net.Socket;
import java.io.*;

public class Sender {
  public static void main(String[] args) throws IOException {
    long start = System.currentTimeMillis();
    Socket s = new Socket("localhost", 7000);
    ObjectOutputStream oos = new ObjectOutputStream(
        s.getOutputStream());
    Person p = new Person("Heinz", "Kabutz", 0);
    for (int age=0; age < 1500 * 1000; age++) {
      p.setAge(age);
      oos.writeObject(p);
    }
    long end = System.currentTimeMillis();
    System.out.println("That took " + (end-start) + "ms");
  }
}
The output was:
java Receiver:
  *snip*
  Heinz Kabutz, 0
  Heinz Kabutz, 0
  Heinz Kabutz, 0
  Heinz Kabutz, 0
  Heinz Kabutz, 0
  Heinz Kabutz, 0

java Sender:
  That took 19548ms
  
When we run this, we will see lots of People objects on the Receiver side, but all the age values will be 0, even though we changed the age on the Sender side. Why is this?
When you construct an ObjectOutputStream and an ObjectInputStream, they each contain a cache of objects that have already been sent across this stream. The cache relies on object identity, rather than the traditional hashing function. It is more similar to a java.util.IdentityHashMap than a normal java.util.HashMap. So, if you resend the same object, only a pointer to the object is sent across the network. This is very clever, and saves network bandwidth. However, the ObjectOutputStream cannot detect whether your object was changed internally, resulting in the Receiver just seeing the same object over and over again. You will notice that this was quite fast. We sent 1'500'000 objects in 19548ms (on my machine). (well, we only sent one object, and 1'499'999 pointers to that object).
There seemed to be some problem with sending the same Person object many times, especially if the contents of that Person changed. Due to the optimisation in ObjectOutputStream, only the pointer to the Person would be sent each time. So, what would happen if we simply sent a new Person each time? Let's try it out...
import java.net.Socket;
import java.io.*;

public class Sender2 {
  public static void main(String[] args) throws IOException {
    long start = System.currentTimeMillis();
    Socket s = new Socket("localhost", 7000);
    ObjectOutputStream oos = new ObjectOutputStream(
        s.getOutputStream());
    for (int age=0; age < 1500 * 1000; age++) {
      oos.writeObject(new Person("Heinz", "Kabutz", age));
    }
    long end = System.currentTimeMillis();
    System.out.println("That took " + (end-start) + "ms");
  }
}
This seems to run fine for a while, until we all of a sudden see an OutOfMemory error on both the Receiver and the Sender2. Someone once challenged regarding the pathetic speed of Java. They claimed that Java was so slow that the Garbage Collector could not even keep up with objects that were being read over the network. It sounded strange to me that Java should run out of memory so after some questioning, we traced the problem to the object cache growing in the Receiver and never being cleared. Since the Person objects are always distinct, they are put into the cache on both sides of the ObjectOutputStream. The Receiver's side cannot clear entries from the table, since it does not know which entries the Sender might send again. It then keeps on growing until the JVM runs out of memory.

Resetting ObjectOutputStream

One hack^H^H^H^Hsolution to the OutOfMemory problem is to every time that you send an object also reset the cache on both sides. Let's try out what that does to our performance:
import java.net.Socket;
import java.io.*;

public class Sender3 {
  public static void main(String[] args) throws IOException {
    long start = System.currentTimeMillis();
    Socket s = new Socket("localhost", 7000);
    ObjectOutputStream oos = new ObjectOutputStream(
        s.getOutputStream());
    for (int age=0; age < 1500 * 1000; age++) {
      oos.writeObject(new Person("Heinz", "Kabutz", age));
      oos.reset();
    }
    long end = System.currentTimeMillis();
    System.out.println("That took " + (end-start) + "ms");
  }
}
When I ran that, it worked without causing any OutOfMemory Errors, so I should be happy. But am I happy? I am old, after having to wait for 314242ms for it to complete, i.e. 16 times longer than with Sender. Sender was fast, but incorrect. Sender2 ran out of memory. Sender3 was correct, but slow. Is there no better way?
The problem with reset() is that it clears the cache of ALL objects, even constants such as the Strings "Heinz" and "Kabutz". So, we end up sending these constants over the network time and time again! Unfortunately the reset() is an all-or-nothing approach, so the entire cache will be lost. But perhaps, if we don't clear it all the time, we can get the advantage of speed and correctness? Let's try that out:
import java.net.Socket;
import java.io.*;

public class Sender4 {
  public static void main(String[] args) throws IOException {
    long start = System.currentTimeMillis();
    Socket s = new Socket("localhost", 7000);
    ObjectOutputStream oos = new ObjectOutputStream(
        s.getOutputStream());
    for (int age=0; age < 1500 * 1000; age++) {
      oos.writeObject(new Person("Heinz", "Kabutz", age));
      if (age % 1000 == 0) oos.reset();
    }
    long end = System.currentTimeMillis();
    System.out.println("That took " + (end-start) + "ms");
  }
}
Because I don't reset the cache on every call, Sender4 can avoid sending the Strings "Heinz" and "Kabutz" over the network 1'500'000 times in just 66015ms. Infact, it only has to send these Strings 1'500 times. If we reset the ObjectOutputStream too frequently, we will increase the network bandwidth, and if we do not reset it often enough, we will increase the burden of our Garbage Collector. Like all things in Java Performance Tuning, you have to set it to the correct number, not too big and not too little.


Wednesday, July 10, 2013

Determine windows is 32 or 64 bit using Java Programatically

import com.sun.servicetag.SystemEnvironment;

"os.arch" environment may not give you the correct architecture.
Let's try out.

public class OSArchLies {
  
  public static void main(String[] args) {
    
    // Will say "x86" even on a 64-bit machine using a 32-bit Java runtime
    SystemEnvironment env =   SystemEnvironment.getSystemEnvironment();
    final String envArch = env.getOsArchitecture();
    
    // The os.arch property will also say "x86" on a 64-bit machine using a 32-bit runtime
    final String propArch = System.getProperty("os.arch");
    
    System.out.println( "getOsArchitecture() says => " + envArch );
    System.out.println( "getProperty() says => " + propArch );
    
  }

}

Environment: Windows 7, 64 bit os, 32 bit JVM

Output:
getOsArchitecture() says => x86
getProperty() says => x86


Try this approach,

public class Windows32Or64bitCheck {

public static void main(String[] args) {
        boolean is64bit = false;
       
        System.out.println(System.getProperty("sun.arch.data.model", "?"));
        System.out.println(System.getProperty("os.arch")); // Please note, the os.arch property will only give you the architecture of the JRE, not of the underlying os. 
        System.out.println(System.getenv("ProgramFiles(x86)"));
        
        if (System.getProperty("os.name").contains("Windows")) {
            is64bit = (System.getenv("ProgramFiles(x86)") != null);
        } else {
            is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
        }
        System.out.println("is64bit: " + is64bit);
 }

}

Environment: Windows 7, 64 bit os, 32 bit JVM

Output:
32
x86
C:\Program Files (x86)
is64bit: true


This is the only way which i could find from Java( Using native C, there is a better and accurate way to achieve this) 

Using C, please follow below link

Other way I have learned recently, using Windows wmi service calls.
>  wmic OS get OSArchitecture


C:\Users\KH1205>wmic OS get OSArchitecture
OSArchitecture
64-bit

Try to run this command programatically using Java Runtime process.

Tuesday, June 4, 2013

Difference between equals() and == in Java?


What’s the difference between equals() and ==?

Before discussing the difference between “==” and the equals() method, it’s important to understand that an object has both a location in memory and a specific state depending on the values that are inside the object.

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:
String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");
    

Take a guess at what the code above will output. Did you guess that it will outputobj1==obj2 is TRUE? Well, if you did, then you are actually wrong. Even though the strings have the same exact characters (“xyz”), The code above will actually output:
 obj1==obj2 is FALSE

The “==” operator compares the objects’ location(s) in memory

Are you confused? Well, let us explain further: as we mentioned earlier, the “==” operator is actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory location. In other words, if both obj1 and obj2 are just different names for the same object then the “==” operator will return true when comparing the 2 objects. Another example will help clarify this:
String obj1 = new String("xyz");

// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;

if(obj1 == obj2)
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:
obj1==obj2 is TRUE

The equals() method

Now that we’ve gone over the “==” operator, let’s discuss the equals() method and how that compares to the “==” operator. The equals method is defined in the Object class, from which every class is either a direct or indirect descendant. By default, the equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory.
so, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations. This is the Java best practice for overriding the equals method – you should compare the values inside the object to determine equality. What value you compare is pretty much up to you. This is important to understand – so we will repeat it: by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.

An example of the equals() method being overriden
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal. Here is an example that will help clarify this:
String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");


This code will output the following:
obj1==obj2 is TRUE
As we discussed, Java’s String class overrides the equals() method to compare the characters in a string. This means that the comparison between the 2 String objects returns true since they both hold the string “xyz”. It should now be clear what the difference is between the equals() method and the “==” operator.

Other example is:
StringBuffer s1 = new StringBuffer("kondal");
StringBuffer s2 = new StringBuffer("kondal");
System.out.println(s3.equals(s4));  //false

Above comparison results 'false' because of StringBuffer has not overridden equals() method as like String class.So, equals() comparison on StringBuffer same as '==' comparison, since it looks for Object 'equals()' method.

String s3 = "kondal";
Now, System.out.println(s3.equals(s1));  //false

Above code also returns false,since 'equals() method in String class has the following criteria.

  public boolean equals(Object anObject) {
if (this == anObject) {
   return true;
}
if (anObject instanceof String) { // Here it fails, StringBuffer is not a instance of String class
   String anotherString = (String)anObject;
   int n = count;
   if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
   if (v1[i++] != v2[j++])
return false;
}
return true;
   }
}
return false;

    }


The following contracts should be satisfied while overriding 'equals() method.

It is reflexive: for any non-null reference value x, x.equals(x) should return true. 
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. 
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. 
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. 
For any non-null reference value x, x.equals(null) should return false. 

It is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes, but vice-versa may not be true