Under high concurrency, dbutils.QueryRunner in the spring framework can be stored as a singleton

1: Understand the difference between singleton and multiple instances

Singleton: The object created each time is the same, and only one copy of the New object is stored in the heap;

Many cases: the objects created each time are different, the New object is stored in the heap N copies;

 

2: Understand the storage of parent class member variables in subclass objects

The subclass object first opens up a space in the heap, and stores a copy of the member variable in the inherited parent class in the space;

The parent class member variables stored in multiple subclass objects are not the same;

 

3: Understand the QueryRunner class

 The QueryRunner class has no member variables, so objects can be created in a singleton way, which is multi-thread safe;

 

4: countDownLatch high concurrency verification

 @Test
    public void testfindAllAccount() throws InterruptedException {

        // 控制线程同步
        final CountDownLatch countDownLatch = new CountDownLatch(1000);
        final CountDownLatch countDownLatch2 = new CountDownLatch(1000);

        // 当前时间
        final Long startTime = System.currentTimeMillis();

        for(int i=0;i<1000;i++)
        {
           new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        // 阻塞等待其它线程
                        countDownLatch.await();

                        System.out.println("当前线程为"+Thread.currentThread().getName());
                        List<Account> allAccount = as.findAllAccount();

                        System.out.println(Thread.currentThread().getName()+"获取的数据长度:"+allAccount.size());
                        long endTime = System.currentTimeMillis();
                        System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms.");

                        countDownLatch2.countDown();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

           countDownLatch.countDown();
        }

        countDownLatch2.await();

    }

result:

countDownLatch knowledge

Additional knowledge points: Singleton bean dependency injection multi-case bean is invalid in spring framework

Guess you like

Origin blog.csdn.net/Growing_hacker/article/details/109009781