Jave interrupted thread

60 Jave code examples are found related to " interrupted thread". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: BlockingHttpClientTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void autoblockWontLeaveStatusThreadInterrupted() throws Exception {
  when(httpClient.execute(any(HttpHost.class), any(), any(HttpContext.class))).thenReturn(httpResponse);
  when(httpResponse.getStatusLine()).thenReturn(statusLine);
  when(statusLine.getStatusCode()).thenReturn(SC_BAD_GATEWAY);

  Config config = new Config();
  config.autoBlock = true;

  boolean[] statusThreadLeftInterrupted = new boolean[1];

  BlockingHttpClient client = new BlockingHttpClient(httpClient, config,
      (oldStatus, newStatus) -> statusThreadLeftInterrupted[0] = Thread.currentThread().isInterrupted(),
      true, autoBlockConfiguration);

  client.scheduleCheckStatus(httpHost.toURI(), now().plusMillis(100));

  Thread.sleep(500);

  assertThat(statusThreadLeftInterrupted[0], is(false));

  client.close();
}
 
Example 2
Source File: WebAsyncManagerTimeoutTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void startCallableProcessingTimeoutAndCheckThreadInterrupted() throws Exception {

	StubCallable callable = new StubCallable();
	Future future = mock(Future.class);

	AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class);
	when(executor.submit(any(Runnable.class))).thenReturn(future);

	this.asyncManager.setTaskExecutor(executor);
	this.asyncManager.startCallableProcessing(callable);

	this.asyncWebRequest.onTimeout(ASYNC_EVENT);

	assertTrue(this.asyncManager.hasConcurrentResult());

	verify(future).cancel(true);
	verifyNoMoreInteractions(future);
}
 
Example 3
Source File: ExceptionUtilsTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void propagateVoidSetsThreadInterruptFlagWhenMappingInterruptedException()
    throws InterruptedException {
    // Arrange:
    final InterruptedExceptionTestRunner runner =
        new InterruptedExceptionTestRunner(
            () -> {
                ExceptionUtils.propagateVoid(() -> Thread.sleep(1000));
                return null;
            });

    // Act:
    runner.run();

    // Assert:
    MatcherAssert.assertThat(runner.isInterruptedPreRun(), IsEqual.equalTo(false));
    MatcherAssert.assertThat(runner.isInterruptedPostRun(), IsEqual.equalTo(true));
}
 
Example 4
Source File: StopThreadManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {

    int interval = 50;

    ControlSubThread controlSubThread = new ControlSubThread(interval);
    controlSubThread.start();

    // Give things a chance to get set up
    Thread.sleep(interval);
    assertTrue(controlSubThread.isRunning());
    assertFalse(controlSubThread.isStopped());

    // Stop it and make sure the flags have been reversed
    controlSubThread.interrupt();

    // Wait less than the time we would normally sleep, and make sure we exited.
    Awaitility.await()
        .pollDelay(2, TimeUnit.MILLISECONDS)
      .atMost(interval/ 10, TimeUnit.MILLISECONDS)
      .until(controlSubThread::isStopped);
}
 
Example 5
Source File: ThreadInterruptedCompletableFuture.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
    cancel = true;

    if (this.isDone() || this.isCompletedExceptionally()) {
        LOGGER.warn("Can not be canceled because the caller future isDone or isCompletedExceptionally");
        return false;
    }

    while (thread == null) {
        try {
            LOGGER.warn("Waiting 1s for taskThread to be set...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOGGER.warn(e.toString(), e);
            Thread.currentThread().interrupt();
            return false;
        }
    }

    thread.interrupt();
    return true;
}
 
Example 6
Source File: RecordingWriterTests.java    From aeron with Apache License 2.0 6 votes vote down vote up
@Test
void onBlockThrowsArchiveExceptionIfCurrentThreadWasInterrupted() throws IOException
{
    final Image image = mockImage(0L);
    final RecordingWriter recordingWriter = new RecordingWriter(
        1, 0, SEGMENT_LENGTH, image, new Context().archiveDir(archiveDir), null, null, null);
    recordingWriter.init();

    assertFalse(Thread.interrupted());
    try
    {
        Thread.currentThread().interrupt();
        final ArchiveException exception = assertThrows(
            ArchiveException.class,
            () -> recordingWriter.onBlock(new UnsafeBuffer(allocate(32)), 0, 10, 5, 8));
        assertEquals(GENERIC, exception.errorCode());
        assertEquals("file closed by interrupt, recording aborted", exception.getMessage());
        assertTrue(recordingWriter.isClosed());
    }
    finally
    {
        assertTrue(Thread.interrupted());
    }
}
 
