linux - Linux内存管理器中的"Weak reference"?

标签 linux caching memory-management weak-references

在 Java 中,如果内存不足,弱引用将被垃圾回收。在 Linux 中,malloc() 总是返回一个强引用,即。在调用者调用 free() 函数之前,指针永远不会被释放。

我想分配一个缓冲区用于缓存,当内存用完时可以自动释放,如下所示:

cache_t cache;
if (! cache_alloc(&cache))
    die("Memory out");

cache_lock(&cache); // realloc cache mem if it is collected

if (! cache->user_init) { // The "user_init" maybe reset if the cache mem is collected
  // lazy-init the cache...
  load_contents(cache->mem, ...);
  cache->user_init = 1;
}

// do with cache..
stuff_t *stuff = (stuff_t *) cache->mem;
...

cache_unlock(&cache);

似乎 vmstat 输出中的 buffcache 与磁盘 IO 相关:

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0  51604 554220  13384 314852    3   10   411   420  702 1063  8  3 75 14

好吧,我想知道更多关于我示例中的缓存是否可以反射(reflect)在 vmstat 输出的“缓存”列中。

最佳答案

确实没有一个好的方法来做到这一点——C 内存模型根本不允许 Java 内存模型允许的相同类型的行为。当与操作系统交互时,Java 的内存模型当然建立在 C 模型之上,这就是为什么 Java 堆必须由应用程序启动器手动限制的原因。

“buff”和“cache”列与内核使用的页面/磁盘缓存和内部缓冲区有关。这些缓存由内核自动处理 - 例如,读取文件会将内容放入“缓存”使用编号中,就像内存不足会将其提交到交换设备(“swpd”)一样。

关于linux - Linux内存管理器中的"Weak reference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632478/

相关文章:

linux - xargs 无法获取用户输入?

node.js - 如何使用redis在 Node 中缓存查询数据

asp.net-mvc - 为什么 System.Web.Services.Protocols.LogicalMethodInfo 无法在 Azure 缓存中序列化?

.net - ASP.Net 缓存共享

c# - C# 引用类型在传递给方法时会分配新内存吗?

linux - 为什么某个进程会多次加载 lib?

java - Spark 如何实现任务间的内存公平?

php - 使用 PHP mysql_connect 函数时绑定(bind)到特定的 ip 地址

c++ - 如何在不结束 C++ 程序的情况下结束 ncurses?

python - 将 glob 命令从 Popen 传递到终端