当前位置: 首页 > news >正文

flink源码分析-获取JVM最大堆内存

flink版本: flink-1.11.2

代码位置: org.apache.flink.runtime.util.EnvironmentInformation#getMaxJvmHeapMemory

如果设置了-Xmx参数,就返回这个参数,如果没设置就返回机器物理内存的1/4.  这里主要看各个机器内存的获取方法。

	/*** The maximum JVM heap size, in bytes.** <p>This method uses the <i>-Xmx</i> value of the JVM, if set. If not set, it returns (as* a heuristic) 1/4th of the physical memory size.** @return The maximum JVM heap size, in bytes.*/public static long getMaxJvmHeapMemory() {final long maxMemory = Runtime.getRuntime().maxMemory();if(maxMemory != Long.MAX_VALUE) {// we have the proper max memoryreturn maxMemory;} else {// max JVM heap size is not set - use the heuristic to use 1/4th of the physical memoryfinal long physicalMemory = Hardware.getSizeOfPhysicalMemory();if(physicalMemory != -1) {// got proper value for physical memoryreturn physicalMemory / 4;} else {throw new RuntimeException("Could not determine the amount of free memory.\n" + "Please set the maximum memory for the JVM, e.g. -Xmx512M for 512 megabytes.");}}}

进入getSizeOfPhysicalMemory()方法,里面有获取各种操作系统物理内存的方法:

/** Licensed to the Apache Software Foundation (ASF) under one* or more contributor license agreements.  See the NOTICE file* distributed with this work for additional information* regarding copyright ownership.  The ASF licenses this file* to you under the Apache License, Version 2.0 (the* "License"); you may not use this file except in compliance* with the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.apache.flink.runtime.util;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.flink.util.OperatingSystem;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** Convenience class to extract hardware specifics of the computer executing the running JVM.*/
public class Hardware {private static final Logger LOG = LoggerFactory.getLogger(Hardware.class);private static final String LINUX_MEMORY_INFO_PATH = "/proc/meminfo";private static final Pattern LINUX_MEMORY_REGEX = Pattern.compile("^MemTotal:\\s*(\\d+)\\s+kB$");// ------------------------------------------------------------------------/*** Gets the number of CPU cores (hardware contexts) that the JVM has access to.* * @return The number of CPU cores.*/public static int getNumberCPUCores() {// TODO_MA 注释: 获取 Cpu Coresreturn Runtime.getRuntime().availableProcessors();}/*** Returns the size of the physical memory in bytes.* * @return the size of the physical memory in bytes or {@code -1}, if*         the size could not be determined.*/public static long getSizeOfPhysicalMemory() {// first try if the JVM can directly tell us what the system memory is// this works only on Oracle JVMstry {Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");Method method = clazz.getMethod("getTotalPhysicalMemorySize");OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();// someone may install different beans, so we need to check whether the bean// is in fact the sun management beanif (clazz.isInstance(operatingSystemMXBean)) {return (Long) method.invoke(operatingSystemMXBean);}}catch (ClassNotFoundException e) {// this happens on non-Oracle JVMs, do nothing and use the alternative code paths}catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {LOG.warn("Access to physical memory size: " +"com.sun.management.OperatingSystemMXBean incompatibly changed.", e);}// we now try the OS specific access pathsswitch (OperatingSystem.getCurrentOperatingSystem()) {case LINUX:return getSizeOfPhysicalMemoryForLinux();case WINDOWS:return getSizeOfPhysicalMemoryForWindows();case MAC_OS:return getSizeOfPhysicalMemoryForMac();case FREE_BSD:return getSizeOfPhysicalMemoryForFreeBSD();case UNKNOWN:LOG.error("Cannot determine size of physical memory for unknown operating system");return -1;default:LOG.error("Unrecognized OS: " + OperatingSystem.getCurrentOperatingSystem());return -1;}}/*** Returns the size of the physical memory in bytes on a Linux-based* operating system.* * @return the size of the physical memory in bytes or {@code -1}, if*         the size could not be determined*/private static long getSizeOfPhysicalMemoryForLinux() {try (BufferedReader lineReader = new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH))) {String line;while ((line = lineReader.readLine()) != null) {Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);if (matcher.matches()) {String totalMemory = matcher.group(1);return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte}}// expected line did not comeLOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +"Unexpected format.");return -1;}catch (NumberFormatException e) {LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +"Unexpected format.");return -1;}catch (Throwable t) {LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo') ", t);return -1;}}/*** Returns the size of the physical memory in bytes on a Mac OS-based* operating system* * @return the size of the physical memory in bytes or {@code -1}, if*         the size could not be determined*/private static long getSizeOfPhysicalMemoryForMac() {BufferedReader bi = null;try {Process proc = Runtime.getRuntime().exec("sysctl hw.memsize");bi = new BufferedReader(new InputStreamReader(proc.getInputStream()));String line;while ((line = bi.readLine()) != null) {if (line.startsWith("hw.memsize")) {long memsize = Long.parseLong(line.split(":")[1].trim());bi.close();proc.destroy();return memsize;}}} catch (Throwable t) {LOG.error("Cannot determine physical memory of machine for MacOS host", t);return -1;} finally {if (bi != null) {try {bi.close();} catch (IOException ignored) {}}}return -1;}/*** Returns the size of the physical memory in bytes on FreeBSD.* * @return the size of the physical memory in bytes or {@code -1}, if*         the size could not be determined*/private static long getSizeOfPhysicalMemoryForFreeBSD() {BufferedReader bi = null;try {Process proc = Runtime.getRuntime().exec("sysctl hw.physmem");bi = new BufferedReader(new InputStreamReader(proc.getInputStream()));String line;while ((line = bi.readLine()) != null) {if (line.startsWith("hw.physmem")) {long memsize = Long.parseLong(line.split(":")[1].trim());bi.close();proc.destroy();return memsize;}}LOG.error("Cannot determine the size of the physical memory for FreeBSD host " +"(using 'sysctl hw.physmem').");return -1;}catch (Throwable t) {LOG.error("Cannot determine the size of the physical memory for FreeBSD host " +"(using 'sysctl hw.physmem')", t);return -1;}finally {if (bi != null) {try {bi.close();} catch (IOException ignored) {}}}}/*** Returns the size of the physical memory in bytes on Windows.* * @return the size of the physical memory in bytes or {@code -1}, if*         the size could not be determined*/private static long getSizeOfPhysicalMemoryForWindows() {BufferedReader bi = null;try {Process proc = Runtime.getRuntime().exec("wmic memorychip get capacity");bi = new BufferedReader(new InputStreamReader(proc.getInputStream()));String line = bi.readLine();if (line == null) {return -1L;}if (!line.startsWith("Capacity")) {return -1L;}long sizeOfPhyiscalMemory = 0L;while ((line = bi.readLine()) != null) {if (line.isEmpty()) {continue;}line = line.replaceAll(" ", "");sizeOfPhyiscalMemory += Long.parseLong(line);}return sizeOfPhyiscalMemory;}catch (Throwable t) {LOG.error("Cannot determine the size of the physical memory for Windows host " +"(using 'wmic memorychip')", t);return -1L;}finally {if (bi != null) {try {bi.close();} catch (Throwable ignored) {}}}}// --------------------------------------------------------------------------------------------private Hardware() {}
}

另外注意try catch的这种用法:

		try (BufferedReader lineReader = new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH))) {String line;while ((line = lineReader.readLine()) != null) {Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);if (matcher.matches()) {String totalMemory = matcher.group(1);return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte}}// expected line did not comeLOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +"Unexpected format.");return -1;}catch (NumberFormatException e) {LOG.error("Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). " +"Unexpected format.");return -1;}

