Sun. Misc. Unsafe package in Java

Source: Internet
Author: User

Chronicle Project: https://github.com/peter-lawrey/Java-Chronicle

This project uses the MMAP mechanism to efficiently read and write data, and claims to write 5 to 20 million pieces of data per second.

The author has a test. It takes 0.234 seconds to write 1 million logs, and 7.347 seconds to write logs using a Java logger.

Looking at Chronicle's source code, we can find an example of using unsafe to directly read and write memory, thus improving the efficiency.

See this class for details: https://github.com/peter-lawrey/Java-Chronicle/blob/master/src/main/java/vanilla/java/chronicle/impl/UnsafeExcerpt.java

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

The following example shows how to modify a byte [] data.

This example cannot be compiled directly in eclipse. It must be set to warning in forbidden reference (access rules) in Java compiler, errors/warnings to the project attributes.

In addition, because the sun. Misc. Unsafe package cannot be used directly, an unsafe instance is obtained using the reflection technique in all codes.

import java.lang.reflect.Field;import java.util.Arrays;import sun.misc.Unsafe;public class Test {private static int byteArrayBaseOffset;public static void main(String[] args) throws SecurityException,NoSuchFieldException, IllegalArgumentException,IllegalAccessException {Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");theUnsafe.setAccessible(true);Unsafe UNSAFE = (Unsafe) theUnsafe.get(null);System.out.println(UNSAFE);byte[] data = new byte[10];System.out.println(Arrays.toString(data));byteArrayBaseOffset = UNSAFE.arrayBaseOffset(byte[].class);System.out.println(byteArrayBaseOffset);UNSAFE.putByte(data, byteArrayBaseOffset, (byte) 1);UNSAFE.putByte(data, byteArrayBaseOffset + 5, (byte) 5);System.out.println(Arrays.toString(data));}}

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.