Java Code Examples for org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor#execute()

The following examples show how to use org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor#execute() . 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. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecutorBeanDefinitionParserTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void defaultExecutor() throws Exception {
	ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class);
	assertEquals(1, getCorePoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor));
	assertEquals(60, getKeepAliveSeconds(executor));
	assertEquals(false, getAllowCoreThreadTimeOut(executor));

	FutureTask<String> task = new FutureTask<>(new Callable<String>() {
		@Override
		public String call() throws Exception {
			return "foo";
		}
	});
	executor.execute(task);
	assertEquals("foo", task.get());
}
 
Example 2
Source File: ExecutorBeanDefinitionParserTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void defaultExecutor() throws Exception {
	ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class);
	assertEquals(1, getCorePoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor));
	assertEquals(60, getKeepAliveSeconds(executor));
	assertEquals(false, getAllowCoreThreadTimeOut(executor));

	FutureTask<String> task = new FutureTask<>(new Callable<String>() {
		@Override
		public String call() throws Exception {
			return "foo";
		}
	});
	executor.execute(task);
	assertEquals("foo", task.get());
}
 
Example 3
Source File: ExecutorBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultExecutor() throws Exception {
	ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class);
	assertEquals(1, getCorePoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor));
	assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor));
	assertEquals(60, getKeepAliveSeconds(executor));
	assertEquals(false, getAllowCoreThreadTimeOut(executor));

	FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
		@Override
		public String call() throws Exception {
			return "foo";
		}
	});
	executor.execute(task);
	assertEquals("foo", task.get());
}
 
Example 4
Source File: RabbitOperations.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
public void startConsumer(String queue,
                          boolean autoAck,
                          Function<Message, Boolean> onMessage,
                          ThreadPoolTaskExecutor executor) throws IOException {
    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag,
                                   Envelope envelope,
                                   AMQP.BasicProperties properties,
                                   byte[] body) throws IOException {

            if (executor != null) {
                executor.execute(() -> {
                    log.debug("======= {} ======", new String(body));
                    onMessage.apply(new Message(properties.getHeaders(), getChannel(), body, envelope));
                });
                return;
            }

            onMessage.apply(new Message(properties.getHeaders(), getChannel(), body, envelope));
        }
    };

    String tag = getChannel().basicConsume(queue, autoAck, consumer);
    consumers.put(queue, tag);
    log.info("[Consumer STARTED] queue {} with tag {}", queue, tag);
}
 
Example 5
Source File: ThreadPoolTaskExecutorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
void startThreads(ThreadPoolTaskExecutor taskExecutor, CountDownLatch countDownLatch, int numThreads) {
    for (int i = 0; i < numThreads; i++) {
        taskExecutor.execute(() -> {
            try {
                Thread.sleep(100L * ThreadLocalRandom.current().nextLong(1, 10));
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }
}
 
Example 6
Source File: UserController.java    From feiqu-opensource with Apache License 2.0 4 votes vote down vote up
@GetMapping("reSendEmail")
@ResponseBody
public Object reSendEmail(HttpServletRequest request, HttpServletResponse response) {
    BaseResult result = new BaseResult();
    FqUserCache currUser = webUtil.currentUser(request,response);
    if(!Validator.isEmail(currUser.getUsername())){
        result.setResult(ResultEnum.EMAIL_NOT_CORRECT);
        return result;
    }
    UserActivateExample example = new UserActivateExample();
    example.createCriteria().andUserIdEqualTo(currUser.getId());
    UserActivate userActivate = userActivateService.selectFirstByExample(example);
    String htmlContent = "";
    if(userActivate == null){
        String token = RandomUtil.randomUUID();
        userActivate = new UserActivate(currUser.getId(),token,new Date());
        userActivateService.insert(userActivate);
        htmlContent = getEmailHtml(currUser.getNickname(),token);
    }else {
        htmlContent = getEmailHtml(currUser.getNickname(),userActivate.getToken());
    }

    final MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GBK");
        helper.setFrom(mailSender.getUsername());
        //邮件主题
        helper.setSubject("邮箱绑定");
        //邮件接收者的邮箱地址
        helper.setTo(currUser.getUsername());
        helper.setText(htmlContent, true);

    } catch (MessagingException e) {
        logger.error("用户{}发送邮件失败 ",currUser.getUsername());
        result.setResult(ResultEnum.FAIL);
    }

    ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) SpringContextUtil.getBean("threadPoolTaskExecutor");
    executor.execute(new Runnable() {
        public void run() {
            mailSender.send(mimeMessage);
        }
    });
    return result;
}
 
Example 7
Source File: AgentServiceTest.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
@Test
    public void should_find_lock_and_release_agents() throws InterruptedException {
        // init:
        agentService.create("hello.test.1", ImmutableSet.of("local", "android"), Optional.empty());
        agentService.create("hello.test.2", null, Optional.empty());
        Agent idle = agentService.create("hello.test.3", ImmutableSet.of("alicloud", "android"), Optional.empty());
        ThreadPoolTaskExecutor executor = ThreadHelper.createTaskExecutor(5, 5, 0, "mock-tryLock-");

        // when:
        Agent agent = agentService.find(Status.CREATED, ImmutableSet.of("android")).get(0);
        Assert.assertNotNull(agent);

        // when: make agent online
        mockAgentOnline(agentService.getPath(idle));

        // then: find available agent
        Agent available = agentService.find(Status.IDLE, null).get(0);
        Assert.assertEquals(idle, available);

        // when: try lock agent in multiple thread
        AtomicInteger numOfLocked = new AtomicInteger(0);
        AtomicInteger numOfFailure = new AtomicInteger(0);
        CountDownLatch counterForLock = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                Boolean isLocked = agentService.tryLock(available);
                if (isLocked) {
                    numOfLocked.incrementAndGet();
                }
                else {
                    numOfFailure.incrementAndGet();
                }

                counterForLock.countDown();
            });
        }

        // then: verify num of locked
        counterForLock.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(1, numOfLocked.get());
        Assert.assertEquals(4, numOfFailure.get());
        Assert.assertEquals(Status.BUSY, getAgentStatus(agentService.getPath(available)));

        // when: release agent and mock event from agent
        agentService.tryRelease(available);
