简体   繁体   English

是否有其他替代概念可用于处理垃圾收集语言中的非托管资源?

[英]Are there any alternative concepts for handling unmanaged resources in garbage collected languages?

Garbage collected object oriented programming languages reclaim unused memory automatically, but all other kinds of resources (ie files, sockets...) still require manual release since finalizers cannot be trusted to run in time (or at all). 垃圾收集的面向对象编程语言会自动回收未使用的内存,但是所有其他类型的资源(即文件,套接字等)仍然需要手动释放,因为终结器无法及时(或完全)运行。

Therefore such resource objects usually provide some kind of "close" - or "dispose" -method/pattern, which can be problematic for a number of reasons: 因此,此类资源对象通常提供某种“关闭”“处置”的方法/模式,由于多种原因,这可能是有问题的:

  • Dispose has to be called manually which may pose problems in cases when it is not clear when the resource has to be released (similar problem as with manual memory management) 必须手动调用Dispose ,这在不清楚何时必须释放资源的情况下可能会引起问题(与手动内存管理类似的问题)
  • The disposable-pattern is somewhat "viral", since each class containing a disposable resource must be made disposable as well in order to guarantee correct resource cleanup 一次性模式有点“病毒”,因为包含一次性资源的每个类别也必须设为一次性 ,以确保正确清理资源
  • An addition of a disposable member to a class, requiring the class to become disposable as well, changes the interface and the usage patterns of the class, thus breaking encapsulation 一次性构件的一类,需要类成为一次性以及的加成,改变接口和类的使用模式,从而打破封装
  • The disposable-pattern creates problems with inheritance, ie when a derived class is disposable , while the base class isn't 一次性模式会产生继承问题,即,当派生类为一次性时 ,而基类不是

So, are there any alternative concepts/approaches for properly releasing such resources? 因此,是否有其他替代概念/方法可以正确释放这些资源? Any papers/research in that direction? 在这个方向上有任何论文/研究吗?

One approach (in languages that support it) is to manually trigger a garbage collection event to cause finalizers to run. 一种方法(使用支持它的语言)是手动触发垃圾回收事件以使终结器运行。 However, some languages (like Java) do not provide a reliable mechanism for doing so. 但是,某些语言(如Java)没有提供可靠的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM