根据我的理解,如果没有其他东西"指向"该对象,Java中的垃圾收集会清除一些对象.
我的问题是,如果我们有这样的事情会发生什么:
class Node {
public object value;
public Node next;
public Node(object o, Node n) { value = 0; next = n;}
}
//...some code
{
Node a = new Node("a", null),
b = new Node("b", a),
c = new Node("c", b);
a.next = c;
} //end of scope
//...other code
Run Code Online (Sandbox Code Playgroud)
a,b和c应该是垃圾收集,但它们都被其他对象引用.
Java垃圾收集如何处理这个问题?(或者它只是一个内存消耗?)
我在 kotlin 扩展文件中有这个函数来传递方法,但它不起作用。请向我解释它是如何正确制作的,我试试这个:
fun showErrorClientScreen(context: Context, action : () -> Unit) {
val intent = Intent(context, RestClientErrorActivity::class.java)
val bundle = Bundle()
bundle.putSerializable(UPDATE_CLIENT_ERROR, ErrorClientListener { action })
intent.putExtra(UPDATE_CLIENT_ERROR_BUNDLE, bundle)
context.startActivity(intent)
}
Run Code Online (Sandbox Code Playgroud)
使用java接口
public interface ErrorClientListener extends Serializable {
void tryAgainFunction();
}
Run Code Online (Sandbox Code Playgroud)
以及我需要收听的活动单击按钮并再次尝试发送请求:
class RestClientErrorActivity: BaseActivity(), View.OnClickListener {
private lateinit var errorClientListener: ErrorClientListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rest_client_error)
try {
val bundle = intent.getBundleExtra(UPDATE_CLIENT_ERROR_BUNDLE)
errorClientListener = bundle?.getSerializable(UPDATE_CLIENT_ERROR) as ErrorClientListener
} catch (e: Exception) {
e.message
}
}
override fun onClick(v: …Run Code Online (Sandbox Code Playgroud) 我SomeSingleton在C#中有一些类(如果重要,则为.NET 3.5)和代码:
foo()
{
...
SomeSingleton.Instance.DoSomething();
...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:垃圾收集器什么时候会收集这个Singleton对象?
ps:SomeSingleton的代码:
private static SomeSingleton s_Instance = null;
public static SomeSingleton Instance
{
get
{
if (s_Instance == null)
{
lock (s_InstanceLock)
{
if (s_Instance == null)
{
s_Instance = new SomeSingleton();
}
}
}
return s_Instance;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢帮助!
编辑(附说明):
在Widnows服务中我有代码:
...
FirstSingleton.Instance.DoSomething();
...
public class FirstSingleton
{
(Instance part the same as in SomeSingleton)
public void DoSomething()
{
SomeSingleton.Instance.DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的目标:我不关心FirstSingleton会发生什么,但SomeSingleton首先使用它启动Timer,所以我需要SomeSingleton存在(所以定时器可以在每个时间段运行新线程),只要我的服务是运行.
正如我从你的答案中理解的那样,所有这一切都会发生,因为对我的FirstSingleton和SomeSingleton的引用是静态的,并且在服务停止之前GC不会收集单身人士,我是对的吗?:)