]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.runtime/src/org/simantics/scl/runtime/SCLContext.java
Fixed multiple issues causing dangling references to discarded queries
[simantics/platform.git] / bundles / org.simantics.scl.runtime / src / org / simantics / scl / runtime / SCLContext.java
1 package org.simantics.scl.runtime;
2
3 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
4
5 import gnu.trove.map.hash.THashMap;
6
7 public class SCLContext extends THashMap<String,Object> {
8     private static ThreadLocal<SCLContext> CONTEXT = new ThreadLocal<SCLContext>();
9     private static ThreadLocal<OldContextNode> OLD_CONTEXT = new ThreadLocal<OldContextNode>();
10     
11     private static class OldContextNode {
12         final SCLContext context;
13         final OldContextNode next;
14         
15         public OldContextNode(SCLContext context, OldContextNode next) {
16             this.context = context;
17             this.next = next;
18         }
19     }
20     
21     public static SCLContext getCurrent() {
22         SCLContext context = CONTEXT.get();
23         if(context == null) {
24             context = new SCLContext();
25             CONTEXT.set(context);
26         }
27         return context;
28     }
29     
30     public static void push(SCLContext newContext) {
31         SCLContext oldContext = CONTEXT.get();
32         if(oldContext != null)
33             OLD_CONTEXT.set(new OldContextNode(oldContext, OLD_CONTEXT.get()));
34         CONTEXT.set(newContext);
35     }
36     
37     /**
38      * Creates a new context based on some properties of the current context.
39      * The new context is safe for use in parallel threads.
40      */
41     public static SCLContext createDerivedContext() {
42         SCLContext newContext = new SCLContext();
43         
44         SCLContext baseContext = CONTEXT.get();
45         if(baseContext != null) {
46             Object reportingHandler = baseContext.get(SCLReportingHandler.REPORTING_HANDLER);
47             if(reportingHandler != null)
48                 newContext.put(SCLReportingHandler.REPORTING_HANDLER, reportingHandler);
49         }
50         return newContext;
51     }
52     
53     public static void pop() {
54         OldContextNode node = OLD_CONTEXT.get();
55         if(node == null)
56             CONTEXT.set(null);
57         else {
58             CONTEXT.set(node.context);
59             OLD_CONTEXT.set(node.next);
60         }
61     }
62     
63     /*
64     @Override
65     public Object get(Object key) {
66         Object result = super.get(key);
67         System.out.println(this + ": " + key + " -> " + result);
68         return result;
69     }
70     
71     @Override
72     public Object put(String key, Object value) {
73         System.out.println(this + ": " + key + " <- " + value);
74         return super.put(key, value);
75     }*/
76 }