读源码的实用技巧

Posted by Vicky Luo on 2021-11-10
Estimated Reading Time 1 Minutes
Words 351 In Total
Viewed Times

读源码的实用技巧

1. 查看Java native方法源码

Java底层的native方法可以在OpenJDK中通过类名_方法名(方法名首字母要大写)的形式找到该方法对应的源码实现

eg:分配直接内存的方法ByteBuffer.allocateDirect(1024)源码跟下去会发现核心代码实现是Unsafe.class中的如下方法:

1
private native long allocateMemory0(long var1);

想要查看 Unsafe::allocateMemory0(long var1)的源码,可以在OpenJDK中搜索Unsafe_AllocateMemory0,如下:

1
2
3
4
5
6
7
8
9
UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
size_t sz = (size_t)size;

assert(is_aligned(sz, HeapWordSize), "sz not aligned");

void* x = os::malloc(sz, mtOther);

return addr_to_java(x);
} UNSAFE_END

2. 查看操作系统方法介绍

上述Unsafe_AllocateMemory0方法中核心实现方法为os::malloc(sz, mtOther)malloc是操作系统的原生方法,此类方法可以借助Linux系统命令man $方法名来查看方法对应的手册条目介绍,如下(不同操作系统可能有略微差别):

1
☁  ~  man malloc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
MALLOC(3)                BSD Library Functions Manual                MALLOC(3)

NAME
calloc, free, malloc, realloc, reallocf, valloc, aligned_alloc -- memory allocation

SYNOPSIS
#include <stdlib.h>

void *
calloc(size_t count, size_t size);

void
free(void *ptr);

void *
malloc(size_t size);

...

DESCRIPTION
The malloc(), calloc(), valloc(), realloc(), and reallocf() functions
allocate memory. The allocated memory is aligned such that it can be
used for any data type, including AltiVec- and SSE-related types. The
aligned_alloc() function allocates memory with the requested alignment.
The free() function frees allocations that were created via the preceding
allocation functions.

The malloc() function allocates size bytes of memory and returns a
pointer to the allocated memory.
......

3. TODO 持续更新


If the images or anything used in the blog infringe your copyright, please contact me to delete them. Thank you!