-3

I just want to know these two libraries use system functionality?

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

int ps = un.pageSize();
System.out.println("Page size: " + ps);
randers
  • 5,031
  • 5
  • 37
  • 64
arezoo
  • 1

1 Answers1

1

This code is not safe and not cross-platform-compatible.

  • The way you are getting the Unsafe itself is public supported Java API from the package java.lang.reflect. This code will run on all platforms, with all implementations of JVMs, because it is part of Java's public API.
  • The object un you are getting using the public supported API itself is not present on any JVMs other than the Oracle/Sun JVM, because it's private API to that JVM implementation. For example, your code will not run on the IBM JVM, since sun.misc.Unsafe will not be present there.

I think the Java 8 javac compiler by Oracle/Sun will even warn you when you compile your code (this compiler is not used if you build your project with Eclipse's built-in features), because you are using a private API.


Yes, your solution will return you the native memory page size, but it will possibly not run on all platforms.

randers
  • 5,031
  • 5
  • 37
  • 64
  • ok ,according your explanation I got that this libraries use system function,am I right?so Is there any way to get page size without system functions like create array ? – arezoo Dec 26 '15 at 10:10
  • What do you mean by "system function"? Yes, this will return you the native page size. – randers Dec 26 '15 at 10:14
  • In my exercise for OS lesson ; I should measure page size without use prepare function for it . and i don't have idea ! it was my point to say "system function" – arezoo Dec 26 '15 at 10:24
  • Yes, your code will use the system functions. It returns what is happening in the core, in the native part, however you want to call it. http://stackoverflow.com/a/19093391/4464702 Look here for a detailed report on what `sun.misc.Unsafe.pageSize()` does. **You are doing it correctly in your code, as long as you don't care about portability. For your programming lessons this is the correct solution.** – randers Dec 26 '15 at 10:30
  • If you care a little bit about my effort, consider clicking the checkmark and the upvote button next to my answer. – randers Dec 26 '15 at 10:33