[“用new关键字创建一个Java对象的时候,它会超出作用域的范围之外”在上面这段代码里,我们没有办法访问对象,因为指向它的唯一一个句柄已超出了作用域的边界”] - s只在{}中可以引用,这是”变量的作用域“问题。 - 但s所指向的”内存对象“何时”可以被GCed“,则比较复杂,这部分取决于{}在什么地方: * 如果{}在一个方法内,则s相当于local-field,在方法结束时,s就变成”可以被GCed“ * 如果{}在init-block内,则s相当于class-field/instance-field, 我猜测当{}结束时,s就变成”可以被GCed“,即上述代码相当于: { String s = new String("a string"); s=null; }
- 若是上述代码变成: { String s = "a string"; } 则问题要麻烦一些,这种”不用new定义的String",何时GCed,不太清楚,我猜测 在当前JVM关闭之前,这样的String不会被GCed :-) 即:即使你写成: { String s = "a string"; s=null; } "a string"所占用的内存也依然不会被GCed
是这样的s出了作用范围,就可以被GC,如果没有其他的object指向"a string",那么"a string"也可以被GC,但什么时候被GC,是有不同的jvm实现的,我们不能知道,即使用System.gc()也不行.注意new String("a string")和"a string"是不一样的 区别是new String("a string")和new String("a string")是两个东西 "a string" 和 "a sting"是同一个东西(东西指内存区)
而上面的s会消失是因为以后的代码中再也没有用到s,所以s会被垃圾收集器收回。不知道各位有什么意见?
* 如果{}在一个方法内,则s相当于local-field,在方法结束时,s就变成”可以被GCed“
* 如果{}在init-block内,则s相当于class-field/instance-field,
我猜测当{}结束时,s就变成”可以被GCed“,即上述代码相当于:
{
String s = new String("a string");
s=null;
}
- 若是上述代码变成:
{
String s = "a string";
}
则问题要麻烦一些,这种”不用new定义的String",何时GCed,不太清楚,我猜测
在当前JVM关闭之前,这样的String不会被GCed :-) 即:即使你写成:
{
String s = "a string";
s=null;
}
"a string"所占用的内存也依然不会被GCed
区别是new String("a string")和new String("a string")是两个东西
"a string" 和 "a sting"是同一个东西(东西指内存区)