静态方法的Java内存模型 [英] Java memory model for static methods

查看:82
本文介绍了静态方法的Java内存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C的操作系统和背景,那里的代码编译时世界很简单.需要处理和理解堆栈,堆文本部分等.

I come from operating systems and background of C where the world is simple when code is compiled. Need to deal and understand stack, heap text section etc.

当我开始学习Java(我确实了解JVM和垃圾收集器)时,我对静态方法感到很开心.根据我的理解,一个类的所有实例都会在堆中创建,然后再清理.但是,对于静态方法,您不需要该类的实例.

When I started learning Java(I do know about JVM and garbage collector), I got amused by static methods. As per my understanding all the instances of a class do get created in the heap and then do get cleaned. However, for a static method, you don't need an instance of the class.

因此,可以请一些人解释一下非静态方法和静态方法在内存模型中的不同之处.它们是否都驻留在内存的文本部分中.还是我把事情弄得一团糟.

So, can some one please explain how non static methods and static methods differ in memory model. Do both of them reside in the text section of the memory. Or I am messing up things completely.

谢谢

推荐答案

在Java中,类的字节码(包括它们的方法,包括静态方法和实例方法)是堆的一部分(通常是特殊的永久生成" "(适用于长期存在的对象).

In Java, the bytecode for the classes (and that includes their methods, both static and instance) is part of the heap (usually in a special "permanent generation" section for long-lived objects).

也可以对类进行垃圾回收,但这通常不会发生太多(仅当从非系统类加载器加载该类并且整个类加载器已过时(例如,在卸载Web应用程序时)). /p>

Classes can be garbage-collected, too, but this usually does not happen much (only when the class was loaded from a non-system classloader and that whole classloader becomes obsolete, for example when a web application is unloaded).

但是,对于静态方法,您不需要该类的实例.

However, for a static method, you don't need an instance of the class.

对.但是所有方法都是类定义的一部分,并且在加载类时一起加载.即使您从未创建类的实例,所有实例方法的代码也将被加载到堆内存中.

Right. But all methods are part of the class definition and loaded together when the class is loaded. Even if you never make an instance of a class, the code for all instance methods will be loaded into heap memory.

然后将JIT编译为本机代码:使用Hotspot,将常用方法的字节码进一步编译为本机代码.这样的结果确实会在堆之外进入本地内存,并且仅在实际使用的方法(静态或非静态)中发生.

And then there is JIT compilation to native code: With Hotspot, the bytecode for frequently used methods is compiled further into native machine code. The result of that does go somewhere outside of the heap into native memory, and that only happens for methods that are actually being used (static or not).

这篇关于静态方法的Java内存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