False Sharing

简介:

原文地址:http://mechanical-sympathy.blogspot.com/2011/07/false-sharing.html(有墙移到墙内)

作者:

Memory is stored within the cache system in units know as cache lines.  Cache lines are a power of 2 of contiguous bytes which are typically 32-256 in size.  The most common cache line size is 64 bytes.   False sharing is a term which applies when threads unwittingly impact the performance of each other while modifying independent variables sharing the same cache line.  Write contention on cache lines is the single most limiting factor on achieving scalability for parallel threads of execution in an SMP system.  I’ve heard false sharing described as the silent performance killer because it is far from obvious when looking at code.

To achieve linear scalability with number of threads, we must ensure no two threads write to the same variable or cache line.  Two threads writing to the same variable can be tracked down at a code level.   To be able to know if independent variables share the same cache line we need to know the memory layout, or we can get a tool to tell us.  Intel VTune is such a profiling tool.  In this article I’ll explain how memory is laid out for Java objects and how we can pad out our cache lines to avoid false sharing.

cache-line.png
Figure 1.

Figure 1. above illustrates the issue of false sharing.  A thread running on core 1 wants to update variable X while a thread on core 2 wants to update variable Y.  Unfortunately these two hot variables reside in the same cache line.  Each thread will race for ownership of the cache line so they can update it.  If core 1 gets ownership then the cache sub-system will need to invalidate the corresponding cache line for core 2.  When Core 2 gets ownership and performs its update, then core 1 will be told to invalidate its copy of the cache line.  This will ping pong back and forth via the L3 cache greatly impacting performance.  The issue would be further exacerbated if competing cores are on different sockets and additionally have to cross the socket interconnect.Java Memory Layout

For the Hotspot JVM, all objects have a 2-word header.  First is the “mark” word which is made up of 24-bits for the hash code and 8-bits for flags such as the lock state, or it can be swapped for lock objects.  The second is a reference to the class of the object.  Arrays have an additional word for the size of the array.  Every object is aligned to an 8-byte granularity boundary for performance.  Therefore to be efficient when packing, the object fields are re-ordered from declaration order to the following order based on size in bytes:

  1. doubles (8) and longs (8)
  2. ints (4) and floats (4)
  3. shorts (2) and chars (2)
  4. booleans (1) and bytes (1)
  5. references (4/8)
  6. <repeat for sub-class fields>

With this knowledge we can pad a cache line between any fields with 7 longs.  Within the Disruptor we pad cache lines around the RingBuffer cursor and BatchEventProcessor sequences.To show the performance impact let’s take a few threads each updating their own independent counters.  These counters will be volatile longs so the world can see their progress.

01 public final class FalseSharing
02     implements Runnable
03 {
04     public final static int NUM_THREADS = 4; // change
05     public final static long ITERATIONS = 500L * 1000L * 1000L;
06     private final int arrayIndex;
07  
08     private static VolatileLong[] longs = new VolatileLong[NUM_THREADS];
09     static
10     {
11         for (int i = 0; i < longs.length; i++)
12         {
13             longs[i] = new VolatileLong();
14         }
15     }
16  
17     public FalseSharing(final int arrayIndex)
18     {
19         this.arrayIndex = arrayIndex;
20     }
21  
22     public static void main(final String[] args) throws Exception
23     {
24         final long start = System.nanoTime();
25         runTest();
26         System.out.println("duration = " + (System.nanoTime() - start));
27     }
28  
29     private static void runTest() throws InterruptedException
30     {
31         Thread[] threads = new Thread[NUM_THREADS];
32  
33         for (int i = 0; i < threads.length; i++)
34         {
35             threads[i] = new Thread(new FalseSharing(i));
36         }
37  
38         for (Thread t : threads)
39         {
40             t.start();
41         }
42  
43         for (Thread t : threads)
44         {
45             t.join();
46         }
47     }
48  
49     public void run()
50     {
51         long i = ITERATIONS + 1;
52         while (0 != --i)
53         {
54             longs[arrayIndex].value = i;
55         }
56     }
57  
58     public final static class VolatileLong
59     {
60         public volatile long value = 0L;
61         public long p1, p2, p3, p4, p5, p6; // comment out
62     }
63 }

Results