//        mockReleaseAgent(agentService.getPath(available));

        // then: the status should be idle
        Status statusFromZk = getAgentStatus(agentService.getPath(available));
        Assert.assertEquals(Status.IDLE, statusFromZk);

        ThreadHelper.sleep(2000);
        Status statusFromDB = agentService.get(available.getId()).getStatus();
        Assert.assertEquals(Status.IDLE, statusFromDB);
    }
 
Example 8
Source File: PerformanceDTTest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Stress tests that create tx and sign them
 *
 * @param totalSignedTxCount
 * @param threadC
 * @throws InterruptedException
 */
public void userTransferSignTxPerfTest(BigInteger totalSignedTxCount, int threadC)
        throws InterruptedException {

    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();

    threadPool.setCorePoolSize(threadC > 0 ? threadC : 10);
    threadPool.setMaxPoolSize(threadC > 0 ? threadC : 10);
    threadPool.setQueueCapacity(threadC > 0 ? threadC : 10);
    threadPool.initialize();

    Credentials credentials = GenCredential.create();

    TransferSignTransactionManager extendedRawTransactionManager =
            new TransferSignTransactionManager(
                    null, credentials, BigInteger.ONE, BigInteger.ONE);

    dagTransfer =
            DagTransfer.load(
                    dagTransferAddr,
                    null,
                    extendedRawTransactionManager,
                    new StaticGasProvider(
                            new BigInteger("30000000"), new BigInteger("30000000")));

    AtomicLong signed = new AtomicLong(0);

    long startTime = System.currentTimeMillis();
    System.out.println(" => " + dateFormat.format(new Date()));

    for (int i = 0; i < threadC; i++) {
        threadPool.execute(
                new Runnable() {
                    @Override
                    public void run() {
                        while (true) {

                            long index = signed.incrementAndGet();
                            if (index > totalSignedTxCount.intValue()) {
                                break;
                            }
                            DagTransferUser from = dagUserMgr.getFrom((int) index);
                            DagTransferUser to = dagUserMgr.getTo((int) index);

                            Random random = new Random();
                            int r = random.nextInt(100) + 1;
                            BigInteger amount = BigInteger.valueOf(r);

                            try {
                                String signedTransaction =
                                        dagTransfer.userTransferSeq(
                                                from.getUser(), to.getUser(), amount);

                                if (index % (totalSignedTxCount.longValue() / 10) == 0) {
                                    System.out.println(
                                            "Signed transaction: "
                                                    + String.valueOf(
                                                            index
                                                                    * 100
                                                                    / totalSignedTxCount
                                                                            .longValue())
                                                    + "%");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                System.exit(-1);
                            }
                        }
                    }
                });
    }

    while (signed.get() < totalSignedTxCount.intValue()) {
        Thread.sleep(10);
    }

    long endTime = System.currentTimeMillis();
    double elapsed = (endTime - startTime) / 1000.0;

    System.out.println(" => " + dateFormat.format(new Date()));

    System.out.print(
            " sign transactions finished, elapse time: "
                    + elapsed
                    + ", tx count = "
                    + totalSignedTxCount
                    + " ,sps = "
                    + (totalSignedTxCount.intValue() / elapsed));
    System.exit(0);
}
 
Example 9
Source File: AgentServiceTest.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
@Test
    public void should_find_lock_and_release_agents() throws InterruptedException {
        // init:
        agentService.create("hello.test.1", ImmutableSet.of("local", "android"), Optional.empty());
        agentService.create("hello.test.2", null, Optional.empty());
        Agent idle = agentService.create("hello.test.3", ImmutableSet.of("alicloud", "android"), Optional.empty());
        ThreadPoolTaskExecutor executor = ThreadHelper.createTaskExecutor(5, 5, 0, "mock-tryLock-");

        // when:
        Agent agent = agentService.find(Status.CREATED, ImmutableSet.of("android")).get(0);
        Assert.assertNotNull(agent);

        // when: make agent online
        mockAgentOnline(agentService.getPath(idle));

        // then: find available agent
        Agent available = agentService.find(Status.IDLE, null).get(0);
        Assert.assertEquals(idle, available);

        // when: try lock agent in multiple thread
        AtomicInteger numOfLocked = new AtomicInteger(0);
        AtomicInteger numOfFailure = new AtomicInteger(0);
        CountDownLatch counterForLock = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                Optional<Agent> optional = agentService.tryLock("dummyJobId", available.getId());
                if (optional.isPresent()) {
                    numOfLocked.incrementAndGet();
                }
                else {
                    numOfFailure.incrementAndGet();
                }

                counterForLock.countDown();
            });
        }

        // then: verify num of locked
        counterForLock.await(10, TimeUnit.SECONDS);
        Assert.assertEquals(1, numOfLocked.get());
        Assert.assertEquals(4, numOfFailure.get());
        Assert.assertEquals(Status.BUSY, getAgentStatus(agentService.getPath(available)));

        // when: release agent and mock event from agent
        agentService.tryRelease(available.getId());