Example 7
Source File: TestNotificationExpirationManagement.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
@Test
public void testSubscriptionRunnerWithInterruptedThreadRedisException() {
  SessionManager sessionManager = mock(SessionManager.class);
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      Thread.currentThread().interrupt();
      throw new DummyException("Test");
    }
  }).when(redis).psubscribe(any(RedisFacade.RedisPubSub.class), anyString());
  doAnswer(new Answer<Boolean>() {
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
      return true;
    }
  }).when(redis).isRedisException(any(DummyException.class));
  SubscriptionRunner runner = spy(expiration.new SubscriptionRunner(sessionManager));
  runner.run();
  verify(runner, never()).doWait();
}
 
Example 8
Source File: CircuitBreakerFutureTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecorateFutureAndInterruptedExceptionThrownByCallingThread()
    throws Exception {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");

    //long running task
    final Future<String> future = mock(Future.class);
    when(future.get()).thenThrow(new InterruptedException());

    CircuitBreakerFuture<String> decoratedFuture = new CircuitBreakerFuture<>(circuitBreaker,
        future);

    Throwable thrown = catchThrowable(() -> decoratedFuture.get());
    //If interrupt is called on the Task thread than InterruptedException is thrown wrapped in
    // ExecutionException where as if current thread gets interrupted it throws
    // InterruptedException directly.
    assertThat(thrown).isInstanceOf(InterruptedException.class);

    assertThat(circuitBreaker.getMetrics().getNumberOfBufferedCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getMetrics().getNumberOfFailedCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);

    then(future).should().get();
}
 
Example 9
Source File: CircuitBreakerFutureTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecorateFutureAndInterruptedExceptionThrownByTaskThread() throws Exception {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");

    final Future<String> future = mock(Future.class);
    when(future.get(anyLong(), any(TimeUnit.class)))
        .thenThrow(new ExecutionException(new InterruptedException()));

    CircuitBreakerFuture<String> decoratedFuture = new CircuitBreakerFuture<>(circuitBreaker,
        future);
    Throwable thrown = catchThrowable(() -> decoratedFuture.get(5, TimeUnit.SECONDS));

    //If interrupt is called on the Task thread than InterruptedException is thrown wrapped in
    // ExecutionException where as if current thread gets interrupted it throws
    // InterruptedException directly.
    assertThat(thrown).isInstanceOf(ExecutionException.class)
        .hasCauseInstanceOf(InterruptedException.class);

    assertThat(circuitBreaker.getMetrics().getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(circuitBreaker.getMetrics().getNumberOfFailedCalls()).isEqualTo(1);
    assertThat(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()).isEqualTo(0);
    assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);

    then(future).should().get(anyLong(), any(TimeUnit.class));
}
 
Example 10
Source File: ThreadUtils.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 恢复中断。
 * 如果是中断异常,则恢复线程中断状态。
 *
 * @param t 异常
 */
public static void recoveryInterrupted(Throwable t) {
    if (t instanceof InterruptedException) {
        try {
            Thread.currentThread().interrupt();
        } catch (SecurityException ignore) {
        }
    }
}
 
Example 11
Source File: ExceptionUtilsTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void propagateVoidSetsThreadInterruptFlagWhenMappingInterruptedException() throws InterruptedException {
	// Arrange:
	final InterruptedExceptionTestRunner runner = new InterruptedExceptionTestRunner(() -> {
		ExceptionUtils.propagateVoid(() -> Thread.sleep(1000));
		return null;
	});

	// Act:
	runner.run();

	// Assert:
	Assert.assertThat(runner.isInterruptedPreRun(), IsEqual.equalTo(false));
	Assert.assertThat(runner.isInterruptedPostRun(), IsEqual.equalTo(true));
}
 
Example 12
Source File: ThreadUtils.java    From curator with Apache License 2.0 5 votes vote down vote up
public static boolean checkInterrupted(Throwable e)
{
    if ( e instanceof InterruptedException )
    {
        Thread.currentThread().interrupt();
        return true;
    }
    return false;
}
 
Example 13
Source File: ThreadUtils.java    From xian with Apache License 2.0 5 votes vote down vote up
public static void checkInterrupted(Throwable e)
{
    if ( e instanceof InterruptedException )
    {
        Thread.currentThread().interrupt();
    }
}
 
