yzhliu commented on a change in pull request #12647: NativeResource Management in Scala URL: https://github.com/apache/incubator-mxnet/pull/12647#discussion_r225735161
########## File path: scala-package/core/src/main/scala/org/apache/mxnet/ResourceScope.scala ########## @@ -0,0 +1,196 @@ +/* + * 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 java.util.HashSet + +import org.slf4j.LoggerFactory + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer +import scala.util.Try +import scala.util.control.{ControlThrowable, NonFatal} + +/** + * This class manages automatically releasing of [[NativeResource]]s + */ +class ResourceScope extends AutoCloseable { + + // HashSet does not take a custom comparator + private[mxnet] val resourceQ = new mutable.TreeSet[NativeResource]()(nativeAddressOrdering) + + private object nativeAddressOrdering extends Ordering[NativeResource] { + def compare(a: NativeResource, b: NativeResource): Int = { + a.nativeAddress compare b.nativeAddress + } + } + + ResourceScope.addToLocalScope(this) + + /** + * Releases all the [[NativeResource]] by calling + * the associated [[NativeResource.close()]] method + */ + override def close(): Unit = { + resourceQ.foreach(resource => if (resource != null) resource.dispose(false) ) + resourceQ.clear() + ResourceScope.removeFromLocalScope(this) + } + + /** + * Add a NativeResource to the scope + * @param resource + */ + def add(resource: NativeResource): Unit = { + resourceQ.+=(resource) + } + + /** + * Remove NativeResource from the Scope, this uses + * object equality to find the resource in the stack. + * @param resource + */ + def remove(resource: NativeResource): Unit = { + resourceQ.-=(resource) Review comment: same as above. ---------------------------------------------------------------- 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: [email protected] With regards, Apache Git Services