Running the above code while ramping the number of threads and adding/removing the cache line padding,  I get the results depicted in Figure 2. below.  This is measuring the duration of test runs on my 4-core Nehalem.

duration.png
Figure 2.

The impact of false sharing can clearly be seen by the increased execution time required to complete the test.  Without the cache line contention we achieve near linear scale up with threads.

This is not a perfect test because we cannot be sure where the VolatileLongs will be laid out in memory.  They are independent objects.  However experience shows that objects allocated at the same time tend to be co-located.

So there you have it.  False sharing can be a silent performance killer.

Note: Please read my further adventures with false sharing in this follow on blog.

目录
相关文章
|
存储 JavaScript 前端开发
|
前端开发 JavaScript API
聊聊 npm 的语义化版本(Semver)
聊聊 npm 的语义化版本(Semver)
659 1
|
数据可视化 物联网 PyTorch
Stable Diffusion模型魔搭最佳实践:训一只你的萌柯基
Stable Diffusion模型魔搭最佳实践:训一只你的萌柯基
|
开发框架 人工智能 API
《鸿蒙开发工具链深度洞察:优缺剖析与提效指南》
鸿蒙系统作为创新型操作系统,其应用开发工具链具备显著优势:统一开发框架支持多设备适配,丰富易用的API简化功能实现,DevEco Studio提供强大开发支持,实时预览与热更新提升效率。然而,生态成熟度、多端深度优化及部分高级功能仍有不足。开发者可通过深入学习工具、利用开源资源、优化流程和提前规划适配来提高效率。随着工具链不断完善,开发者将助力鸿蒙生态繁荣发展。
862 0
|
11月前
|
存储 弹性计算 Linux
2026阿里云购买云服务器流程及注意事项(新用户指南)
在数字化场景中,个人和企业部署网站、APP 常需要服务器支撑。相比逐渐淘汰的虚拟主机和成本较高的独立服务器,云服务器凭借弹性扩展、性价比高的优势成为主流。阿里云 ECS(弹性计算服务)地域节点多、配置灵活,但新手容易在地域、实例规格等选择上困惑。下面结合最新信息,梳理阿里云服务器的购买流程和配置要点,帮新手高效完成选购。
|
消息中间件 NoSQL Java
【Redis】浅尝Redis Stream做消息队列
SpringBoot整合Redis5.0新特性Redis Stream
2238 0
【Redis】浅尝Redis Stream做消息队列
|
存储 缓存 自然语言处理
64_模型部署:推理优化策略
随着人工智能技术的飞速发展,大型语言模型(LLM)在自然语言处理、多模态理解等领域展现出惊人的能力。然而,将这些模型从实验室环境部署到实际生产系统中,面临着诸多挑战。根据2025年最新研究数据,大模型部署的主要挑战包括:
1575 0
|
数据格式
Element el-cascader 级联选择器详解
本文目录 1. 概述 2. 数据绑定 2.1 默认数据绑定 2.2 指定绑定数据格式 3. 常用功能 3.1 修改触发方式 3.2 增加清空按钮 3.3 可搜索 3.4 选中项只显示最后一级 3.5 可选中任意一级 3.6 面板样式 3.7 自定义节点内容 4. 动态加载下级 5. 小结
5013 0
|
安全 测试技术 Python
零操作,高效下载:利用Playwright和Python完成文件下载
Playwright是Microsoft开发的跨浏览器自动化测试工具,能模拟用户操作,包括文件下载。在Python中,它提供`expect_download()`来处理文件下载,无需额外工具。下载开始时触发事件,完成后可通过`download.path()`获取路径。下载相关操作包括取消、删除、获取错误信息、所属页面、文件名、URL等。示例代码展示了如何下载pytest的压缩文件,简化了web自动化测试中的文件下载场景。
|
机器学习/深度学习 人工智能 自然语言处理
从平凡到非凡:借AI风口普通人如何起飞?
雷军曾说:“站在风口上,猪也能飞上天。”而AI无疑是当前最强劲的风口。本文介绍了如何抓住AI时代的机遇,包括理解AI基础概念、选择合适的AI工具、将AI融入工作提升效率,以及利用AI创造被动收入。通过这些步骤,你将能够在AI浪潮中获得成功。
1295 0
从平凡到非凡:借AI风口普通人如何起飞?