相关文章:

flink源码分析-获取JVM最大堆内存

flink版本: flink-1.11.2 代码位置: org.apache.flink.runtime.util.EnvironmentInformation#getMaxJvmHeapMemory 如果设置了-Xmx参数&#xff0c;就返回这个参数&#xff0c;如果没设置就返回机器物理内存的1/4. 这里主要看各个机器内存的获取方法。 /*** The maximum JVM…...

第17节 R语言分析:生物统计数据集 R 编码分析和绘图

生物统计数据集 R 编码分析和绘图 生物统计学,用于对给定文件 data.csv 中的医疗数据应用 R 编码,该文件是患者人口统计数据集,包含有关来自各种祖先谱系的个体的标准信息。 数据集特征解释 脚本 output= file("Output.txt") # File name of output log sink(o…...

一文了解什么是Selenium自动化测试?

目录 一、Selenium是什么&#xff1f; 二、Selenium History 三、Selenium原理 四、Selenium工作过程总结&#xff1a; 五、remote server端的这些功能是如何实现的呢&#xff1f; 六、附&#xff1a; 一、Selenium是什么&#xff1f; 用官网的一句话来讲&#xff1a;Sel…...

java接口实现

文章目录 java接口实现接口中成员组成默认方法静态方法私有接口&#xff08;保证自己的JDK版本大于等于9版本&#xff09;类和接口的关系抽象类与接口之间的区别 java接口实现 1.接口关键字 interface2.接口不能实例化3.类与接口之间的关系是实现关系&#xff0c;通过 impleme…...

