1.前言

众所周知,Java是一门跨平台语言,针对不同的操作系统有不同的实现。本文从一个非常简单的api调用来看看Java具体是怎么做的.

2.源码分析

从FileInputStream.java中看到readBytes最后是native调用

/**
* Reads a subarray as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @exception IOException If an I/O error has occurred.
*/
private native int readBytes(byte b[], int off, int len) throws IOException; // native调用 /**
* Reads up to <code>b.length</code> bytes of data from this input
* stream into an array of bytes. This method blocks until some input
* is available.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[]) throws IOException {
return readBytes(b, 0, b.length);
}

从jdk源码中,我们找到FileInputStream.c(/jdk/src/share/native/java/io),此文件定义了对应文件的native调用.

// FileInputStream.c

JNIEXPORT jint JNICALL
Java_java_io_FileInputStream_readBytes(JNIEnv *env, jobject this,
jbyteArray bytes, jint off, jint len) {
return readBytes(env, this, bytes, off, len, fis_fd);
}

我们观察下当前的目录,可以看到java 对典型的四种unix like的系统(bsd, linux, macosx, solaris), 以及windows 提供了特殊实现。share是公用部分。

在头部获取文件fd field (fd 是非负正整数,用来标识打开文件)

// FileInputStream.c

JNIEXPORT void JNICALL
Java_java_io_FileInputStream_initIDs(JNIEnv *env, jclass fdClass) {
fis_fd = (*env)->GetFieldID(env, fdClass, "fd", "Ljava/io/FileDescriptor;"); /* fd field,后面用来获取 fd */
}

继续调用readBytes

// ioutil.c

jint
readBytes(JNIEnv *env, jobject this, jbyteArray bytes,
jint off, jint len, jfieldID fid)
{
jint nread;
char stackBuf[BUF_SIZE];
char *buf = NULL;
FD fd; if (IS_NULL(bytes)) {
JNU_ThrowNullPointerException(env, NULL);
return -1;
} if (outOfBounds(env, off, len, bytes)) { /* 越界判断 */
JNU_ThrowByName(env, "java/lang/IndexOutOfBoundsException", NULL);
return -1;
} if (len == 0) {
return 0;
} else if (len > BUF_SIZE) {
buf = malloc(len); /* 缓冲区不足,动态分配内存 */
if (buf == NULL) {
JNU_ThrowOutOfMemoryError(env, NULL);
return 0;
}
} else {
buf = stackBuf;
} fd = GET_FD(this, fid); /* 获取fd */
if (fd == -1) {
JNU_ThrowIOException(env, "Stream Closed");
nread = -1;
} else {
nread = IO_Read(fd, buf, len); /* 执行read,系统调用 */
if (nread > 0) {
(*env)->SetByteArrayRegion(env, bytes, off, nread, (jbyte *)buf);
} else if (nread == -1) {
JNU_ThrowIOExceptionWithLastError(env, "Read error");
} else { /* EOF */
nread = -1;
}
} if (buf != stackBuf) {
free(buf); /* 失败释放内存 */
}
return nread;
}

我们继续看看IO_Read的实现,是个宏定义

#define IO_Read handleRead

handleRead有两种实现

solaris实现:

// /jdk/src/solaris/native/java/io/io_util_md.c

ssize_t
handleRead(FD fd, void *buf, jint len)
{
ssize_t result;
RESTARTABLE(read(fd, buf, len), result);
return result;
} /*
* Retry the operation if it is interrupted
*/
#define RESTARTABLE(_cmd, _result) do { \
do { \
_result = _cmd; \
} while((_result == -1) && (errno == EINTR)); \ /* 如果是中断,则不断重试,避免进程调度等待*/
} while(0)

read方法可以参考unix man page

windows实现:

// jdk/src/windows/native/java/io/io_util_md.c

JNIEXPORT
jint
handleRead(FD fd, void *buf, jint len)
{
DWORD read = 0;
BOOL result = 0;
HANDLE h = (HANDLE)fd;
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
result = ReadFile(h, /* File handle to read */
buf, /* address to put data */
len, /* number of bytes to read */
&read, /* number of bytes read */
NULL); /* no overlapped struct */
if (result == 0) {
int error = GetLastError();
if (error == ERROR_BROKEN_PIPE) {
return 0; /* EOF */
}
return -1;
}
return (jint)read;
}

3.java异常初探

// jdk/src/share/native/common/jni_util.c

/**
* Throw a Java exception by name. Similar to SignalError.
*/
JNIEXPORT void JNICALL
JNU_ThrowByName(JNIEnv *env, const char *name, const char *msg)
{
jclass cls = (*env)->FindClass(env, name); if (cls != 0) /* Otherwise an exception has already been thrown */
(*env)->ThrowNew(env, cls, msg); /* 调用JNI 接口*/
} /* JNU_Throw common exceptions */ JNIEXPORT void JNICALL
JNU_ThrowNullPointerException(JNIEnv *env, const char *msg)
{
JNU_ThrowByName(env, "java/lang/NullPointerException", msg);
}

最后是调用JNI:

// hotspot/src/share/vm/prims/jni.h

jint ThrowNew(jclass clazz, const char *msg) {
return functions->ThrowNew(this, clazz, msg);
} jint (JNICALL *ThrowNew)
(JNIEnv *env, jclass clazz, const char *msg);

4.总结

很多高级语言,有着不同的编程范式,但是归根到底还是(c语言)系统调用,c语言能够在更低的层面做非常多的优化。如果我们了解了这些底层的系统调用,就能看到问题的本质。

本文没有对JNI 做深入分析,后续继续解析。

5.参考

https://man7.org/linux/man-pages/man2/read.2.html

Java的readBytes是怎么实现的?的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. Java线上应用故障排查之一:高CPU占用

    一个应用占用CPU很高,除了确实是计算密集型应用之外,通常原因都是出现了死循环. 以我们最近出现的一个实际故障为例,介绍怎么定位和解决这类问题. 根据top命令,发现PID为28555的Java进程占 ...

  3. java netty socket库和自定义C#socket库利用protobuf进行通信完整实例

    之前的文章讲述了socket通信的一些基本知识,已经本人自定义的C#版本的socket.和java netty 库的二次封装,但是没有真正的发表测试用例. 本文只是为了讲解利用protobuf 进行C ...

  4. 我看不下去鸟。。。。Java和C#的socket通信真的简单吗?

    这几天在博客园上看到好几个写Java和C#的socket通信的帖子.但是都为指出其中关键点. C# socket通信组件有很多,在vs 使用nuget搜索socket组件有很多类似的.本人使用的是自己 ...

  5. java.net.SocketException: Connection reset

    java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java ...

  6. Java Netty 4.x 用户指南

    问题 今天,我们使用通用的应用程序或者类库来实现互相通讯,比如,我们经常使用一个 HTTP 客户端库来从 web 服务器上获取信息,或者通过 web 服务来执行一个远程的调用. 然而,有时候一个通用的 ...

  7. Cocos2d-JS/Ajax用Protobuf与NodeJS/Java通信

    原文地址:http://www.iclojure.com/blog/articles/2016/04/29/cocos2d-js-ajax-protobuf-nodejs-java Google的Pr ...

  8. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

  9. java中 用telnet 判断服务器远程端口是否开启

    package net.jweb.common.util; import java.io.BufferedReader; import java.io.BufferedWriter; import j ...

  10. Java 把 InputStream 转换成 String 的几种方法

    我们在 Java 中经常会碰到如何把 InputStream 转换成 String 的情形,比如从文件或网络得到一个 InputStream,需要转换成字符串输出或赋给别的变量. 未真正关注这个问题之 ...

随机推荐

  1. Python表达式及运算符

    表达式 由一个或者几个数字或者变量或者运算符合成的一行代码 通常返回一个结果 运算符 由一个以上的值经过一系列的运算得到新值的过程叫运算 用来操作运算的符号叫运算符 运算符分类 算数运算符 比较或者关 ...

  2. 【Visual Leak Detector】源码调试 VLD 库

    说明 使用 VLD 内存泄漏检测工具辅助开发时整理的学习笔记.本篇介绍 VLD 源码的调试.同系列文章目录可见 <内存泄漏检测工具>目录 目录 说明 1. VLD 库源码调试步骤 1.1 ...

  3. Go函数基础

    在Go语言中,函数是一种基本的代码组织方式.函数能够接受输入参数并返回结果.Go语言中的函数有以下特点: 函数定义使用关键字func,后跟函数名.参数列表和返回值类型. 如果函数有返回值,则在函数定义 ...

  4. git仓库过渡,同时向两个仓库推送代码

    公司部门被大佬收购,产品项目迁移新公司仓库,过渡期间产品上线流程继续使用原公司的,新公司部署新系统后通过域名重定向逐渐将用户引流到新系统上完成切换,最后关闭原公司系统及上线流程. 过渡期间新功能代码需 ...

  5. iOS中的3种定时器

    在iOS中有3种常见的定时器,它们会根据不同的场景进行选择使用. 1.DispatchSourceTimer: 基于GCD实现. 2.CADisplayLink:基于屏幕刷新实现. 3.Timer:基 ...

  6. 2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距

    2022-03-11:int n, int[][] roads, int x, int y, n表示城市数量,城市编号0~n-1, roads[i][j] == distance,表示城市i到城市j距 ...

  7. 2022-02-06:等差数列划分 II - 子序列。 给你一个整数数组 nums ,返回 nums 中所有 等差子序列 的数目。 如果一个序列中 至少有三个元素 ,并且任意两个相邻元素之差相同,则称

    2022-02-06:等差数列划分 II - 子序列. 给你一个整数数组 nums ,返回 nums 中所有 等差子序列 的数目. 如果一个序列中 至少有三个元素 ,并且任意两个相邻元素之差相同,则称 ...

  8. SQL Server临时表删除

    SQL Server临时表删除 IF (SELECT object_id('tempdb..#tmpacqichu')) is not null DROP TABLE #tmpacqichu

  9. 这款全自动自适应工具你用过了吗?autofit.js请求加入你的战场!

    前段时间做了一个自适应的小工具(autofit.js) 经过一段时间的试用,同学们发现了工具存在的一些问题,我自己也发现了一些,这篇文章是针对这些问题撰写的. autofit.js autofit.j ...

  10. 记一次 Visual Studio 2022 卡死分析

    一:背景 1. 讲故事 最近不知道咋了,各种程序有问题都寻上我了,你说 .NET 程序有问题找我能理解,Windows 崩溃找我,我也可以试试看,毕竟对 Windows 内核也知道一丢丢,那 Visu ...