Java Direct Memory read and write examples

Source: Internet
Author: User

On the hotspot JVM, we are able to read and write directly to the memory. The Allocatememory method of this class is used to request the allocation of memory, and the Putaddress and GetAddress methods are used to read and write direct memory.

This article will give an example of direct read and write memory through Sun.misc.Unsafe.

Note: This is only an example of the possibility of using Sun.misc.Unsafe to read and write memory directly. However, there is no security guarantee, and a bit of negligence can cause the JVM to crash.

The three methods of the unsafe class: Allocatememory,putaddress and GetAddress are as follows:

Java code
  1. /**
  2. * Fetches a native pointer from a given memory address. If the address is
  3. * Zero, or does not point to a block obtained from {@link
  4. * #allocateMemory}, the results is undefined.
  5. *
  6. * <p> If The native pointer is less than bits wide, it's extended as
  7. * A unsigned number to a Java long. The pointer is indexed by any
  8. * Given byte offset, simply by adding this offset (as a simple integer) to
  9. * The long representing the pointer. The number of bytes actually read
  10. * from the target address maybe determined by consulting {@link
  11. * #addressSize}.
  12. *
  13. * @see #allocateMemory
  14. */
  15. public native long getaddress (long address);
  16. /** 
  17. * Stores A native pointer into a given memory address. If the address is
  18. * Zero, or does not point to a block obtained from {@link
  19. * #allocateMemory}, the results is undefined.
  20. *
  21. * <p> the number of bytes actually written at the target address maybe
  22. * Determined by consulting {@link #addressSize}.
  23. *
  24. * @see #getAddress (Long)
  25. */
  26. public native void putaddress (long address, long x);
  27. //wrappers for malloc, realloc, free:
  28. /** 
  29. * Allocates a new block of native memory, of the given size in bytes. The
  30. * Contents of the memory is uninitialized; They'll generally be
  31. * Garbage. The resulting native pointer would never be zero, and would be
  32. * aligned for all value types. Dispose of this memory by calling {@link
  33. * #freeMemory}, or resize it with {@link #reallocateMemory}.
  34. *
  35. * @throws IllegalArgumentException If the size is negative or too large
  36. * For the native size_t type
  37. *
  38. * @throws OutOfMemoryError If the allocation is refused by the system
  39. *
  40. * @see #getByte (Long)
  41. * @see #putByte (long, byte)
  42. */
  43. public native long allocatememory (long bytes);



1. Long allocatememory (long bytes)
Request to allocate memory
2. Long getaddress (long address) and void putaddress (long address, long X)
Read and write to direct memory.


because the access to this class is restricted, only classes in Rt.jar can use the unsafe function, and its construction method is private, so we cannot create an instance from new. However, an unsafe instance can be obtained by means of reflection.

Here is an example of a direct memory access:

Java code
  1. Import Java.lang.reflect.Field;
  2. Import Sun.misc.Unsafe;
  3. Public class Directmemoryaccess {
  4. public static void Main (string[] args) {
  5. /* 
  6. * Unsafe's constructor is private and cannot be obtained by new.
  7. *
  8. * Through reflection to get
  9. */
  10. unsafe unsafe = null;
  11. Field field = null;
  12. try {
  13. field = Sun.misc.Unsafe.  Class.getdeclaredfield ("Theunsafe");
  14. /* 
  15. * Private static final unsafe Theunsafe = new unsafe ();
  16. *
  17. * Because the field modifier is private static final,
  18. * Setaccessible must be set to true, otherwise it will be reported java.lang.IllegalAccessException
  19. */
  20. Field.setaccessible (true);
  21. unsafe = (unsafe) field.get (null);
  22. } catch (SecurityException e) {
  23. //TODO auto-generated catch block
  24. E.printstacktrace ();
  25. } catch (Nosuchfieldexception e) {
  26. //TODO auto-generated catch block
  27. E.printstacktrace ();
  28. } catch (IllegalArgumentException e) {
  29. //TODO auto-generated catch block
  30. E.printstacktrace ();
  31. } catch (Illegalaccessexception e) {
  32. //TODO auto-generated catch block
  33. E.printstacktrace ();
  34. }
  35. long onehundred = 100;
  36. byte size = 1;
  37. /* 
  38. * Call Allocatememory to allocate memory
  39. */
  40. Long memoryaddress = unsafe.allocatememory (size);
  41. /* 
  42. * Write 100 to Memory
  43. */
  44. Unsafe.putaddress (memoryaddress, onehundred);
  45. /* 
  46. * Read data in memory
  47. */
  48. Long readvalue = unsafe.getaddress (memoryaddress);
  49. System.out.println ("Val:" + readvalue);
  50. }
  51. }



Output Result:
val:100

If you would like to consult the source code of unsafe, please refer to the link below.
Http://www.docjar.com/html/api/sun/misc/Unsafe.java.html

Translated from: http://blog.csdn.net/joe_007/article/details/38964407

Java Direct Memory read and write examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.