Example 14
Source File: Basic.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void threadInterrupted() throws Throwable{
    int count = 0;
    Basic test = new Basic();
    CountDownLatch latch = new CountDownLatch(3);
    Awaiter a[] = new Awaiter[12];

    for (int i = 0; i < 3; i++) {
        CountDownLatch gate = new CountDownLatch(4);
        AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
        AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count-1].interrupt();
        test.toTheStartingGate(gate);
        System.out.println("Main Thread: " + latch.toString());
        latch.countDown();
        checkCount(latch, 2-i);
    }
    for (int i = 0; i < 12; i++)
        a[i].join();

    for (int i = 0; i < 12; i++)
        checkResult(a[i],
                    (i % 4) == 3 ? InterruptedException.class : null);
}
 
Example 15
Source File: InstanceBasedAutomationResultBuilderTest.java    From bromium with MIT License 5 votes vote down vote up
@Test
public void correctlyCreatesInterruptedExceptionThread() {
    Throwable throwable = new InterruptedException();
    AutomationResultBuilder automationResultBuilder = new InstanceBasedAutomationResultBuilder();
    AutomationResult automationResult = automationResultBuilder.buildAutomationResult(throwable);
    assertEquals(automationResult, AutomationResult.INTERRUPTED);
}
 
Example 16
Source File: VirtualUserControllerTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void testThreadGroupInterrupted() {
    VirtualUserController vuc = new VirtualUserController();
    vuc.addTestElement(new DebugSampler());

    ArrivalsThreadGroup tg = new ArrivalsThreadGroup() {
        @Override
        public boolean isRunning() {
            return false;
        }
    };
    tg.addTestElement(vuc);
    vuc.setOwner(tg);
    assertNull(vuc.next());
}
 
Example 17
Source File: AzureKeyVaultClientCredentialsTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void threadInterruptedExceptionIsCaughtAndLogged() throws ExecutionException, InterruptedException {
    Future<AuthenticationResult> response = mock(Future.class);
    when(response.get()).thenThrow(InterruptedException.class);
    when(authenticationContext.acquireToken(anyString(), any(ClientCredential.class), any())).thenReturn(response);

    credentials.doAuthenticate("auth", "resource", null);
}
 
Example 18
Source File: ThreadAssertionDefault.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
@Override
public ThreadAssertion isInterrupted() {

  if (!candidate.isInterrupted()) {
    String message = "Current thread '" + candidate.getName() +
            "' is expected to be interrupted but not.";
    throw exceptionMapper.apply(message);
  }
  return this;
}
 
Example 19
Source File: TimeWindowReporterTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void reportingThreadSleepsAgainIfInterruptedAndHasNotSleptEnough()
    throws InterruptedException {

  long start = System.currentTimeMillis();
  reporter = new TimeWindowReporter("testReport", 1) {
    @Override
    protected void doReport(Map<String, Aggregator> aggregators) {
    }
  };
  reporter.start();

  new Expectations(reporter) {{
  }};

  Thread reportingThread = Deencapsulation.getField(reporter, "reportingThread");

  Thread.sleep(calculateDelay(1000, start) + 100);

  reportingThread.interrupt();

  Thread.sleep(100);

  new Verifications() {{
    reporter.doReport(withInstanceOf(Map.class));
    times = 1;
  }};
}
 
Example 20
Source File: Basic.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void threadInterrupted() throws Throwable{
    int count = 0;
    Basic test = new Basic();
    CountDownLatch latch = new CountDownLatch(3);
    Awaiter a[] = new Awaiter[12];

    for (int i = 0; i < 3; i++) {
        CountDownLatch gate = new CountDownLatch(4);
        AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
        AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count-1].interrupt();
        test.toTheStartingGate(gate);
        System.out.println("Main Thread: " + latch.toString());
        latch.countDown();
        checkCount(latch, 2-i);
    }
    for (int i = 0; i < 12; i++)
        a[i].join();

    for (int i = 0; i < 12; i++)
        checkResult(a[i],
                    (i % 4) == 3 ? InterruptedException.class : null);
}
 
Example 21
Source File: ParallelEvaluatorTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Test interruption handling when the Evaluator is in-between running SkyFunctions.
 *
 * <p>This is the point in time after a SkyFunction requested a dependency which is not yet built
 * so the builder returned null to the Evaluator, and the latter is about to schedule evaluation
 * of the missing dependency but gets interrupted before the dependency's SkyFunction could start.
 */
