MultitenantStorage { final S currentSlice() { TenantFunction<S> func = new TenantFunction<S>(isMultitenant()) { @Override public @Nullable S apply(@Nullable TenantId tenantId) { checkNotNull(tenantId); lock.lock(); try { return tenantSlices.computeIfAbsent(tenantId, id -> createSlice()); } finally { lock.unlock(); } } }; S result = func.execute(); checkNotNull(result, "Current tenant slice is null."); return result; } MultitenantStorage(boolean multitenant);   }
@Test @DisplayName("return same slice within single tenant and multitenant environment") void returnSameSlice() throws InterruptedException, ExecutionException { int numberOfTasks = 1000; Collection<Callable<TenantRecords>> tasks = newArrayListWithExpectedSize(numberOfTasks); for (int i = 0; i < numberOfTasks; i++) { tasks.add(() -> { TenantRecords<ProjectId> storage = multitenantStorage.currentSlice(); return storage; }); } List<Future<TenantRecords>> futures = executeInMultithreadedEnvironment(tasks); Set<TenantRecords> tenantRecords = convertFuturesToSetOfCompletedResults(futures); int expected = 1; assertEquals(expected, tenantRecords.size()); }