简体   繁体   中英

Java Hibernate - Making multiple threads run simultaneously

I am trying to test my SPRING MVC service performance by calling below method from multiple threads. The method uses Hibernate to fetch a record and then update it again. But it seems that all threads are executing sequentially, not in parallel.

My Service Method

@Transactional
public String performOperation() {
     USER user = dao.findUsr("name");
     user.setMarks(50);
}

My Test App

*Round 1*
thread1.start() : For Only T1, It takes time to execute : 5 Sec

*Round 2*
thread1.start()
thread2.start() : With T1 and T2: 10 Sec

*Round 3*
thread1.start()
thread2.start()
thread3.start() : With T1, T2, T3: 15 sec

*Round 4*
thread1.start()
thread2.start()
thread3.start()
thread4.start() : With T1, T2, T3, T4: 20 sec

My Configuration

jdbc.initial.pool.size=10
jdbc.min.pool.size=10
jdbc.max.pool.size=120

Not set anything for below settings : So taking default values for it

- current_session_context_class
- cache

Observation: Even for loop of 5000 per thread, max DB pool size utilized is 25. As observed in MySQL Dashboard

Problem If you see its not executing in parallel. Hibernate is locking the row I guess. Can you provide any pointers to run it simultaneously.

To start the threads at exactly the same time i would recommend giving CyclicBarrier a try.

CyclicBarrier is "A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point".

Within that Doc is an example of how it works and runs. Make reference to that within your code. For example:

final CyclicBarrier gate = new CyclicBarrier(5);

Thread thread1 = new Thread(){
public void run(){
    gate.await(); // Waits until all parties have invoked await on this barrier.
    //Your Code    
}};
Thread thread2 = new Thread(){
public void run(){
    gate.await();
    //Your Code    
}};
Thread thread3 = new Thread(){
public void run(){
    gate.await();
    //Your Code    
}};
Thread thread4 = new Thread(){
public void run(){
    gate.await();
    //Your Code    
}};

thread1.start();
thread2.start();
thread3.start();
thread4.start();
gate.await();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM