1
1
package com .github .enablingflow .springbootdatamongomultitenant ;
2
2
3
+ import java .util .LinkedList ;
3
4
import java .util .concurrent .Callable ;
4
5
5
6
public class MultiTenantContext <T > {
6
7
private static final ThreadLocal <Boolean > asRoot = new ThreadLocal <>();
7
- private static final ThreadLocal <Object > asTenant = new ThreadLocal <>();
8
+ private static final ThreadLocal <LinkedList < Object > > asTenant = new ThreadLocal <>();
8
9
private static final ThreadLocal <Object > tenant = new ThreadLocal <>();
9
10
10
11
public T get () {
@@ -47,32 +48,27 @@ public <T> T performAsRoot(Callable<T> callable) throws Exception {
47
48
}
48
49
49
50
public void performAsTenant (T tenant , ThrowingRunnable runnable ) throws Exception {
50
- if (asTenant .get () != null && asTenant .get ().equals (tenant )) {
51
- runnable .run ();
52
- return ;
53
- } else if (asTenant .get () != null && !asTenant .get ().equals (tenant )) {
54
- throw new IllegalStateException ("Cannot change tenant" );
51
+ if (asTenant .get () == null ) {
52
+ asTenant .set (new LinkedList <>());
55
53
}
56
- asTenant .set (tenant );
54
+ asTenant .get (). add (tenant );
57
55
try {
58
56
runnable .run ();
59
57
} finally {
60
- asTenant .remove ();
58
+ asTenant .get (). pollLast ();
61
59
}
62
60
}
63
61
64
62
public <T > T performAsTenant (String tenant , Callable <T > callable ) throws Exception {
65
- if (asTenant .get () != null && asTenant .get ().equals (tenant )) {
66
- return callable .call ();
67
- } else if (asTenant .get () != null && !asTenant .get ().equals (tenant )) {
68
- throw new IllegalStateException ("Cannot change tenant" );
63
+ if (asTenant .get () == null ) {
64
+ asTenant .set (new LinkedList <>());
69
65
}
70
- asTenant .set (tenant );
66
+ asTenant .get (). add (tenant );
71
67
T result ;
72
68
try {
73
69
result = callable .call ();
74
70
} finally {
75
- asTenant .remove ();
71
+ asTenant .get (). pollLast ();
76
72
}
77
73
return result ;
78
74
}
@@ -82,10 +78,10 @@ public boolean isRoot() {
82
78
}
83
79
84
80
public boolean hasScopedTenant () {
85
- return asTenant .get () != null ;
81
+ return asTenant .get () != null && ! asTenant . get (). isEmpty () ;
86
82
}
87
83
88
84
public T getScopedTenant () {
89
- return (T ) asTenant .get ();
85
+ return (T ) asTenant .get (). getLast () ;
90
86
}
91
87
}
0 commit comments