Saturday, November 12, 2011

Does java really allows Pointers ?? why can't it ? ?

Hi Guys,

I need response from all the Java experts. After reading this topic you will come to  a conclusion that java supports Pointers Arithmetic. Actually java 1.5 supports java Pointer Arithmetic. JDK 1.5 has the most disastrous java class called sun.misc.Unsafe which allow you to access the direct memory.
Please execute the following Code and your JVM will get crashed.

Please hang on a minute if java does not support  pointers it should throw Null Reference Exception. but JVM always throw Null Pointer Exception.

Think ..... Think ...... Think....... Think  ....Think..... Think........ and enjoy the below code...

import sun.misc.Unsafe;
import java.lang.reflect.Field;

public class TestPointers {
    public static void main(String[] args) throws Exception {
         Unsafe unsafe = getUnsafe();
         System.out.println("Unsafe = " + unsafe);
         System.out.println(" addressSize() = " + unsafe.addressSize());
         System.out.println(" pageSize() = " + unsafe.pageSize());
         System.out.println(" pageSize() = " + unsafe.pageSize());
         try {
             unsafe.putByte((long) 0xa000, (byte) 47);
         } catch(Throwable e) {
             System.out.println("IN THE CATCH BLOCK");
             e.printStackTrace();
         } finally {
             System.out.println("IN THE FINALLY BLOCK");
         }
         System.exit(0);
    }

     public static Unsafe getUnsafe() {
         Unsafe unsafe = null;
         try {
             Class uc = Unsafe.class;
             Field[] fields = uc.getDeclaredFields();
             for(int i = 0; i < fields.length; i++) {
                 if(fields[i].getName().equals("theUnsafe")) {
                     fields[i].setAccessible(true);
                     unsafe = (Unsafe) fields[i].get(uc);
                     break;
                 }
             }
         } catch(Exception ignore) {
     }
     return unsafe;
     }
   }



resource:
http://knol.google.com/k/pointers-in-java#

http://www.docjar.com/docs/api/sun/misc/Unsafe.html

Actually it s a bug in jdk 1.5  please read the following link


http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4420961

No comments:

Post a Comment