Search in sources :

Example 1 with IBlockingCondition

use of org.eclipse.scout.rt.platform.job.IBlockingCondition in project scout.rt by eclipse.

the class InvocationContextTest method testCancel.

@Test(timeout = 5000)
public void testCancel() {
    final BlockingCountDownLatch setupLatch = new BlockingCountDownLatch(1);
    final IBlockingCondition processingCondition = Jobs.newBlockingCondition(true);
    final InvocationContext<TestPort> invocationContext = new InvocationContext<>(m_port, "name");
    invocationContext.withEndpointUrl("http://localhost");
    // Make Stub.webMethod to block until cancelled.
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            setupLatch.countDown();
            processingCondition.waitForUninterruptibly(10, TimeUnit.SECONDS);
            return null;
        }
    }).when(m_port).webMethod();
    final RunMonitor runMonitor = new RunMonitor();
    // Cancel the 'webMethod' once blocking.
    Jobs.schedule(new IRunnable() {

        @Override
        public void run() throws Exception {
            setupLatch.await();
            runMonitor.cancel(true);
        }
    }, Jobs.newInput().withRunContext(RunContexts.copyCurrent()));
    // Run the test by invoking the web service with a specific RunMonitor to test cancellation.
    try {
        RunContexts.empty().withRunMonitor(runMonitor).run(new IRunnable() {

            @Override
            public void run() throws Exception {
                try {
                    // this method blocks until cancelled.
                    invocationContext.getPort().webMethod();
                    fail("WebServiceRequestCancelledException expected");
                } catch (WebServiceRequestCancelledException e) {
                    verify(m_implementorSpecifics).closeSocket(same(m_port), anyString());
                }
            }
        });
    } finally {
        processingCondition.setBlocking(false);
    }
}
Also used : BlockingCountDownLatch(org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) InvocationOnMock(org.mockito.invocation.InvocationOnMock) RunMonitor(org.eclipse.scout.rt.platform.context.RunMonitor) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) Test(org.junit.Test)

Example 2 with IBlockingCondition

use of org.eclipse.scout.rt.platform.job.IBlockingCondition in project scout.rt by eclipse.

the class JobListenerBlockedFutureTest method testEventsForBlockingJob.

