|
1 | 1 | package com.cloudata.structured.sql; |
2 | 2 |
|
| 3 | +import static com.google.common.base.Preconditions.checkNotNull; |
| 4 | + |
| 5 | +import java.util.concurrent.ExecutionException; |
3 | 6 | import java.util.concurrent.ExecutorService; |
4 | 7 | import java.util.concurrent.Executors; |
5 | 8 |
|
| 9 | +import javax.annotation.Nonnull; |
| 10 | +import javax.annotation.concurrent.Immutable; |
6 | 11 | import javax.inject.Inject; |
7 | 12 | import javax.inject.Singleton; |
8 | 13 |
|
| 14 | +import org.slf4j.Logger; |
| 15 | +import org.slf4j.LoggerFactory; |
| 16 | + |
9 | 17 | import com.cloudata.structured.StructuredStateMachine; |
10 | 18 | import com.cloudata.structured.StructuredStore; |
| 19 | +import com.google.common.base.Throwables; |
| 20 | +import com.google.common.cache.CacheBuilder; |
| 21 | +import com.google.common.cache.CacheLoader; |
| 22 | +import com.google.common.cache.LoadingCache; |
11 | 23 |
|
12 | 24 | @Singleton |
13 | 25 | public class SqlEngineFactory { |
| 26 | + private static final Logger log = LoggerFactory.getLogger(SqlEngineFactory.class); |
14 | 27 |
|
15 | 28 | @Inject |
16 | 29 | StructuredStateMachine stateMachine; |
17 | 30 |
|
18 | 31 | final ExecutorService executor = Executors.newCachedThreadPool(); |
19 | 32 |
|
20 | | - public SqlEngine get(long storeId) { |
21 | | - StructuredStore structuredStore = stateMachine.getStructuredStore(storeId); |
| 33 | + final LoadingCache<Long, SqlEngine> sqlEngineCache; |
22 | 34 |
|
23 | | - return new SqlEngine(structuredStore, executor); |
| 35 | + public SqlEngineFactory() { |
| 36 | + SqlEngineLoader loader = new SqlEngineLoader(); |
| 37 | + this.sqlEngineCache = CacheBuilder.newBuilder().recordStats().build(loader); |
24 | 38 | } |
25 | 39 |
|
| 40 | + public SqlEngine get(long storeId) { |
| 41 | + try { |
| 42 | + return sqlEngineCache.get(storeId); |
| 43 | + } catch (ExecutionException e) { |
| 44 | + throw Throwables.propagate(e); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + @Immutable |
| 49 | + final class SqlEngineLoader extends CacheLoader<Long, SqlEngine> { |
| 50 | + |
| 51 | + @Override |
| 52 | + public SqlEngine load(@Nonnull Long id) throws Exception { |
| 53 | + checkNotNull(id); |
| 54 | + try { |
| 55 | + StructuredStore structuredStore = stateMachine.getStructuredStore(id); |
| 56 | + |
| 57 | + return new SqlEngine(structuredStore, executor); |
| 58 | + } catch (Exception e) { |
| 59 | + log.warn("Error building SqlEngine", e); |
| 60 | + throw e; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
26 | 64 | } |
0 commit comments