Skip to content

Commit

Permalink
Use a single thread local with a custom object for the tenant
Browse files Browse the repository at this point in the history
  • Loading branch information
filiphr committed Oct 9, 2023
1 parent 476ad3b commit bcfdd1c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,37 @@
*/
package org.flowable.common.engine.impl.tenant;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.tenant.TenantContext;

/**
* @author Filip Hrisafov
*/
public class ThreadLocalTenantContext implements TenantContext {

protected final ThreadLocal<String> tenantId = ThreadLocal.withInitial(() -> {
throw new FlowableException("Tenant value has not been set");
});
protected final ThreadLocal<Boolean> tenantIdSet = ThreadLocal.withInitial(() -> Boolean.FALSE);
protected final ThreadLocal<Tenant> tenantId = new ThreadLocal<>();

@Override
public String getTenantId() {
return tenantId.get();
Tenant tenant = tenantId.get();
return tenant != null ? tenant.tenantId() : null;
}

@Override
public void setTenantId(String tenantId) {
this.tenantId.set(tenantId);
this.tenantIdSet.set(true);
this.tenantId.set(new Tenant(tenantId));
}

@Override
public void clearTenantId() {
tenantId.remove();
tenantIdSet.remove();
}

@Override
public boolean isTenantIdSet() {
return tenantIdSet.get();
return tenantId.get() != null;
}

protected record Tenant(String tenantId) {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
package org.flowable.common.engine.impl.tenant;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.tenant.TenantContext;
import org.junit.jupiter.api.Test;

Expand All @@ -28,9 +26,7 @@ class ThreadLocalTenantContextTest {

@Test
void getTenantId() {
assertThatThrownBy(() -> underTest.getTenantId())
.isExactlyInstanceOf(FlowableException.class)
.hasMessage("Tenant value has not been set");
assertThat(underTest.getTenantId()).isNull();

underTest.setTenantId("acme");
assertThat(underTest.getTenantId()).isEqualTo("acme");
Expand All @@ -39,9 +35,7 @@ void getTenantId() {
assertThat(underTest.getTenantId()).isEqualTo("muppets");

underTest.clearTenantId();
assertThatThrownBy(() -> underTest.getTenantId())
.isExactlyInstanceOf(FlowableException.class)
.hasMessage("Tenant value has not been set");
assertThat(underTest.getTenantId()).isNull();
}

@Test
Expand All @@ -53,5 +47,8 @@ void isTenantIdSet() {

underTest.clearTenantId();
assertThat(underTest.isTenantIdSet()).isFalse();

underTest.setTenantId(null);
assertThat(underTest.isTenantIdSet()).isTrue();
}
}

0 comments on commit bcfdd1c

Please sign in to comment.