@Test
public void interruptedEvaluatorThread() throws Exception {
  runInterruptionTest(
      new SkyFunctionFactory() {
        @Override
        public SkyFunction create(final Semaphore threadStarted, final String[] errorMessage) {
          return new SkyFunction() {
            // No need to synchronize access to this field; we always request just one more
            // dependency, so it's only one SkyFunction running at any time.
            private int valueIdCounter = 0;

            @Override
            public SkyValue compute(SkyKey key, Environment env) throws InterruptedException {
              // Signal the waiting test thread that the Evaluator thread has really started.
              threadStarted.release();

              // Keep the evaluator busy until the test's thread gets scheduled and can
              // interrupt the Evaluator's thread.
              env.getValue(GraphTester.toSkyKey("a" + valueIdCounter++));

              // This method never throws InterruptedException, therefore it's the responsibility
              // of the Evaluator to detect the interrupt and avoid calling subsequent
              // SkyFunctions.
              return null;
            }

            @Nullable
            @Override
            public String extractTag(SkyKey skyKey) {
              return null;
            }
          };
        }
      });
}
 
Example 22
Source File: Basic.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void threadInterrupted() throws Throwable{
    int count = 0;
    Basic test = new Basic();
    CountDownLatch latch = new CountDownLatch(3);
    Awaiter a[] = new Awaiter[12];

    for (int i = 0; i < 3; i++) {
        CountDownLatch gate = new CountDownLatch(4);
        AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
        AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count-1].interrupt();
        test.toTheStartingGate(gate);
        System.out.println("Main Thread: " + latch.toString());
        latch.countDown();
        checkCount(latch, 2-i);
    }
    for (int i = 0; i < 12; i++)
        a[i].join();

    for (int i = 0; i < 12; i++)
        checkResult(a[i],
                    (i % 4) == 3 ? InterruptedException.class : null);
}
 
Example 23
Source File: Basic.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void threadInterrupted() throws Throwable{
    int count = 0;
    Basic test = new Basic();
    CountDownLatch latch = new CountDownLatch(3);
    Awaiter a[] = new Awaiter[12];

    for (int i = 0; i < 3; i++) {
        CountDownLatch gate = new CountDownLatch(4);
        AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
        AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count-1].interrupt();
        test.toTheStartingGate(gate);
        System.out.println("Main Thread: " + latch.toString());
        latch.countDown();
        checkCount(latch, 2-i);
    }
    for (int i = 0; i < 12; i++)
        a[i].join();

    for (int i = 0; i < 12; i++)
        checkResult(a[i],
                    (i % 4) == 3 ? InterruptedException.class : null);
}
 
Example 24
Source File: Basic.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void threadInterrupted() throws Throwable{
    int count = 0;
    Basic test = new Basic();
    CountDownLatch latch = new CountDownLatch(3);
    Awaiter a[] = new Awaiter[12];

    for (int i = 0; i < 3; i++) {
        CountDownLatch gate = new CountDownLatch(4);
        AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
        AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory1.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count] = factory2.getAwaiter(); a[count++].start();
        a[count-1].interrupt();
        test.toTheStartingGate(gate);
        System.out.println("Main Thread: " + latch.toString());
        latch.countDown();
        checkCount(latch, 2-i);
    }
    for (int i = 0; i < 12; i++)
        a[i].join();

    for (int i = 0; i < 12; i++)
        checkResult(a[i],
                    (i % 4) == 3 ? InterruptedException.class : null);
}
 
Example 25
Source File: WebSocketServiceTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterruptCurrentThreadIfConnectionIsInterrupted() throws Exception {
    when(webSocketClient.connectBlocking()).thenThrow(new InterruptedException());
    service.connect();

    assertTrue("Interrupted flag was not set properly",
            Thread.currentThread().isInterrupted());
}
 
Example 26
Source File: ThreadSpawnerTest.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testThreadSpawnerInterrupted() {
    new CallerInterrupter(Thread.currentThread(), TimeUnit.SECONDS.toNanos(1)).start();

    ThreadSpawner spawner = new ThreadSpawner("AnyTestCaseId");
    spawner.spawn(sleepInfiniteRunnable);
    spawner.awaitCompletion();
}
 
