示例#1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCancelRecurringJob() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldCancelRecurringJob()
        {
            // Given
            long period = 2;

            _life.start();
            JobHandle jobHandle = _scheduler.scheduleRecurring(Group.INDEX_POPULATION, _countInvocationsJob, period, MILLISECONDS);

            AwaitFirstInvocation();

            // When
            jobHandle.Cancel(false);

            try
            {
                jobHandle.WaitTermination();
                fail("Task should be terminated");
            }
            catch (CancellationException)
            {
                // task should be canceled
            }

            // Then
            int recorded = _invocations.get();

            sleep(period * 100);
            // we can have task that is already running during cancellation so lets count it as well
            assertThat(_invocations.get(), both(greaterThanOrEqualTo(recorded)).and(lessThanOrEqualTo(recorded + 1)));
        }
示例#2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotifyCancelListeners()
        public virtual void ShouldNotifyCancelListeners()
        {
            // GIVEN
            CentralJobScheduler centralJobScheduler = new CentralJobScheduler();

            centralJobScheduler.Init();

            // WHEN
            AtomicBoolean halted = new AtomicBoolean();
            ThreadStart   job    = () =>
            {
                while (!halted.get())
                {
                    LockSupport.parkNanos(MILLISECONDS.toNanos(10));
                }
            };
            JobHandle handle = centralJobScheduler.Schedule(Group.INDEX_POPULATION, job);

            handle.RegisterCancelListener(mayBeInterrupted => halted.set(true));
            handle.Cancel(false);

            // THEN
            assertTrue(halted.get());
            centralJobScheduler.Shutdown();
        }
示例#3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void recurringTasksMustStopWhenCancelled() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RecurringTasksMustStopWhenCancelled()
        {
            IList <bool> cancelListener = new List <bool>();
            ThreadStart  recurring      = () =>
            {
                _counter.incrementAndGet();
                _semaphore.release();
            };
            JobHandle handle = _scheduler.submit(Group.STORAGE_MAINTENANCE, recurring, 100, 100);

            handle.RegisterCancelListener(cancelListener.add);
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            AssertSemaphoreAcquire();
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            AssertSemaphoreAcquire();
            handle.Cancel(true);
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            _pools.getThreadPool(Group.STORAGE_MAINTENANCE).shutDown();
            assertThat(_counter.get(), @is(2));
            assertThat(cancelListener, contains(true));
        }
示例#4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void overdueRecurringTasksMustStartAsSoonAsPossible()
        public virtual void OverdueRecurringTasksMustStartAsSoonAsPossible()
        {
            ThreadStart recurring = () =>
            {
                _counter.incrementAndGet();
                _semaphore.acquireUninterruptibly();
            };
            JobHandle handle = _scheduler.submit(Group.STORAGE_MAINTENANCE, recurring, 100, 100);

            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            while (_counter.get() < 1)
            {
                // Spin.
                Thread.yield();
            }
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            _clock.forward(100, TimeUnit.NANOSECONDS);
            _semaphore.release();
            _scheduler.tick();
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);

            while (_counter.get() < 2 && System.nanoTime() < deadline)
            {
                _scheduler.tick();
                Thread.yield();
            }
            assertThat(_counter.get(), @is(2));
            _semaphore.release(int.MaxValue);
            handle.Cancel(false);
        }
示例#5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void recurringJobWithExceptionShouldKeepRunning() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RecurringJobWithExceptionShouldKeepRunning()
        {
            // given
            RobustJobSchedulerWrapper robustWrapper = new RobustJobSchedulerWrapper(_actualScheduler, _log);

            AtomicInteger count = new AtomicInteger();

            System.InvalidOperationException e = new System.InvalidOperationException();

            // when
            int       nRuns     = 100;
            JobHandle jobHandle = robustWrapper.ScheduleRecurring(Group.HZ_TOPOLOGY_REFRESH, 1, () =>
            {
                if (count.get() < nRuns)
                {
                    count.incrementAndGet();
                    throw e;
                }
            });

            // then
            assertEventually("run count", count.get, Matchers.equalTo(nRuns), _defaultTimeoutMs, MILLISECONDS);
            jobHandle.Cancel(true);
            verify(_log, timeout(_defaultTimeoutMs).times(nRuns)).warn("Uncaught exception", e);
        }
示例#6
0
        public override void Cancel(bool mayInterruptIfRunning)
        {
            set(FAILED);
            JobHandle handle = _latestHandle;

            if (handle != null)
            {
                handle.Cancel(mayInterruptIfRunning);
            }
            foreach (CancelListener cancelListener in _cancelListeners)
            {
                cancelListener.Cancelled(mayInterruptIfRunning);
            }
            // Release the handle to allow waitTermination() to observe the cancellation.
            _handleRelease.release();
        }
示例#7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void recurringJobWithErrorShouldStop() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RecurringJobWithErrorShouldStop()
        {
            // given
            RobustJobSchedulerWrapper robustWrapper = new RobustJobSchedulerWrapper(_actualScheduler, _log);

            AtomicInteger count = new AtomicInteger();
            Exception     e     = new Exception();

            // when
            JobHandle jobHandle = robustWrapper.ScheduleRecurring(Group.HZ_TOPOLOGY_REFRESH, 1, () =>
            {
                count.incrementAndGet();
                throw e;
            });

            // when
            Thread.Sleep(50);                 // should not keep increasing during this time

            // then
            assertEventually("run count", count.get, Matchers.equalTo(1), _defaultTimeoutMs, MILLISECONDS);
            jobHandle.Cancel(true);
            verify(_log, timeout(_defaultTimeoutMs).times(1)).error("Uncaught error rethrown", e);
        }
