下面列出了com.google.common.util.concurrent.MoreExecutors#sameThreadExecutor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Executor provideThreadPoolExecutor(Provider<RequestScopeExecutor> executorProvider,
int threadCount, String name) {
if (threadCount == 0) {
return MoreExecutors.sameThreadExecutor();
}
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(name).build();
ExecutorService executor;
if (threadCount < 0) {
executor = Executors.newCachedThreadPool(threadFactory);
} else if (threadCount == 1) {
executor = Executors.newSingleThreadExecutor(threadFactory);
} else {
executor = Executors.newFixedThreadPool(threadCount, threadFactory);
}
RequestScopeExecutor scopeExecutor = executorProvider.get();
scopeExecutor.setExecutor(executor, name);
return scopeExecutor;
}
@Before
public void setUp() throws Exception {
t = new RuntimeException("the original problem");
Map<Input<?>, Object> emptyMap = Collections.emptyMap();
traverseState = new TraverseState(emptyMap, MoreExecutors.sameThreadExecutor(), true);
List<? extends NodeInfo> currentNodeParameters = ImmutableList.of(
new FakeNodeInfo("arg1", Collections .<NodeInfo>emptyList()),
new FakeNodeInfo("argument 2", Collections .<NodeInfo>emptyList())
);
currentNodeInfo = new FakeNodeInfo("the node", currentNodeParameters);
currentNodeValues = ImmutableList.<ListenableFuture<?>>of(
immediateFuture("value 1"),
immediateFuture("andra värdet")
);
currentCall = new TraverseState.FutureCallInformation(currentNodeInfo, currentNodeValues);
}
private QuorumJournalManager createSpyingQJM()
throws IOException, URISyntaxException {
AsyncLogger.Factory spyFactory = new AsyncLogger.Factory() {
@Override
public AsyncLogger createLogger(Configuration conf, NamespaceInfo nsInfo,
String journalId, InetSocketAddress addr) {
AsyncLogger logger = new IPCLoggerChannel(conf, nsInfo, journalId, addr) {
protected ExecutorService createSingleThreadExecutor() {
// Don't parallelize calls to the quorum in the tests.
// This makes the tests more deterministic.
return MoreExecutors.sameThreadExecutor();
}
};
return Mockito.spy(logger);
}
};
return closeLater(new QuorumJournalManager(
conf, cluster.getQuorumJournalURI(JID), FAKE_NSINFO, spyFactory));
}
private QuorumJournalManager createSpyingQJM()
throws IOException, URISyntaxException {
AsyncLogger.Factory spyFactory = new AsyncLogger.Factory() {
@Override
public AsyncLogger createLogger(Configuration conf, NamespaceInfo nsInfo,
String journalId, InetSocketAddress addr) {
AsyncLogger logger = new IPCLoggerChannel(conf, nsInfo, journalId, addr) {
protected ExecutorService createSingleThreadExecutor() {
// Don't parallelize calls to the quorum in the tests.
// This makes the tests more deterministic.
return MoreExecutors.sameThreadExecutor();
}
};
return Mockito.spy(logger);
}
};
return closeLater(new QuorumJournalManager(
conf, cluster.getQuorumJournalURI(JID), FAKE_NSINFO, spyFactory));
}
public <T> void invokeAll(Collection<Callable<T>> commands) throws GitException, InterruptedException {
ExecutorService executorService = null;
try {
if (threads == 1) {
executorService = MoreExecutors.sameThreadExecutor();
} else {
ThreadFactory threadFactory = new ExceptionCatchingThreadFactory(new NamingThreadFactory(new DaemonThreadFactory(), GitCommandsExecutor.class.getSimpleName()));
executorService = Executors.newFixedThreadPool(threads, threadFactory);
}
invokeAll(executorService, commands);
} finally {
if (executorService != null) {
executorService.shutdownNow();
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
listener.getLogger().println("[WARNING] Threads did not terminate properly");
}
}
}
}
@Test
public void testFileVariables() throws Exception {
// make sure we can handle short file names
FilePath path = new FilePath(new LocalChannel(MoreExecutors.sameThreadExecutor()),
"/Users/nothing");
List<PackerFileEntry> fileEntries = new ArrayList<>();
fileEntries.add(new PackerFileEntry("a", "oqiwueroqiweur"));
PackerPublisher placeHolder = new PackerPublisher(name,
jsonProjectTemplate, "", PLUGIN_HOME,
localParams, fileEntries, false, null);
String result = placeHolder.createTempFileEntries(path);
System.out.println("testFileVariables result: " + result);
}
public DefaultTransactionExecutor(TransactionSystemClient txClient,
Iterable<TransactionAware> txAwares,
RetryStrategy retryStrategy) {
super(MoreExecutors.sameThreadExecutor());
this.txAwares = ImmutableList.copyOf(txAwares);
this.txClient = txClient;
this.retryStrategy = retryStrategy;
}
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final DeltaStore deltaStore = new MemoryDeltaStore();
final Executor persistExecutor = MoreExecutors.sameThreadExecutor();
final Executor storageContinuationExecutor = MoreExecutors.sameThreadExecutor();
LocalWaveletContainer.Factory localWaveletContainerFactory =
new LocalWaveletContainer.Factory() {
@Override
public LocalWaveletContainer create(WaveletNotificationSubscriber notifiee,
WaveletName waveletName, String domain) {
WaveletState waveletState;
try {
waveletState = DeltaStoreBasedWaveletState.create(deltaStore.open(waveletName),
persistExecutor);
} catch (PersistenceException e) {
throw new RuntimeException(e);
}
return new LocalWaveletContainerImpl(waveletName, notifiee,
Futures.immediateFuture(waveletState), DOMAIN, storageContinuationExecutor);
}
};
waveletStore = mock(DeltaAndSnapshotStore.class);
Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>of(
"core.wave_cache_size", 1000,
"core.wave_cache_expire", "60m")
);
waveMap =
new WaveMap(waveletStore, notifiee, localWaveletContainerFactory,
remoteWaveletContainerFactory, "example.com", config, storageContinuationExecutor);
}
public MultiDCDataStores(int numDCs, boolean asyncCompacter, MetricRegistry metricRegistry) {
_tableDao = new InMemoryTableDAO();
// create multiple data stores, one per data center
_inMemoryDaos = new InMemoryDataReaderDAO[numDCs];
_replDaos = new ReplicatingDataWriterDAO[numDCs];
for (int i = 0; i < numDCs; i++) {
_inMemoryDaos[i] = new InMemoryDataReaderDAO();
_replDaos[i] = new ReplicatingDataWriterDAO(_inMemoryDaos[i]);
}
// connect each data store to every other data store
for (ReplicatingDataWriterDAO src : _replDaos) {
for (ReplicatingDataWriterDAO dst : _replDaos) {
if (src != dst) {
src.replicateTo(dst);
}
}
}
_historyStores = new HistoryStore[numDCs];
_stores = new DataStore[numDCs];
for (int i = 0; i < numDCs; i++) {
_historyStores[i] = new InMemoryHistoryStore();
if (asyncCompacter) {
_stores[i] = new DefaultDataStore(new SimpleLifeCycleRegistry(), metricRegistry, new DatabusEventWriterRegistry(), _tableDao,
_inMemoryDaos[i].setHistoryStore(_historyStores[i]), _replDaos[i], new NullSlowQueryLog(), _historyStores[i],
Optional.<URI>absent(), new InMemoryCompactionControlSource(), Conditions.alwaysFalse(), new DiscardingAuditWriter(), new InMemoryMapStore<>(), Clock.systemUTC());
} else {
_stores[i] = new DefaultDataStore(new DatabusEventWriterRegistry(), _tableDao, _inMemoryDaos[i].setHistoryStore(_historyStores[i]),
_replDaos[i], new NullSlowQueryLog(), MoreExecutors.sameThreadExecutor(), _historyStores[i],
Optional.<URI>absent(), new InMemoryCompactionControlSource(), Conditions.alwaysFalse(),
new DiscardingAuditWriter(), new InMemoryMapStore<>(), metricRegistry, Clock.systemUTC());
}
}
}
@Before
public final void setUp() throws Exception {
logFileService = new LogFileService(testDirectory);
logFileService.clearAllLogs();
log = new QuorumDelegatingLog(
logFileService,
new WrappingKeySerializingExecutor(MoreExecutors.sameThreadExecutor()),
NavigableMapOLogEntryOracle::new,
InMemoryPersistenceNavigator::new);
log.openAsync(quorumId).get();
}
@Override
public void setUp() throws Exception {
super.setUp();
SessionManager sessionManager = Mockito.mock(SessionManager.class);
org.eclipse.jetty.server.SessionManager jettySessionManager =
Mockito.mock(org.eclipse.jetty.server.SessionManager.class);
/*
* NOTE: Specifying port zero (0) causes the OS to select a random port.
* This allows the test to run without clashing with any potentially in-use port.
*/
server =
new ServerRpcProvider(new InetSocketAddress[] {new InetSocketAddress("localhost", 0)},
new String[] {"./war"}, sessionManager, null, null, false, null, null,
MoreExecutors.sameThreadExecutor(), 0, 2, 60, 3600, 3600, "localhost");
final Map<String, Object> props = new HashMap<>();
props.put("network.websocket_max_idle_time", 0);
props.put("network.websocket_max_message_size", 2);
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(ServerRpcProvider.class).toInstance(server);
bind(Config.class).toInstance(ConfigFactory.parseMap(props));
bind(SessionManager.class).toInstance(sessionManager);
bind(NamingStore.class).toInstance(Mockito.mock(NamingStore.class));
bind(WaveletProvider.class).toInstance(Mockito.mock(WaveletProvider.class));
}
});
server.startWebSocketServer(injector);
}
@Override
protected ExecutorService createSingleThreadExecutor() {
return MoreExecutors.sameThreadExecutor();
}
@Override
protected ExecutorService createSingleThreadExecutor() {
return MoreExecutors.sameThreadExecutor();
}
@Ignore("TODO fails as of 0b27f364f99ec98cb616d4f0cfc0858ecf339852 in 1.559")
@Test
public void testPluginInJobWindowsPathExec() throws Exception {
final String jsonText = "{ \"here\": \"i am\"}";
PackerInstallation installation = new PackerInstallation(name, home,
params, createTemplateModeJson(TemplateMode.TEXT, jsonText), emptyFileEntries, null);
final String pluginHome = "bin";
PackerPublisher placeHolder = new PackerPublisher(name,
null, null, pluginHome, localParams, emptyFileEntries, false, null);
PackerInstallation[] installations = new PackerInstallation[1];
installations[0] = installation;
placeHolder.getDescriptor().setInstallations(installations);
StaplerRequest mockReq = mock(StaplerRequest.class);
when(mockReq.bindJSON(any(Class.class), any(JSONObject.class))).thenReturn(placeHolder);
JSONObject formJson = new JSONObject();
formJson.put("templateMode", createTemplateModeJson(TemplateMode.TEXT, jsonText));
PackerPublisher plugin = placeHolder.getDescriptor().newInstance(mockReq, formJson);
assertEquals(pluginHome, plugin.getPackerHome());
assertEquals(localParams, plugin.getParams());
assertTrue(plugin.isTextTemplate());
assertFalse(plugin.isFileTemplate());
assertFalse(plugin.isGlobalTemplate());
assertEquals(jsonText, plugin.getJsonTemplateText());
FreeStyleProject project = jenkins.createFreeStyleProject();
FreeStyleBuild build = project.scheduleBuild2(0).get();
FilePath winFilePath = new FilePath(new LocalChannel(MoreExecutors.sameThreadExecutor()), "C:\\");
Node mockNode = mock(Node.class);
when(mockNode.createPath(anyString())).thenReturn(winFilePath);
FreeStyleBuild mockBuildWin = spy(build);
when(mockBuildWin.getBuiltOn()).thenReturn(mockNode);
Launcher launcherMock = mock(Launcher.class);
TaskListener listenerMock = mock(TaskListener.class);
String exec = plugin.getRemotePackerExec(mockBuildWin, launcherMock, listenerMock);
// C:\bin\packer.exe
assertEquals(mockBuildWin.getWorkspace().getRemote() + pluginHome + "\\" + PackerInstallation.WINDOWS_PACKER_COMMAND,
exec);
}
@Test
public void testDrainQueueForAllRedundantItemsInOnePeek() {
Supplier<Condition> ignoreReEtl = Suppliers.ofInstance(
Conditions.not(Conditions.mapBuilder().matches(UpdateRef.TAGS_NAME, Conditions.containsAny("re-etl")).build()));
final List<String> actualIds = Lists.newArrayList();
DedupEventStore dedupEventStore = mock(DedupEventStore.class);
DatabusEventStore eventStore = new DatabusEventStore(mock(EventStore.class), dedupEventStore, Suppliers.ofInstance(true)) {
@Override
public boolean peek(String subscription, EventSink sink) {
// The single peek will supply 3 redundant events followed by an empty queue return value
for (int i = 0; i < 3; i++) {
String id = "a" + i;
actualIds.add(id);
assertTrue(sink.remaining() > 0);
EventSink.Status status = sink.accept(newEvent(id, "table", "key", TimeUUIDs.newUUID()));
assertEquals(status, EventSink.Status.ACCEPTED_CONTINUE);
}
return false;
}
};
Map<String, Object> content = entity("table", "key", ImmutableMap.of("rating", "5"));
// Create a custom annotated content which returns all changes as redundant
DataProvider.AnnotatedContent annotatedContent = mock(DataProvider.AnnotatedContent.class);
when(annotatedContent.getContent()).thenReturn(content);
when(annotatedContent.isChangeDeltaRedundant(any(UUID.class))).thenReturn(true); // Items are redundant.
DefaultDatabus testDatabus = new DefaultDatabus(
mock(LifeCycleRegistry.class), mock(DatabusEventWriterRegistry.class), new TestDataProvider().add(annotatedContent), mock(SubscriptionDAO.class),
eventStore, mock(SubscriptionEvaluator.class), mock(JobService.class),
mock(JobHandlerRegistry.class), mock(DatabusAuthorizer.class), "systemOwnerId", ignoreReEtl, MoreExecutors.sameThreadExecutor(),
1, key -> 0, new MetricRegistry(), Clock.systemUTC());
// Call the drainQueue method.
testDatabus.drainQueueAsync("test-subscription");
// deletes should happen.
verify(dedupEventStore).delete("test-subscription", actualIds, true);
verifyNoMoreInteractions(dedupEventStore);
// the entry should be removed from map.
assertEquals(testDatabus.getDrainedSubscriptionsMap().size(), 0);
}
@Test
public void testLazyPollResult() {
Supplier<Condition> acceptAll = Suppliers.ofInstance(Conditions.alwaysTrue());
TestDataProvider testDataProvider = new TestDataProvider();
final Set<String> expectedIds = Sets.newHashSet();
DatabusEventStore eventStore = mock(DatabusEventStore.class);
when(eventStore.poll(eq("subscription"), eq(Duration.ofMinutes(1)), any(EventSink.class)))
.thenAnswer(invocationOnMock -> {
EventSink sink = (EventSink) invocationOnMock.getArguments()[2];
// Return 40 updates for records from 40 unique tables
for (int iteration = 1; iteration <= 40; iteration++) {
String id = "a" + iteration;
addToPoll(id, "table-" + iteration, "key-" + iteration, false, sink, testDataProvider);
expectedIds.add(id);
}
return false;
});
SubscriptionDAO subscriptionDAO = mock(SubscriptionDAO.class);
when(subscriptionDAO.getSubscription("subscription")).thenReturn(
new DefaultOwnedSubscription("subscription", Conditions.alwaysTrue(), new Date(1489090060000L),
Duration.ofSeconds(30), "owner"));
DatabusAuthorizer databusAuthorizer = ConstantDatabusAuthorizer.ALLOW_ALL;
// Use a clock that advances 1 second after the first call
Clock clock = mock(Clock.class);
when(clock.millis())
.thenReturn(1489090000000L)
.thenReturn(1489090001000L);
DefaultDatabus testDatabus = new DefaultDatabus(
mock(LifeCycleRegistry.class), mock(DatabusEventWriterRegistry.class), testDataProvider, subscriptionDAO,
eventStore, mock(SubscriptionEvaluator.class), mock(JobService.class),
mock(JobHandlerRegistry.class), databusAuthorizer, "systemOwnerId", acceptAll, MoreExecutors.sameThreadExecutor(),
1, key -> 0, new MetricRegistry(), clock);
PollResult pollResult = testDatabus.poll("owner", "subscription", Duration.ofMinutes(1), 500);
assertFalse(pollResult.hasMoreEvents());
Iterator<Event> events = pollResult.getEventIterator();
Set<String> actualIds = Sets.newHashSet();
// Read the entire event list
while (events.hasNext()) {
actualIds.add(events.next().getEventKey());
}
assertEquals(actualIds, expectedIds);
// Events should have been loaded in 3 batches. The first was a synchronous batch that loaded the first 10 events.
// The seconds should have loaded 25 more events. The third loaded the final 5 events;
List<List<Coordinate>> executions = testDataProvider.getExecutions();
assertEquals(executions.size(), 3);
assertEquals(executions.get(0).size(), 10);
assertEquals(executions.get(1).size(), 25);
assertEquals(executions.get(2).size(), 5);
}
public InMemoryDataStore(DatabusEventWriterRegistry eventWriterRegistry, InMemoryDataReaderDAO dataDao, MetricRegistry metricRegistry) {
super(eventWriterRegistry, new InMemoryTableDAO(), dataDao, dataDao,
new NullSlowQueryLog(), MoreExecutors.sameThreadExecutor(), new InMemoryHistoryStore(),
Optional.<URI>absent(), new InMemoryCompactionControlSource(), Conditions.alwaysFalse(),
new DiscardingAuditWriter(), new InMemoryMapStore<>(), metricRegistry, Clock.systemUTC());
}
@Ignore("TODO fails as of 0b27f364f99ec98cb616d4f0cfc0858ecf339852 in 1.559")
@Test
public void testPluginInJobWindowsAbsPathExec() throws Exception {
final String jsonText = "{ \"here\": \"i am\"}";
PackerInstallation installation = new PackerInstallation(name, home,
params, createTemplateModeJson(TemplateMode.TEXT, jsonText), emptyFileEntries, null);
final String pluginHome = "D:\\bin";
PackerPublisher placeHolder = new PackerPublisher(name,
null, null, pluginHome, localParams, emptyFileEntries, false, null);
PackerInstallation[] installations = new PackerInstallation[1];
installations[0] = installation;
placeHolder.getDescriptor().setInstallations(installations);
StaplerRequest mockReq = mock(StaplerRequest.class);
when(mockReq.bindJSON(any(Class.class), any(JSONObject.class))).thenReturn(placeHolder);
JSONObject formJson = new JSONObject();
formJson.put("templateMode", createTemplateModeJson(TemplateMode.TEXT, jsonText));
PackerPublisher plugin = placeHolder.getDescriptor().newInstance(mockReq, formJson);
assertEquals(pluginHome, plugin.getPackerHome());
assertEquals(localParams, plugin.getParams());
assertTrue(plugin.isTextTemplate());
assertFalse(plugin.isFileTemplate());
assertFalse(plugin.isGlobalTemplate());
assertEquals(jsonText, plugin.getJsonTemplateText());
FreeStyleProject project = jenkins.createFreeStyleProject();
FreeStyleBuild build = project.scheduleBuild2(0).get();
FilePath winFilePath = new FilePath(new LocalChannel(MoreExecutors.sameThreadExecutor()), "C:\\");
Node mockNode = mock(Node.class);
when(mockNode.createPath(anyString())).thenReturn(winFilePath);
FreeStyleBuild mockBuildWin = spy(build);
when(mockBuildWin.getBuiltOn()).thenReturn(mockNode);
Launcher launcherMock = mock(Launcher.class);
TaskListener listenerMock = mock(TaskListener.class);
String exec = plugin.getRemotePackerExec(mockBuildWin, launcherMock, listenerMock);
// D:\bin\\packer.exe
assertEquals(pluginHome + "\\" + PackerInstallation.WINDOWS_PACKER_COMMAND, exec);
}
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
wavesViews.put(USER1, wavesViewUser1);
wavesViews.put(USER2, wavesViewUser2);
wavesViews.put(SHARED_USER, wavesViewUser3);
when(waveViewProvider.retrievePerUserWaveView(USER1)).thenReturn(wavesViewUser1);
when(waveViewProvider.retrievePerUserWaveView(USER2)).thenReturn(wavesViewUser2);
when(waveViewProvider.retrievePerUserWaveView(SHARED_USER)).thenReturn(wavesViewUser3);
ConversationUtil conversationUtil = new ConversationUtil(idGenerator);
WaveDigester digester = new WaveDigester(conversationUtil);
final DeltaStore deltaStore = new MemoryDeltaStore();
final Executor persistExecutor = MoreExecutors.sameThreadExecutor();
final Executor storageContinuationExecutor = MoreExecutors.sameThreadExecutor();
final Executor lookupExecutor = MoreExecutors.sameThreadExecutor();
final AccessController accessController = mock(AccessController.class);
LocalWaveletContainer.Factory localWaveletContainerFactory =
new LocalWaveletContainer.Factory() {
@Override
public LocalWaveletContainer create(WaveletNotificationSubscriber notifiee,
WaveletName waveletName, String domain) {
WaveletState waveletState;
try {
waveletState = DeltaStoreBasedWaveletState.create(deltaStore.open(waveletName),
persistExecutor);
} catch (PersistenceException e) {
throw new RuntimeException(e);
}
return new LocalWaveletContainerImpl(waveletName, notifiee,
Futures.immediateFuture(waveletState), DOMAIN, storageContinuationExecutor,
accessController);
}
};
Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>of(
"core.wave_cache_size", 1000,
"core.wave_cache_expire", "60m")
);
waveMap =
new WaveMap(waveletStore, notifiee, localWaveletContainerFactory,
remoteWaveletContainerFactory, DOMAIN, config, lookupExecutor);
searchProvider = new SimpleSearchProviderImpl(DOMAIN, digester, waveMap, waveViewProvider);
}
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
wavesViews.put(USER1, wavesViewUser1);
wavesViews.put(USER2, wavesViewUser2);
wavesViews.put(SHARED_USER, wavesViewUser3);
when(waveViewProvider.retrievePerUserWaveView(USER1)).thenReturn(wavesViewUser1);
when(waveViewProvider.retrievePerUserWaveView(USER2)).thenReturn(wavesViewUser2);
when(waveViewProvider.retrievePerUserWaveView(SHARED_USER)).thenReturn(wavesViewUser3);
ConversationUtil conversationUtil = new ConversationUtil(idGenerator);
WaveDigester digester = new WaveDigester(conversationUtil);
final DeltaStore deltaStore = new MemoryDeltaStore();
final Executor persistExecutor = MoreExecutors.sameThreadExecutor();
final Executor storageContinuationExecutor = MoreExecutors.sameThreadExecutor();
final Executor lookupExecutor = MoreExecutors.sameThreadExecutor();
LocalWaveletContainer.Factory localWaveletContainerFactory =
new LocalWaveletContainer.Factory() {
@Override
public LocalWaveletContainer create(WaveletNotificationSubscriber notifiee,
WaveletName waveletName, String domain) {
WaveletState waveletState;
try {
waveletState = DeltaStoreBasedWaveletState.create(deltaStore.open(waveletName),
persistExecutor);
} catch (PersistenceException e) {
throw new RuntimeException(e);
}
return new LocalWaveletContainerImpl(waveletName, notifiee,
Futures.immediateFuture(waveletState), DOMAIN, storageContinuationExecutor);
}
};
Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>of(
"core.wave_cache_size", 1000,
"core.wave_cache_expire", "60m")
);
waveMap =
new WaveMap(waveletStore, notifiee, localWaveletContainerFactory,
remoteWaveletContainerFactory, DOMAIN, config, lookupExecutor);
searchProvider = new SimpleSearchProviderImpl(DOMAIN, digester, waveMap, waveViewProvider);
}