Example 27
Source File: StreamLogTest.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInterruptStreamWhenReadingThreadInterrupted() throws InterruptedException, ExecutionException {
    CountDownLatch executionStarted = new CountDownLatch(1);
    Future<?> threadStillInterrupted = executor.submit(() -> {
        executionStarted.countDown();
        streamLog.stream().collect(toList());
        assertThat(currentThread().isInterrupted())
            .overridingErrorMessage("Thread should keep its interruption state")
            .isTrue();
    });
    executionStarted.await();
    interruptStream();
    assertExecutionOf(threadStillInterrupted::get).hasNoAssertionFailures();
}
 
Example 28
Source File: ThreadUtilsUnitTest.java    From gridgo with MIT License 5 votes vote down vote up
@Test
public void testInterruptedSleep() {
    Thread.currentThread().interrupt();
    try {
        ThreadUtils.sleep(500);
        Assert.fail("Must throw exception");
    } catch (ThreadingException e) {
    }
    Assert.assertTrue(Thread.currentThread().isInterrupted());
    Assert.assertFalse(ThreadUtils.sleepSilence(500));
    Assert.assertTrue(Thread.currentThread().isInterrupted());
}
 
Example 29
Source File: ThreadStopperTest.java    From rabbitmq-cdi with MIT License 5 votes vote down vote up
@Test
void testThreadWillNotJoinAndJoinGetsInterrupted() throws InterruptedException {
  ThreadStopper sut = new ThreadStopper();
  StoppableThread threadToStop = new StoppableThread(() -> {
    while (threadShouldStop == false) {
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // ignore
      }
    }
  }) {
  };

  threadToStop.start();

  Thread stopperThread = new Thread(() -> {
    sut.stopThread(threadToStop);
    threadShouldStopCalled = true;
  });
  stopperThread.start();
  waitForAliveWithTimeout(50,stopperThread);
  stopperThread.interrupt();
  stopperThread.join(500);
  assertFalse(stopperThread.isAlive());
  assertTrue(threadShouldStopCalled);
  threadShouldStop = true;
  threadToStop.join(500);
  assertFalse(threadToStop.isAlive());


}
 
Example 30
Source File: ThreadProxyInterruptTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testServiceProxiesCanBeInterrupted() throws Exception
{
   AddonRegistry registry = LocalServices.getFurnace(getClass().getClassLoader())
            .getAddonRegistry();

   final MockSimpleCountService service = registry.getServices(MockSimpleCountService.class).get();
   final AtomicReference<ContainerException> exception = new AtomicReference<>();
   Thread t = new Thread(new Runnable()
   {
      @Override
      public void run()
      {
         try
         {
            while (true)
            {
               service.execute();
            }
         }
         catch (ContainerException e)
         {
            exception.set(e);
         }

         if (!Thread.currentThread().isInterrupted())
            throw new RuntimeException("Should have been interrupted at this point.");
      }
   });

   Assert.assertNull(exception.get());

   t.start();
   Thread.sleep(250);
   t.interrupt();
   Thread.sleep(250);

   Assert.assertTrue(service.execute() > 0);
   Assert.assertNotNull(exception.get());
}
 
Example 31
Source File: ThreadInfo.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private void assureInterrupted() throws VMNotInterruptedException {
    if (!interrupted) {
        throw new VMNotInterruptedException();
    }
}
 
Example 32
Source File: ThreadInfo.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void assureInterrupted() throws VMNotInterruptedException {
    if (!interrupted) {
        throw new VMNotInterruptedException();
    }
}
 