示例#8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void delayedTasksMustNotRunIfCancelledFirst() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DelayedTasksMustNotRunIfCancelledFirst()
        {
            IList <bool> cancelListener = new List <bool>();
            JobHandle    handle         = _scheduler.submit(Group.STORAGE_MAINTENANCE, _counter.incrementAndGet, 100, 0);

            handle.RegisterCancelListener(cancelListener.add);
            _clock.forward(90, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            handle.Cancel(false);
            _clock.forward(10, TimeUnit.NANOSECONDS);
            _scheduler.tick();
            _pools.getThreadPool(Group.STORAGE_MAINTENANCE).shutDown();
            assertThat(_counter.get(), @is(0));
            assertThat(cancelListener, contains(false));
            try
            {
                handle.WaitTermination();
                fail("waitTermination should have thrown a CancellationException.");
            }
            catch (CancellationException)
            {
                // Good stuff.
            }
        }
示例#9
0
        private HazelcastInstance CreateHazelcastInstance()
        {
            JoinConfig joinConfig = new JoinConfig();

            joinConfig.MulticastConfig.Enabled = false;
            TcpIpConfig tcpIpConfig = joinConfig.TcpIpConfig;

            tcpIpConfig.Enabled = true;

//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            ICollection <string> initialMembers = _remoteMembersResolver.resolve(SocketAddress::toString);

            initialMembers.forEach(tcpIpConfig.addMember);

            ListenSocketAddress hazelcastAddress = Config.get(discovery_listen_address);
            NetworkConfig       networkConfig    = new NetworkConfig();

            if (!hazelcastAddress.Wildcard)
            {
                InterfacesConfig interfaces = new InterfacesConfig();
                interfaces.addInterface(hazelcastAddress.Hostname);
                interfaces.Enabled       = true;
                networkConfig.Interfaces = interfaces;
            }

            networkConfig.Port = hazelcastAddress.Port;
            networkConfig.Join = joinConfig;
            networkConfig.PortAutoIncrement = false;

            // We'll use election_timeout as a base value to calculate HZ timeouts. We multiply by 1.5
            long?electionTimeoutMillis      = Config.get(CausalClusteringSettings.leader_election_timeout).toMillis();
            long?baseHazelcastTimeoutMillis = (3 * electionTimeoutMillis) / 2;

            /*
             * Some HZ settings require the value in seconds. Adding the divider and subtracting 1 is equivalent to the
             * ceiling function for integers ( Math.ceil() returns double ). Anything < 0 will return 0, any
             * multiple of 1000 returns the result of the division by 1000, any non multiple of 1000 returns the result
             * of the division + 1. In other words, values in millis are rounded up.
             */
            long baseHazelcastTimeoutSeconds = (baseHazelcastTimeoutMillis + 1000 - 1) / 1000;

            com.hazelcast.config.Config c = new com.hazelcast.config.Config();
            c.setProperty(OPERATION_CALL_TIMEOUT_MILLIS.Name, baseHazelcastTimeoutMillis.ToString());
            c.setProperty(MERGE_NEXT_RUN_DELAY_SECONDS.Name, baseHazelcastTimeoutSeconds.ToString());
            c.setProperty(MERGE_FIRST_RUN_DELAY_SECONDS.Name, baseHazelcastTimeoutSeconds.ToString());
            c.setProperty(INITIAL_MIN_CLUSTER_SIZE.Name, HAZELCAST_MIN_CLUSTER.ToString());

            if (Config.get(disable_middleware_logging))
            {
                c.setProperty(LOGGING_TYPE.Name, "none");
            }

            if (hazelcastAddress.IPv6)
            {
                c.setProperty(PREFER_IPv4_STACK.Name, "false");
            }

            c.NetworkConfig = networkConfig;

            MemberAttributeConfig memberAttributeConfig = HazelcastClusterTopology.BuildMemberAttributesForCore(MyselfConflict, Config);

            c.MemberAttributeConfig = memberAttributeConfig;
            LogConnectionInfo(initialMembers);
            c.addListenerConfig(new ListenerConfig(new OurMembershipListener(this)));

            JobHandle logJob = _scheduler.schedule(Group.HZ_TOPOLOGY_HEALTH, _hazelcastIsHealthyTimeoutMs, () => Log.warn("The server has not been able to connect in a timely fashion to the " + "cluster. Please consult the logs for more details. Rebooting the server may " + "solve the problem."));

            try
            {
                _hazelcastInstance = Hazelcast.newHazelcastInstance(c);
                logJob.Cancel(true);
            }
            catch (HazelcastException e)
            {
                string errorMessage = string.Format("Hazelcast was unable to start with setting: {0} = {1}", discovery_listen_address.name(), Config.get(discovery_listen_address));
                UserLog.error(errorMessage);
                Log.error(errorMessage, e);
                throw new Exception(e);
            }

            IList <string> groups = Config.get(CausalClusteringSettings.server_groups);

            refreshGroups(_hazelcastInstance, MyselfConflict.Uuid.ToString(), groups);

            return(_hazelcastInstance);
        }