@Test(timeout = 10000)
public void testEventsForBlockingJob() {
    final IBlockingCondition condition = Jobs.newBlockingCondition(true);
    IClientSession clientSession = mock(IClientSession.class);
    when(clientSession.getModelJobSemaphore()).thenReturn(Jobs.newExecutionSemaphore(1));
    JobEventCaptureListener captureListener = new JobEventCaptureListener();
    Jobs.getJobManager().addListener(ModelJobs.newEventFilterBuilder().toFilter(), captureListener);
    IFuture<Void> outerFuture = null;
    final AtomicReference<IFuture<?>> innerFuture = new AtomicReference<>();
    final JobInput modelJobInput = ModelJobs.newInput(ClientRunContexts.empty().withSession(clientSession, true));
    // start recording of events
    outerFuture = Jobs.getJobManager().schedule(new IRunnable() {

        @Override
        public void run() throws Exception {
            innerFuture.set(Jobs.getJobManager().schedule(new IRunnable() {

                @Override
                public void run() throws Exception {
                    condition.setBlocking(false);
                    // Wait until the outer future is re-acquiring the mutex.
                    // 2=outer-job + inner-job
                    JobTestUtil.waitForPermitCompetitors(modelJobInput.getExecutionSemaphore(), 2);
                }
            }, modelJobInput.copy().withName("inner").withExecutionTrigger(Jobs.newExecutionTrigger().withStartIn(2, TimeUnit.SECONDS))));
            condition.waitFor();
        }
    }, modelJobInput.copy().withName("outer"));
    Jobs.getJobManager().awaitDone(Jobs.newFutureFilterBuilder().andMatchFuture(outerFuture).toFilter(), 1, TimeUnit.MINUTES);
    Jobs.getJobManager().shutdown();
    // verify events
    int i = -1;
    List<JobEvent> capturedEvents = captureListener.getCapturedEvents();
    List<JobState> capturedFutureStates = captureListener.getCapturedFutureStates();
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.SCHEDULED, capturedEvents.get(i));
    assertEquals(JobState.SCHEDULED, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.WAITING_FOR_PERMIT, capturedEvents.get(i));
    assertEquals(JobState.WAITING_FOR_PERMIT, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.RUNNING, capturedEvents.get(i));
    assertEquals(JobState.RUNNING, capturedFutureStates.get(i));
    // inner
    i++;
    assertStateChangedEvent(innerFuture.get(), JobState.SCHEDULED, capturedEvents.get(i));
    assertEquals(JobState.SCHEDULED, capturedFutureStates.get(i));
    // inner
    i++;
    assertStateChangedEvent(innerFuture.get(), JobState.PENDING, capturedEvents.get(i));
    assertEquals(JobState.PENDING, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.WAITING_FOR_BLOCKING_CONDITION, capturedEvents.get(i));
    assertEquals(JobState.WAITING_FOR_BLOCKING_CONDITION, capturedFutureStates.get(i));
    // inner
    i++;
    assertStateChangedEvent(innerFuture.get(), JobState.WAITING_FOR_PERMIT, capturedEvents.get(i));
    assertEquals(JobState.WAITING_FOR_PERMIT, capturedFutureStates.get(i));
    // inner
    i++;
    assertStateChangedEvent(innerFuture.get(), JobState.RUNNING, capturedEvents.get(i));
    assertEquals(JobState.RUNNING, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.WAITING_FOR_PERMIT, capturedEvents.get(i));
    assertEquals(JobState.WAITING_FOR_PERMIT, capturedFutureStates.get(i));
    // inner
    i++;
    assertStateChangedEvent(innerFuture.get(), JobState.DONE, capturedEvents.get(i));
    assertEquals(JobState.DONE, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.RUNNING, capturedEvents.get(i));
    assertEquals(JobState.RUNNING, capturedFutureStates.get(i));
    // outer
    i++;
    assertStateChangedEvent(outerFuture, JobState.DONE, capturedEvents.get(i));
    assertEquals(JobState.DONE, capturedFutureStates.get(i));
    assertEquals(i + 1, capturedEvents.size());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) IFuture(org.eclipse.scout.rt.platform.job.IFuture) JobInput(org.eclipse.scout.rt.platform.job.JobInput) JobEvent(org.eclipse.scout.rt.platform.job.listener.JobEvent) IClientSession(org.eclipse.scout.rt.client.IClientSession) JobState(org.eclipse.scout.rt.platform.job.JobState) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) Test(org.junit.Test)

Example 3 with IBlockingCondition

use of org.eclipse.scout.rt.platform.job.IBlockingCondition in project scout.rt by eclipse.

the class MutualExclusionTest method testExpiredWhenReAcquiringMutex.

/**
 * Tests that a job continues execution after waiting for a blocking condition to fall.
 */