Example 33
Source File: ParallelEvaluatorTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test
public void interruptedEvaluatorThreadAfterEnqueueBeforeWaitForCompletionAndConstructResult()
    throws InterruptedException {
  // This is a regression test for a crash bug in
  // AbstractExceptionalParallelEvaluator#doMutatingEvaluation in a very specific window of time
  // between enqueueing one top-level node for evaluation and checking if another top-level node
  // is done.

  // When we have two top-level nodes, A and B,
  SkyKey keyA = GraphTester.toSkyKey("a");
  SkyKey keyB = GraphTester.toSkyKey("b");

  // And rig the graph and node entries, such that B's addReverseDepAndCheckIfDone waits for A to
  // start computing and then tries to observe an interrupt (which will happen on the calling
  // thread, aka the main Skyframe evaluation thread),
  CountDownLatch keyAStartedComputingLatch = new CountDownLatch(1);
  CountDownLatch keyBAddReverseDepAndCheckIfDoneLatch = new CountDownLatch(1);
  NodeEntry nodeEntryB = Mockito.mock(NodeEntry.class);
  AtomicBoolean keyBAddReverseDepAndCheckIfDoneInterrupted = new AtomicBoolean(false);
  Mockito.doAnswer(
          invocation -> {
            keyAStartedComputingLatch.await();
            keyBAddReverseDepAndCheckIfDoneLatch.countDown();
            try {
              Thread.sleep(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
              throw new IllegalStateException("shouldn't get here");
            } catch (InterruptedException e) {
              keyBAddReverseDepAndCheckIfDoneInterrupted.set(true);
              throw e;
            }
          })
      .when(nodeEntryB)
      .addReverseDepAndCheckIfDone(Mockito.eq(null));
  graph = new InMemoryGraphImpl() {
    @Override
    protected NodeEntry newNodeEntry(SkyKey key) {
      return key.equals(keyB) ? nodeEntryB : super.newNodeEntry(key);
    }
  };
  // And A's SkyFunction tries to observe an interrupt after it starts computing,
  AtomicBoolean keyAComputeInterrupted = new AtomicBoolean(false);
  tester.getOrCreate(keyA).setBuilder(new SkyFunction() {
    @Override
    public SkyValue compute(SkyKey skyKey, Environment env) throws InterruptedException {
      keyAStartedComputingLatch.countDown();
      try {
        Thread.sleep(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
        throw new IllegalStateException("shouldn't get here");
      } catch (InterruptedException e) {
        keyAComputeInterrupted.set(true);
        throw e;
      }
    }

    @Override
    public String extractTag(SkyKey skyKey) {
      return null;
    }
  });

  // And we have a dedicated thread that kicks off the evaluation of A and B together (in that
  // order).
  TestThread evalThread =
      new TestThread(
          () ->
              assertThrows(
                  InterruptedException.class, () -> eval(/*keepGoing=*/ true, keyA, keyB)));

  // Then when we start that thread,
  evalThread.start();
  // We (the thread running the test) are able to observe that B's addReverseDepAndCheckIfDone has
  // just been called (implying that A has started to be computed).
  assertThat(
          keyBAddReverseDepAndCheckIfDoneLatch.await(
              TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
      .isTrue();
  // Then when we interrupt the evaluation thread,
  evalThread.interrupt();
  // The evaluation thread eventually terminates.
  evalThread.joinAndAssertState(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
  // And we are able to verify both that A's SkyFunction had observed an interrupt,
  assertThat(keyAComputeInterrupted.get()).isTrue();
  // And also that B's addReverseDepAndCheckIfDoneInterrupted had observed an interrupt.
  assertThat(keyBAddReverseDepAndCheckIfDoneInterrupted.get()).isTrue();
}
 
Example 34
Source File: ThreadInterruptedCompletableFuture.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public boolean isCancelled() {
    return cancel;
}
 
Example 35
Source File: ThreadInterruptedCompletableFuture.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
public void setThread(Thread t) {
    thread = Objects.requireNonNull(t);
}
 
Example 36
Source File: GridCacheAbstractDataStructuresFailoverSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCanCloseAtomicReferenceInInterruptedThread() throws Exception {
    doCloseByInterruptedThread(grid(0).atomicReference(STRUCTURE_NAME, 10, true));
}
 
Example 37
Source File: StuckThreadDetectionValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
public long getInterruptedThreadsCount() {
    return interruptedThreadsCount.get();
}
 
Example 38
Source File: GridCacheAbstractDataStructuresFailoverSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCanCloseAtomicLongInInterruptedThread() throws Exception {
    doCloseByInterruptedThread(grid(0).atomicLong(STRUCTURE_NAME, 10, true));
}
 
Example 39
Source File: IgniteApplicationMasterSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Interrupt thread and join.
 *
 * @param thread Thread.
 */
private static void interruptedThread(Thread thread) throws InterruptedException {
    thread.interrupt();

    thread.join();
}
 
Example 40
Source File: GridCacheAbstractDataStructuresFailoverSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCanCloseSemaphoreInInterruptedThread() throws Exception {
    doCloseByInterruptedThread(grid(0).semaphore(STRUCTURE_NAME, 1, true, true));
}
 
Example 41
Source File: OSThread.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public boolean interrupted() {
    return ((int)interruptedField.getValue(addr)) != 0;
}
 
Example 42
Source File: BadQueryDetector.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
private void setQueryThreadInterrupted(Entry e, float runningSec) {
    if (queryTimeoutSeconds != 0 && runningSec >= queryTimeoutSeconds) {
        e.thread.interrupt();
        logger.error("Query running "+ runningSec + "s, Trying to cancel query:" + e.thread.getName());
    }
}
 
Example 43
Source File: ThreadUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 纯粹为了提醒下处理InterruptedException的正确方式,除非你是在写不可中断的任务.
 */
public static void handleInterruptedException() {
	Thread.currentThread().interrupt();
}
 
Example 44
Source File: TestThreadUtil.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testSleepNotInterrupted() {
  Assert.assertTrue(ThreadUtil.sleep(1));
}
 
Example 45
Source File: InstanceImpl_JAVA_THREAD.java    From jbse with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean isInterrupted() {
    return this.interrupted;
}
 
Example 46
Source File: SuspiciousThreadInterrupted.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SuspiciousThreadInterrupted(BugReporter bugReporter) {
    this.bugReporter = bugReporter;
}
 
Example 47
Source File: BadQueryDetector.java    From kylin with Apache License 2.0 4 votes vote down vote up
private void setQueryThreadInterrupted(Entry e, float runningSec) {
    if (queryTimeoutSeconds != 0 && runningSec >= queryTimeoutSeconds) {
        e.thread.interrupt();
        logger.error("Query running "+ runningSec + "s, Trying to cancel query:" + e.thread.getName());
    }
}
 
Example 48
Source File: SingleThreadEventExecutor.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isInterrupted() {
    return t.isInterrupted();
}
 
Example 49
Source File: ThreadInfo.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void assureInterrupted() throws VMNotInterruptedException {
    if (!interrupted) {
        throw new VMNotInterruptedException();
    }
}
 
Example 50
Source File: AbstractFormatter.java    From yarg with Apache License 2.0 4 votes vote down vote up
public void checkThreadInterrupted() {
    if (Thread.interrupted()) {
        throw new ReportingInterruptedException("Formatting interrupted");
    }
}
 
Example 51
Source File: ThreadInfo.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void assureInterrupted() throws VMNotInterruptedException {
    if (!interrupted) {
        throw new VMNotInterruptedException();
    }
}
 
Example 52
Source File: ContainerIntegrationLogger.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
public void interruptedWhileShuttingDownThreadPool(InterruptedException e) {
  logError(
      "034",
      "Interrupted while shutting down thread pool", e);
}
 
Example 53
Source File: Interrupter.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean hasCurrentThreadBeenInterruptedWithReason(final Object reason) {
	return this.hasThreadBeenInterruptedWithReason(Thread.currentThread(), reason);
}
 
Example 54
Source File: InterruptionTimerTask.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
public Thread getThreadToBeInterrupted() {
	return this.threadToBeInterrupted;
}
 
Example 55
Source File: AAlgorithm.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean hasThreadBeenInterruptedDuringShutdown(final Thread t) {
	return Interrupter.get().hasThreadBeenInterruptedWithReason(t, this.getId() + INTERRUPT_NAME_SUFFIX);
}
 
Example 56
Source File: Thread_isInterrupted03.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public boolean getInterrupted() {
    return interrupted;
}
 
Example 57
Source File: QueueIteratorTest.java    From junit5-docker with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldInterruptIfThreadIsInterrupted() {
    Thread.currentThread().interrupt();
    assertThat(iterator.hasNext()).isFalse();
    assertThat(Thread.interrupted()).isTrue();
}
 
Example 58
Source File: ThreadUtils.java    From fastjgame with Apache License 2.0 4 votes vote down vote up
/**
 * 检查线程中断状态。
 *
 * @throws InterruptedException 如果线程被中断,则抛出中断异常
 */
public static void checkInterrupted() throws InterruptedException {
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
}
 
Example 59
Source File: ThreadUtilsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public SleepInterruptedMultithreadedTestCase(final long expectedSleepDuration) {
  assert expectedSleepDuration > 0 : "The duration of sleep must be greater than equal to 0!";
  this.expectedSleepDuration = expectedSleepDuration;
  this.latch = new CountDownLatch(1);
}
 
Example 60
Source File: ThreadInterruptedException.java    From LogViewer with Eclipse Public License 2.0 4 votes vote down vote up
public ThreadInterruptedException() {
	super();
}