You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2018/10/16 23:41:33 UTC

[GitHub] yzhliu commented on a change in pull request #12647: NativeResource Management in Scala

yzhliu commented on a change in pull request #12647: NativeResource Management in Scala
URL: https://github.com/apache/incubator-mxnet/pull/12647#discussion_r225739773
 
 

 ##########
 File path: scala-package/core/src/main/scala/org/apache/mxnet/NativeResource.scala
 ##########
 @@ -0,0 +1,186 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.mxnet
+
+import org.apache.mxnet.Base.CPtrAddress
+import java.lang.ref.{PhantomReference, ReferenceQueue, WeakReference}
+import java.util.concurrent._
+
+import org.apache.mxnet.Base.checkCall
+import java.util.concurrent.atomic.AtomicLong
+
+
+/**
+  * NativeResource trait is used to manage MXNet Objects
+  * such as NDArray, Symbol, Executor, etc.,
+  * The MXNet Object calls NativeResource.register
+  * and assign the returned NativeResourceRef to PhantomReference
+  * NativeResource also implements AutoCloseable so MXNetObjects
+  * can be used like Resources in try-with-resources paradigm
+  */
+private[mxnet] trait NativeResource
+  extends AutoCloseable with WarnIfNotDisposed {
+
+  /**
+    * native Address associated with this object
+    */
+  def nativeAddress: CPtrAddress
+
+  /**
+    * Function Pointer to the NativeDeAllocator of nativeAddress
+    */
+  def nativeDeAllocator: (CPtrAddress => Int)
+
+  /** Call NativeResource.register to get the reference
+    */
+  val ref: NativeResourceRef
+
+  /**
+    * Off-Heap Bytes Allocated for this object
+    */
+  // intentionally making it a val, so it gets evaluated when defined
+  val bytesAllocated: Long
+
+  private[mxnet] var scope: ResourceScope = null
+
+  @volatile var disposed = false
+
+  override def isDisposed: Boolean = disposed || isDeAllocated
+
+  /**
+    * Register this object for PhantomReference tracking and in
+    * ResourceScope if used inside ResourceScope.
+    * @return NativeResourceRef that tracks reachability of this object
+    *         using PhantomReference
+    */
+  def register(): NativeResourceRef = {
+    scope = ResourceScope.getCurrentScope()
+    if (scope != null) scope.add(this)
+
+    NativeResource.totalBytesAllocated.getAndAdd(bytesAllocated)
+    // register with PhantomRef tracking to release incase the objects go
+    // out of reference within scope but are held for long time
+    NativeResourceRef.register(this, nativeDeAllocator)
+ }
+
+  // Removes this object from PhantomRef tracking and from ResourceScope
+  private def deRegister(removeFromScope: Boolean): Unit = {
+    NativeResourceRef.deRegister(ref)
+    if (scope != null && removeFromScope) scope.remove(this)
+  }
+
+  // Implements [[@link AutoCloseable.close]]
+  override def close(): Unit = {
+    dispose()
+  }
+
+  // Implements [[@link WarnIfNotDisposed.dispose]]
+  def dispose(): Unit = dispose(true)
+
+  private[mxnet] def dispose(removeFromScope: Boolean = true): Unit = {
+    if (!disposed) {
+      checkCall(nativeDeAllocator(this.nativeAddress))
+      deRegister(removeFromScope)
+      NativeResource.totalBytesAllocated.getAndAdd(-1*bytesAllocated)
+      disposed = true
+    }
+  }
+
+  /*
+  this is used by the WarnIfNotDisposed finalizer,
+  the object could be disposed by the GC without the need for explicit disposal
+  but the finalizer might not have run, then the WarnIfNotDisposed throws a warning
+   */
+  private[mxnet] def isDeAllocated(): Boolean = NativeResourceRef.isDeAllocated(ref)
+
+}
+
+private[mxnet] object NativeResource {
+  var totalBytesAllocated : AtomicLong = new AtomicLong(0)
+}
+
+// Do not make [[NativeResource.resource]] a member of the class,
+// this will hold reference and GC will not clear the object.
+private[mxnet] class NativeResourceRef(resource: NativeResource,
+                                       val resourceDeAllocator: CPtrAddress => Int)
+        extends PhantomReference[NativeResource](resource, NativeResourceRef.refQ) {}
+
+private[mxnet] object NativeResourceRef {
+
+  private[mxnet] val refQ: ReferenceQueue[NativeResource]
+                = new ReferenceQueue[NativeResource]
+
+  private[mxnet] val refMap = new ConcurrentHashMap[NativeResourceRef, CPtrAddress]()
 
 Review comment:
   do we really need this Map? can we store resource.nativeAddress (not whole NativeResource.resource) as a member of NativeResourceRef?
   My major concern is, given two thread-safe containers cooperate with each other, a small carelessness can result in concurrency disaster. `isDeAllocated` is not really necessary - if you're worry about `WarnIfNotDisposed`, can we simply remove it? since now everything is guaranteed to be disposed finally (we invented that because we removed `dispose()` in `finalize` at that time).

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services