数据结构入门指南:链表(新手避坑指南)

目录 前言 1.链表 1.1链表的概念 1.2链表的分类 1.2.1单向或双向 1.2.2.带头或者不带头 1.2.33. 循环或者非循环 1.3链表的实现 定义链表 总结 前言 前边我们学习了顺序表&#xff0c;顺序表是数据结构中最简单的一种线性数据结构&#xff0c;今天我们来学习链表&#x…...

SpringBoot第24讲:SpringBoot集成MySQL - MyBatis XML方式

SpringBoot第24讲&#xff1a;SpringBoot集成MySQL - MyBatis XML方式 上文介绍了用JPA方式的集成MySQL数据库&#xff0c;JPA方式在中国以外地区开发而言基本是标配&#xff0c;在国内MyBatis及其延伸框架较为主流。本文是SpringBoot第24讲&#xff0c;主要介绍MyBatis技栈的演…...

linux 查看网卡,网络情况

1&#xff0c;使用nload命令查看 #yum -y install nload 2&#xff0c; 查看eth0网卡网络情况 #nload eth0 Incoming也就是进入网卡的流量&#xff0c;Outgoing&#xff0c;也就是从这块网卡出去的流量&#xff0c;每一部分都有下面几个。 – Curr&#xff1a;当前流量 – Avg…...

在Mac上搭建Gradle环境

在Mac上搭建Gradle环境&#xff1a; 步骤1&#xff1a;下载并安装Java开发工具包&#xff08;JDK&#xff09; Gradle运行需要Java开发工具包&#xff08;JDK&#xff09;。您可以从Oracle官网下载适合您的操作系统版本的JDK。请按照以下步骤进行操作&#xff1a; 打开浏览器…...

Docker网络与Docker Compose服务编排

docker网络 docker是以镜像一层一层构建的&#xff0c;而基础镜像是linux内核&#xff0c;因此docker之间也需要通讯&#xff0c;那么就需要有自己的网络。就像windows都有自己的内网地址一样&#xff0c;每个docker容器也是有自己的私有地址的。 docker inspect [docker_ID]…...

opencv+ffmpeg环境(ubuntu)搭建全面详解

一.先讲讲opencv和ffmpeg之间的关系 1.1它们之间的联系 我们知道opencv主要是用来做图像处理的&#xff0c;但也包含视频解码的功能&#xff0c;而在视频解码部分的功能opencv是使用了ffmpeg。所以它们都是可以处理图像和视频的编解码&#xff0c;我个人感觉两个的侧重点不一…...

开发基于 LoRaWAN 的设备须知--最大兼容性

最大兼容性配置简介 LoRaWAN开放协议的建立前提是每个制造的设备都可以被唯一且安全地识别。配置是创建唯一标识和相应秘密的过程。虽然配置过程是常规的,但存在一些可能并不明显的陷阱。本章尝试描述配置基于 LoRa 的设备的一些最佳实践。 配置概念 基于 LoRa 的设备配置与银…...

一、SpringBoot基础[日志]

一、日志 解释&#xff1a;SpringBoot使用logback作为默认的日志框架&#xff0c;其中还可以导入log4j2等优秀的日志框架 1.修改日志内容 修改整个日志格式&#xff1a;logging.pattern.console%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{15} 你好 %msg%n %d{yyy…...

libuv库学习笔记-networking

Networking 在 libuv 中&#xff0c;网络编程与直接使用 BSD socket 区别不大&#xff0c;有些地方还更简单&#xff0c;概念保持不变的同时&#xff0c;libuv 上所有接口都是非阻塞的。它还提供了很多工具函数&#xff0c;抽象了恼人、啰嗦的底层任务&#xff0c;如使用 BSD …...

C++多线程编程(第三章 案例1,使用互斥锁+ list模拟线程通信)

主线程和子线程进行list通信&#xff0c;要用到互斥锁&#xff0c;避免同时操作 1、封装线程基类XThread控制线程启动和停止&#xff1b; 2、模拟消息服务器线程&#xff0c;接收字符串消息&#xff0c;并模拟处理&#xff1b; 3、通过Unique_lock和mutex互斥方位list 消息队列…...

IOS UICollectionView 设置cell大小不生效问题

代码设置flowLayout.itemSize 单元格并没有改变布局大小&#xff0c; 解决办法如下图&#xff1a;把View flow layout 的estimate size 设置为None&#xff0c;上面设置的itemSize 生效了。...

浅谈3D隐式表示(SDF,Occupancy field,NeRF)