//        mockReleaseAgent(agentService.getPath(available));

        // then: the status should be idle
        Status statusFromZk = getAgentStatus(agentService.getPath(available));
        Assert.assertEquals(Status.IDLE, statusFromZk);

        ThreadHelper.sleep(2000);
        Status statusFromDB = agentService.get(available.getId()).getStatus();
        Assert.assertEquals(Status.IDLE, statusFromDB);
    }
 
Example 10
Source File: MdcThreadPoolTaskExecutorTest.java    From spring-boot-starter-batch-web with Apache License 2.0 4 votes vote down vote up
@Test
public void run() throws Exception {
	// Given
	ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
	taskExecutor.afterPropertiesSet();

	final ThreadPoolTaskExecutor innerTaskExecutor = new MdcThreadPoolTaskExecutor();
	innerTaskExecutor.afterPropertiesSet();

	// Simple task which returns always the key from the MDC
	final FutureTask<String> innerTask = new FutureTask<String>(new Callable<String>() {

		@Override
		public String call() throws Exception {
			return MDC.get("key");
		}
	});

	taskExecutor.execute(new Runnable() {

		@Override
		public void run() {
			MDC.put("key", "1");
			innerTaskExecutor.execute(innerTask);
		}
	});
	// Wait for Thread and verify that it contains the right value of key
	assertThat(innerTask.get(), is(equalTo("1")));

	// Wait 1sec. for outer thread
	Thread.sleep(1000);

	// Simple task which returns always the key from the MDC
	final FutureTask<String> innerTask2 = new FutureTask<String>(new Callable<String>() {

		@Override
		public String call() throws Exception {
			return MDC.get("key");
		}
	});

	taskExecutor.execute(new Runnable() {

		@Override
		public void run() {
			MDC.put("key", "2");
			innerTaskExecutor.execute(innerTask2);
		}
	});

	// Wait for Thread and verify that it contains the right value of key
	assertThat(innerTask2.get(), is(equalTo("2")));

}