@Test
public void testExpiredWhenReAcquiringMutex() throws java.lang.InterruptedException {
    // synchronized because modified/read by different threads.
    final List<String> protocol = Collections.synchronizedList(new ArrayList<String>());
    final IBlockingCondition condition = Jobs.newBlockingCondition(true);
    final BlockingCountDownLatch latch = new BlockingCountDownLatch(1);
    final int expirationTime = 100;
    IFuture<Void> future = ModelJobs.schedule(new IRunnable() {

        @Override
        public void run() throws Exception {
            protocol.add("1: running");
            ModelJobs.schedule(new IRunnable() {

                @Override
                public void run() throws Exception {
                    protocol.add("2: running");
                    condition.setBlocking(false);
                    latch.countDownAndBlock();
                }
            }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-2"));
            condition.waitFor();
            protocol.add("3: running");
        }
    }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-1").withExceptionHandling(null, false).withExpirationTime(expirationTime, TimeUnit.MILLISECONDS));
    // Wait until job-1 can re-acquire the mutex
    assertTrue(latch.await());
    // Wait until job-1 would be expired
    SleepUtil.sleepSafe(expirationTime + 1, TimeUnit.MILLISECONDS);
    latch.unblock();
    // Expect the job to continue running.
    future.awaitDoneAndGet(5, TimeUnit.SECONDS);
    List<String> expected = new ArrayList<>();
    expected.add("1: running");
    expected.add("2: running");
    expected.add("3: running");
    assertEquals(expected, protocol);
}
Also used : BlockingCountDownLatch(org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch) ArrayList(java.util.ArrayList) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) AssertionException(org.eclipse.scout.rt.platform.util.Assertions.AssertionException) Test(org.junit.Test)

Example 4 with IBlockingCondition

use of org.eclipse.scout.rt.platform.job.IBlockingCondition in project scout.rt by eclipse.

the class MutualExclusionTest method testBlockedJobs.

/**
 * We have 5 jobs that get scheduled simultaneously. The first waits some time so that job2, job3, job4 and job5 get
 * queued. Job1 then enters a blocking condition, which allows job2 to run. But job2 gets rejected by the executor,
 * which allows job3 to run. After job3 completes, job1 is resumed and continues running. After job1 complete, job4
 * gets scheduled. Job4 in turn gets blocked, which prevents job5 from running.
 */
@Test
public void testBlockedJobs() throws java.lang.InterruptedException {
    P_JobManager jobManager = new P_JobManager();
    ExecutorService executorMock = jobManager.getExecutorMock();
    IBean<IJobManager> jobManagerBean = JobTestUtil.replaceCurrentJobManager(jobManager);
    try {
        // synchronized because modified/read by different threads.
        final List<String> protocol = Collections.synchronizedList(new ArrayList<String>());
        // Executor mock
        doAnswer(new Answer<Future>() {

            @Override
            public Future answer(InvocationOnMock invocation) throws Throwable {
                final Runnable runnable = (Runnable) invocation.getArguments()[0];
                // Reject job-2 from being scheduled
                if (runnable instanceof JobFutureTask) {
                    JobFutureTask<?> futureTask = (JobFutureTask<?>) runnable;
                    if ("job-2".equals(futureTask.getJobInput().getName())) {
                        futureTask.reject();
                        return null;
                    }
                }
                s_executor.execute(new NamedThreadRunnable(runnable));
                return null;
            }
        }).when(executorMock).execute(any(Runnable.class));
        final BlockingCountDownLatch job4RunningLatch = new BlockingCountDownLatch(1);
        final IBlockingCondition condition = Jobs.newBlockingCondition(true);
        // Job-1
        IFuture<Void> future1 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                // Wait until all 5 jobs are scheduled.
                JobTestUtil.waitForPermitCompetitors(m_clientSession.getModelJobSemaphore(), 5);
                try {
                    protocol.add("running-job-1 (a)");
                    condition.waitFor();
                    protocol.add("running-job-1 (b)");
                } catch (ProcessingException e) {
                    protocol.add("jobException");
                }
                if (ModelJobs.isModelThread()) {
                    protocol.add("running-job-1 (e) [model-thread]");
                }
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-1").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-2
        IFuture<Void> future2 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-2");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-2").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-3
        IFuture<Void> future3 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-3 (a)");
                condition.setBlocking(false);
                // Wait until job-1 tried to re-acquire the mutex.
                // 4 = job1(re-acquiring), job3(owner), job4, job5
                JobTestUtil.waitForPermitCompetitors(m_clientSession.getModelJobSemaphore(), 4);
                protocol.add("running-job-3 (b)");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-3").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-4
        IFuture<Void> future4 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-4");
                try {
                    job4RunningLatch.countDownAndBlock();
                } catch (java.lang.InterruptedException e) {
                    protocol.add("job-4 [interrupted]");
                }
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-4").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        // Job-5
        IFuture<Void> future5 = Jobs.schedule(new IRunnable() {

            @Override
            public void run() throws Exception {
                protocol.add("running-job-5");
            }
        }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withName("job-5").withExecutionHint(JOB_IDENTIFIER).withExceptionHandling(null, false));
        assertTrue(job4RunningLatch.await());
        try {
            Jobs.getJobManager().awaitDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter(), 1, TimeUnit.MILLISECONDS);
            // job-4 and job-5 are pending
            fail("timeout expected");
        } catch (TimedOutError e) {
        // NOOP
        }
        // job-4 and job-5 are pending
        assertFalse(Jobs.getJobManager().isDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter()));
        List<String> expectedProtocol = new ArrayList<>();
        expectedProtocol.add("running-job-1 (a)");
        expectedProtocol.add("running-job-3 (a)");
        expectedProtocol.add("running-job-3 (b)");
        expectedProtocol.add("running-job-1 (b)");
        expectedProtocol.add("running-job-1 (e) [model-thread]");
        expectedProtocol.add("running-job-4");
        assertEquals(expectedProtocol, protocol);
        assertFalse(future1.isCancelled());
        assertTrue(future1.isDone());
        assertTrue(future2.isCancelled());
        assertTrue(future2.isDone());
        assertFalse(future3.isCancelled());
        assertTrue(future3.isDone());
        assertFalse(future4.isCancelled());
        assertFalse(future4.isDone());
        assertFalse(future5.isCancelled());
        assertFalse(future5.isDone());
        // cancel job4
        future4.cancel(true);
        awaitDoneElseFail(JOB_IDENTIFIER);
        expectedProtocol.add("job-4 [interrupted]");
        expectedProtocol.add("running-job-5");
        assertEquals(expectedProtocol, protocol);
        assertTrue(Jobs.getJobManager().isDone(Jobs.newFutureFilterBuilder().andMatchExecutionHint(JOB_IDENTIFIER).toFilter()));
        assertTrue(future4.isCancelled());
        assertTrue(future4.isDone());
        assertFalse(future5.isCancelled());
        assertTrue(future5.isDone());
    } finally {
        JobTestUtil.unregisterAndShutdownJobManager(jobManagerBean);
    }
}
Also used : BlockingCountDownLatch(org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch) ArrayList(java.util.ArrayList) IJobManager(org.eclipse.scout.rt.platform.job.IJobManager) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) TimedOutError(org.eclipse.scout.rt.platform.util.concurrent.TimedOutError) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) JobFutureTask(org.eclipse.scout.rt.platform.job.internal.JobFutureTask) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) AssertionException(org.eclipse.scout.rt.platform.util.Assertions.AssertionException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) IFuture(org.eclipse.scout.rt.platform.job.IFuture) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) Test(org.junit.Test)