本篇文章介绍了符号距离函数Signed Distance Funciton(SDF)&#xff0c;占用场Occupancy Field&#xff0c;神经辐射场Neural Radiance Field&#xff08;NeRF&#xff09;的概念、联系与区别。 显式表示与隐式表示 三维空间的表示形式可以分为显式和隐式。 比较常用的显式表…...

软件测试技能大赛任务二单元测试试题

任务二 单元测试 执行代码测试 本部分按照要求&#xff0c;执行单元测试&#xff0c;编写java应用程序&#xff0c;按照要求的覆盖方法设计测试数据&#xff0c;使用JUnit框架编写测试类对程序代码进行测试&#xff0c;对测试执行结果进行截图&#xff0c;将相关代码和相关截…...

MybatisPlus拓展篇

文章目录 逻辑删除通用枚举字段类型处理器自动填充功能防全表更新与删除插件MybatisX快速开发插件插件安装逆向工程常见需求代码生成 乐观锁问题引入乐观锁的使用效果测试 代码生成器执行SQL分析打印多数据源 逻辑删除 逻辑删除的操作就是增加一个字段表示这个数据的状态&…...

设置k8s中节点node的ROLES值,K8S集群怎么修改node1的集群ROLES

设置k8s中节点node的ROLES值 1.查看集群 [rootk8s-master ~]# kubectl get nodes NAME STATUS ROLES AGE VERSION k8s-master Ready control-plane,master 54d v1.23.8 k8s-node1 Ready <none> 54d v1.…...

【*1900 图论】CF1328 E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 注意到题目的性质&#xff1a;满足条件的路径个数是极少的&#xff0c;因为每个点离路径的距离<1 先考虑一条链&#xff0c;那么直接就选最深那个点作为端点即可 为什么&#xff0c;因为我们需要遍历所有点…...

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…...

Android Wi-Fi 连接失败日志分析

1. Android wifi 关键日志总结 (1) Wi-Fi 断开 (CTRL-EVENT-DISCONNECTED reason3) 日志相关部分&#xff1a; 06-05 10:48:40.987 943 943 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid44:9b:c1:57:a8:90 reason3 locally_generated1解析&#xff1a; CTR…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局&#xff1a;PCB行业的时代之问 在数字经济蓬勃发展的浪潮中&#xff0c;PCB&#xff08;印制电路板&#xff09;作为 “电子产品之母”&#xff0c;其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透&#xff0c;PCB行业面临着前所未有的挑战与机遇。产品迭代…...

FastAPI 教程:从入门到实践

FastAPI 是一个现代、快速&#xff08;高性能&#xff09;的 Web 框架&#xff0c;用于构建 API&#xff0c;支持 Python 3.6。它基于标准 Python 类型提示&#xff0c;易于学习且功能强大。以下是一个完整的 FastAPI 入门教程&#xff0c;涵盖从环境搭建到创建并运行一个简单的…...

【JVM】- 内存结构

引言 JVM&#xff1a;Java Virtual Machine 定义&#xff1a;Java虚拟机&#xff0c;Java二进制字节码的运行环境好处&#xff1a; 一次编写&#xff0c;到处运行自动内存管理&#xff0c;垃圾回收的功能数组下标越界检查&#xff08;会抛异常&#xff0c;不会覆盖到其他代码…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装

以下是基于 vant-ui&#xff08;适配 Vue2 版本 &#xff09;实现截图中照片上传预览、删除功能&#xff0c;并封装成可复用组件的完整代码&#xff0c;包含样式和逻辑实现&#xff0c;可直接在 Vue2 项目中使用&#xff1a; 1. 封装的图片上传组件 ImageUploader.vue <te…...

学习STC51单片机31(芯片为STC89C52RCRC)OLED显示屏1

每日一言 生活的美好&#xff0c;总是藏在那些你咬牙坚持的日子里。 硬件&#xff1a;OLED 以后要用到OLED的时候找到这个文件 OLED的设备地址 SSD1306"SSD" 是品牌缩写&#xff0c;"1306" 是产品编号。 驱动 OLED 屏幕的 IIC 总线数据传输格式 示意图 …...

[Java恶补day16] 238.除自身以外数组的乘积

给你一个整数数组 nums&#xff0c;返回 数组 answer &#xff0c;其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 请 不要使用除法&#xff0c;且在 O(n) 时间复杂度…...

python报错No module named ‘tensorflow.keras‘

是由于不同版本的tensorflow下的keras所在的路径不同&#xff0c;结合所安装的tensorflow的目录结构修改from语句即可。 原语句&#xff1a; from tensorflow.keras.layers import Conv1D, MaxPooling1D, LSTM, Dense 修改后&#xff1a; from tensorflow.python.keras.lay…...