Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the instance of sun.misc.Unsafe?

Tags:

java

unsafe

How do I get the instance of the unsafe class?

I always get the security exception. I listed the code of the OpenJDK 6 implementation. I would like to mess around with the function sun.misc.Unsafe offers to me, but I always end up getting the SecurityException("Unsafe").

public static Unsafe getUnsafe() {
    Class cc = sun.reflect.Reflection.getCallerClass(2);
    if (cc.getClassLoader() != null)
        throw new SecurityException("Unsafe");
    return theUnsafe;
}

(Please don't try to tell me how unsafe it is to use this class.)

like image 949
Arne Avatar asked Oct 22 '12 01:10

Arne


People also ask

What is unsafe class in Java?

For example, Unsafe allows developers to. Directly access CPU and other hardware features. Create an object but not run its constructor. Create a truly anonymous class without the usual verification. Manually manage off-heap memory.

What is unsafe park in Java?

unsafe. park is pretty much the same as thread. wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits.

What is unsafe reflection?

Description. This vulnerability is caused by unsafe use of the reflection mechanisms in programming languages like Java or C#. An attacker may be able to create unexpected control flow paths through the application, potentially bypassing security checks.

Why is Java considered unsafe?

The Java programming language and Java software platform have been criticized for design choices including the implementation of generics, forced object-oriented programming, the handling of unsigned numbers, the implementation of floating-point arithmetic, and a history of security vulnerabilities in the primary Java ...


1 Answers

From baeldung.com, we can get the instance using reflection:

   Field f =Unsafe.class.getDeclaredField("theUnsafe");
   f.setAccessible(true);
   unsafe = (Unsafe) f.get(null);

Edit

The following is quoted from the description of the project where this code belongs to.

"The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven project, so it should be easy to import and run as it is."

like image 114
TiyebM Avatar answered Oct 11 '22 14:10

TiyebM