Java's Unsafe class

Anyone have experience using sun.misc.Unsafe ? I tried using it today and it’s giving an error when i run it.


import sun.misc.*;

public class UnsafeTester {
  private static final Unsafe unsafe = Unsafe.getUnsafe();
  public static void main(String[] args) {
    long ptr = unsafe.allocateMemory(512);
    try{
      unsafe.putChar(ptr,'a');
      unsafe.putChar(ptr,'b');
      System.out.println("Unsafe: " + unsafe.toString());
    }
    finally{
      unsafe.freeMemory(ptr);
    }
  }
}

java.lang.ExceptionInInitializerError
Caused by: java.lang.SecurityException: Unsafe
      at sun.misc.Unsafe.getUnsafe(Unsafe.java:68)
      at garbage.UnsafeTester.<clinit>(UnsafeTester.java:8)
Exception in thread "main" 

I’m not sure exactly how I should go about tackling this one so any help would be great. :wink:

Well, don’t use it ;D

There was a bug once upon a time :wink: when you could actually use it to wrec havoc (first beta1.4.0 or something like that) - they fixed that quite fast :slight_smile:

Ummmm… what is this class?

why does it curiously remind me of the structs discussion that was occurring in another thread somewhere?

And for future reference, where can I get information about the sun.misc.* classes?

Whatever it is, I suspect it is unsafe to use :slight_smile:

You’re really not supposed to use any of the sun.* classes for real use. They are subject to change at any moment, and are only available on Sun JVMs.

Check this page: http://www.jguru.com/faq/view.jsp?EID=448031

Cheers

Thanks for your help. The only reason I was curious about that Unsafe class was my friend wanted to make a stringBuffer class using JNI and it turned out being alot slower than even your normal stringbuffer. I’m guessing the JNI calls are expensive. so we went hunting in the nio classes and found no native methods and that lead to the Unsafe class. Only problem is that security exception that i’m getting. Guess it’s unusable at this point. :-/

You should have no need whatsoever to use Unsafe.
Got performance problems? You’ve written the code wrong. Time to run with the -Xprof flag methinks!

Cas :slight_smile:

yeah this is true. It was just something i was toying around with. ;D

When I allocate memory with the Unsafe class what exactly is it doing? I’m really just experimenting with the class. And the other thing is that when i call unsafe.addressSize() it always returns 4 for some odd reason. Anyone know how this class works? ???

[quote] And the other thing is that when i call unsafe.addressSize() it always returns 4 for some odd reason.
[/quote]
I suppose that it returns size of native platform pointer in bytes. So on 64-bit system you will probably get 8 as a return.

Good thinking. Thanks for the help

Unsafe is the underpinning to Native Byte Buffers

Thats really where you want to hit this.

JK