Github user marmbrus commented on a diff in the pull request:
https://github.com/apache/spark/pull/8909#discussion_r41421569
--- Diff: sql/core/src/main/scala/org/apache/spark/sql/SQLContext.scala ---
@@ -1208,36 +1204,72 @@ object SQLContext {
private val INSTANTIATION_LOCK = new Object()
/**
- * Reference to the last created SQLContext.
+ * The active SQLContext for threads.
+ */
+ private val activeContexts: InheritableThreadLocal[SQLContext] =
+ new InheritableThreadLocal[SQLContext]
+
+ /**
+ * Reference to the created SQLContext.
*/
- @transient private val lastInstantiatedContext = new
AtomicReference[SQLContext]()
+ @transient private val instantiatedContext = new
AtomicReference[SQLContext]()
/**
* Get the singleton SQLContext if it exists or create a new one using
the given SparkContext.
+ *
* This function can be used to create a singleton SQLContext object
that can be shared across
* the JVM.
+ *
+ * If there an active SQLContext for current thread, it will returned
instead of the global one.
*/
def getOrCreate(sparkContext: SparkContext): SQLContext = {
+ val ctx = activeContexts.get()
+ if (ctx != null) {
+ return ctx
+ }
+
INSTANTIATION_LOCK.synchronized {
- if (lastInstantiatedContext.get() == null) {
+ val ctx = instantiatedContext.get()
+ if (ctx == null) {
new SQLContext(sparkContext)
+ } else {
+ ctx
}
}
- lastInstantiatedContext.get()
}
- private[sql] def clearLastInstantiatedContext(): Unit = {
+ private[sql] def clearInstantiatedContext(): Unit = {
+ INSTANTIATION_LOCK.synchronized {
+ instantiatedContext.set(null)
+ }
+ }
+
+ private[sql] def clearTheInstantiatedContext(sqlContext: SQLContext):
Unit = {
INSTANTIATION_LOCK.synchronized {
- lastInstantiatedContext.set(null)
+ instantiatedContext.compareAndSet(sqlContext, null)
}
}
- private[sql] def setLastInstantiatedContext(sqlContext: SQLContext):
Unit = {
+ private[sql] def setInstantiatedContext(sqlContext: SQLContext): Unit = {
INSTANTIATION_LOCK.synchronized {
- lastInstantiatedContext.set(sqlContext)
+ instantiatedContext.compareAndSet(null, sqlContext)
}
}
+ /*
+ * Set a SQLContext for current thread
--- End diff --
"Changes the SQLContext that will be returned in this thread and its
children when `SQLContext.getOrCreate()` is called. This can be used to ensure
that a given thread receives a SQLContext with an isolated session, instead of
the global (first created) context."
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]