Example 5 with IBlockingCondition

use of org.eclipse.scout.rt.platform.job.IBlockingCondition in project scout.rt by eclipse.

the class MutualExclusionTest method testBlockingConditionNotBlocking.

/**
 * Tests that an invalidated Blocking condition does not block.
 */
@Test
public void testBlockingConditionNotBlocking() {
    final IBlockingCondition condition = Jobs.newBlockingCondition(false);
    ModelJobs.schedule(new IRunnable() {

        @Override
        public void run() throws Exception {
            condition.waitFor();
        }
    }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withExecutionHint(JOB_IDENTIFIER));
    ModelJobs.schedule(new IRunnable() {

        @Override
        public void run() throws Exception {
            condition.waitFor();
        }
    }, ModelJobs.newInput(ClientRunContexts.copyCurrent()).withExecutionHint(JOB_IDENTIFIER));
    awaitDoneElseFail(JOB_IDENTIFIER);
}
Also used : IRunnable(org.eclipse.scout.rt.platform.util.concurrent.IRunnable) IBlockingCondition(org.eclipse.scout.rt.platform.job.IBlockingCondition) ProcessingException(org.eclipse.scout.rt.platform.exception.ProcessingException) AssertionException(org.eclipse.scout.rt.platform.util.Assertions.AssertionException) Test(org.junit.Test)

Aggregations

IBlockingCondition (org.eclipse.scout.rt.platform.job.IBlockingCondition)32 Test (org.junit.Test)24 IRunnable (org.eclipse.scout.rt.platform.util.concurrent.IRunnable)20 AssertionException (org.eclipse.scout.rt.platform.util.Assertions.AssertionException)12 ProcessingException (org.eclipse.scout.rt.platform.exception.ProcessingException)10 BlockingCountDownLatch (org.eclipse.scout.rt.testing.platform.util.BlockingCountDownLatch)9 ArrayList (java.util.ArrayList)8 IExecutionSemaphore (org.eclipse.scout.rt.platform.job.IExecutionSemaphore)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 PlatformException (org.eclipse.scout.rt.platform.exception.PlatformException)4 IFuture (org.eclipse.scout.rt.platform.job.IFuture)4 TimedOutError (org.eclipse.scout.rt.platform.util.concurrent.TimedOutError)4 Times (org.eclipse.scout.rt.testing.platform.runner.Times)4 ClientNotificationDispatcher (org.eclipse.scout.rt.client.clientnotification.ClientNotificationDispatcher)3 ThreadInterruptedError (org.eclipse.scout.rt.platform.util.concurrent.ThreadInterruptedError)3 PropertyChangeEvent (java.beans.PropertyChangeEvent)2 PropertyChangeListener (java.beans.PropertyChangeListener)2 Serializable (java.io.Serializable)2 List (java.util.List)2 ClientRunContext (org.eclipse.scout.rt.client.context.ClientRunContext)2