Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zhugw/0fcae92d6b08bcf237cad9617471e4e4 to your computer and use it in GitHub Desktop.
Save zhugw/0fcae92d6b08bcf237cad9617471e4e4 to your computer and use it in GitHub Desktop.
ConcurrentlyExecuteDbQuery
package com.tn.api.service;
import com.tn.api.dao.TestDao;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertTrue;
/**
* Created by zhuguowei on 4/4/17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-api.xml","classpath:spring/spring-dao.xml"})
@Slf4j
public class ConcurrentlyDbQureyTest {
@Autowired
private TestDao dao;
@Test
public void test_sleep1(){
long start = System.currentTimeMillis();
dao.sleep1();
long end = System.currentTimeMillis();
log.info("took time: {}", end - start);
assertTrue((end - start) > 1000L);
}
@Test
public void test_concurrently_invoke_sleep1() throws InterruptedException {
long start = System.currentTimeMillis();
int nThreads = 10;
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
CountDownLatch countDownLatch = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
executorService.submit(()->{
dao.sleep1();
countDownLatch.countDown();
});
}
countDownLatch.await();
long end = System.currentTimeMillis();
log.info("took time: {}", end - start);
assertTrue((end - start) < 2000L);
}
}
@Select("select sleep(1)")
long sleep1();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment