文档章节

bytebuffer vs c++ malloc

不道归来
 不道归来
发布于 2017/10/23 14:09
字数 733
阅读 24
收藏 0

Java equivalents of malloc()newfree() and delete (ctd)

Continued from our introduction to memory management operators in C/C++ and Java.

A Java equivalent of the malloc() function...?

If you've read the previous page on memory management and new in Java, you may be wondering why the current section on malloc() even exists. We've just stated that in Java, all memory has to be accessed via well-defined objects. In C/C++, on the other hand, malloc() gives us a pointer to an arbitrary block of memory. And in Java, there's no such thing, right?

Well, strictly speaking this is true: there isn't a way in Java to access "raw" memory via its address (pointer)— at least, not in a way where the address is visible to your Java program. But Java does provide the following rough equivalents to an area of memory allocated via malloc():

  • if you just want a block of bytes, e.g. in order to buffer input form a file or stream, then a common solution is to use a byte array;
  • the Java NIO (New I/O) package provides various buffer classes that allow you to manipulate an array or area of memory more flexibly: with methods to get/set a given primitive at a particular offset in the buffer, for example.

So, for example, the equivalent of the following C code:

unsigned char *memarea = (char *) malloc(200);
*(memarea + 10) = 200;
*((int *) (memarea + 16) = 123456;
ch = memarea[4];

would be something along the following lines in Java, using a NIO ByteBuffer object:

ByteBuffer bb = ByteBuffer.allocate(200);
bb.put(0, (byte) 200);
bb.putInt(16, 123456);
int ch = bb.get(4) & 0xff;

Notice a subtlety of buffer access in Java is that we must deal with sign conversions ourselves. To read an unsigned byte from the ByteBuffer, we must store it in an int (or some primitive big enough to handle values between 128 and 255— basically, anything but a byte!), and must explicitly "AND off" the bits holding the sign.

Performance

Note that in Sun's JVM— and probably other JVMs with a good JIT compiler— accesses to ByteBuffers usually compile directly to MOV instructions at the machine code level. In other words, accessing a ByteBuffer really is usually as efficient as accessing a malloced area of memory from C/C++1.

Direct byte buffers

In the above example, the byte buffer would actually be "backed" by an ordinary Java byte array. It is even possible to call bb.array() to retrieve the backing array. An alternative that is perhaps closer to malloc() is to create what is called a direct ByteBuffer in Java: a ByteBuffer that is backed by a "pure block of memory" rather than a Java byte array2. To do so requires us simply to change the initial call:

ByteBuffer bb = ByteBuffer.allocateDirect(200);

Note that from Java, we still don't see or have control over the actual memory address of the buffer. Direct byte buffers have the advantage ofaccessibility via native code: although the address is of the buffer isn't available or controllable in Java, it is possible for your Java program to interface with native code (via the Java Native Interface). From the native side, you can:

  • query the address of a direct buffer;
  • allocate a direct buffer around a determined address range.

This very last point is quite significant, as it effectively allows things like device drivers to be written in Java (OK, in "Java plus a couple of lines of C" at any rate...).

Note, however, that you generally shouldn't use direct ByteBuffers "by default":

 

  • because they're essentially not Java objects (or at least, the actual data isn't), the direct buffer data is not allocated from the Java heap, but rather from the process's remaining memory space;
  • in practice, direct buffers are difficult to garbage collect, if even possible: Sun's Java 1.4 VM, for example, appears never to reclaim the memory of a direct byte buffer.

See also:
 Memory usage in Java
 Querying the memory usage of an object
 Reducing memory usage of Java Strings
 Data compression in Java

1. The same is often true of accessing object fields: the JIT compiler can compile accesses to object fields into MOV instructions that "know" the offset of the field in question.
2. You can actually create buffers backed by other types of primitive array, such as an IntBuffer backed by an int array.

 

--------------------\

ref: api

本文转载自:https://www.javamex.com/java_equivalents/malloc.shtml

共有 人打赏支持
不道归来
粉丝 2
博文 117
码字总数 14449
作品 0
南京
后端工程师
【整理】为什么在C/C++中总是对malloc的返回值进行强制转换

============= 文章1 ================ 首先要说的是,使用 malloc 函数,请包含 stdlib.h(C++ 中可以是 cstdlib),而不是 malloc.h 。因为 malloc.h 从来没有在 C 或者 C++ 标准中出现过!...

摩云飞
2013/05/07
0
0
malloc和new有什么区别

malloc和new有以下不同: new、delete是操作符,可以重载,只能在c++中使用。 malloc、free是函数,可以覆盖,c、c++中都可以使用。 new可以调用对象的构造函数,对应的delete调用相应的析构...

夏雪冬日
2012/12/11
0
0
对malloc的返回值应该如何转型

本文概括叙述了一篇老文的内容,并且总结对malloc返回值的3种转型方式,(相对于原文)更全面的总结其各自的应用范围。 1. 原文内容 2. 对malloc的3种转型方式 3. 各自的应用范围 以前有篇文...

Start-up
2012/05/08
0
0
【原创】使用 VS 编译遇到的一些 error 和 warning(持续更新)

【error C2143】 error C2143: 语法错误 : 缺少“;”(在“类型”的前面) 原因:以“编译为 C 代码(/TC)”方式编译时,没有把变量定义在函数开始的位置。 【error LNK2019】 error LNK2019: 无...

摩云飞
2012/11/16
0
0
C语言编程知识学习:if语句对出错的处理

C语言是面向过程的,而C++是面向对象的 C和C++的区别: C是一个结构化语言,它的重点在于算法和数据结构。C程序的设计首要考虑的是如何通过一个过程,对输入(或环境条件)进行运算处理得到...

小辰带你看世界
05/15
0
0

没有更多内容

加载失败,请刷新页面

加载更多

关于编程,你的练习是不是有效的?

最近由于工作及Solution项目的影响,我在重新学习DDD和领域建模的一些知识。然后,我突然就想到了这个问题,以及我是怎么做的? 对于我来说,提升技能的项目会有四种: 纯兴趣驱动的项目。即...

问题终结者
43分钟前
1
0
打开eclipse出现an error has occurred see the log file

解决方法: 1,打开eclipse安装目录下的eclipse.ini文件; 2,打开的文本文件最后添加一行 --add-modules=ALL-SYSTEM 3,保存重新打开Eclipse。...

任梁荣
昨天
4
0
搞定Northwind示例数据库,无论哪个版本的SQLServer都受用

Northwind数据库 从这里可以找到突破口: http://social.msdn.microsoft.com/Forums/zh-CN/Vsexpressvb/thread/8490a1c6-9018-40c9-aafb-df9f79d29cde 下面是MSDN: http://msdn2.microsoft......

QQZZFT
昨天
1
0
mysql主从同步,安装配置操作

准备 两台mysql服务,我这里准备了如下: 主库:192.168.176.128 从库:192.168.176.131 如何在Linux上安装mysql服务,请看https://blog.csdn.net/qq_18860653/article/details/80250499 操作...

小致dad
昨天
4
0
Redis的“死键”问题

大规模的数据库存储系统中,数据的生命周期管理是很有必要的;从业务角度发现过期数据,数据归档和数据碎片整理等。以MySQL为例,1个运行很久的TB级MySQL实例中,极有可能数百GB的数据,对业...

IT--小哥
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部