Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use service to realize multithreading in springboot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to use service to achieve multithreading in springboot, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Thread safety: since it is a thread safety problem, there is no doubt that all the hidden dangers arise in the case of multiple thread access, that is, we need to ensure that when multiple threads access, our program can also execute as we expect, let's take a look at the following code:

Integer count = 0; public void getCount () {count + +; System.out.println (count);}

The three threads I started, each looping 10 times, got the following results:

We can see that there are two 26s here, which clearly shows that this method is not thread-safe at all, and there are many reasons for this problem.

The most common one is that our A thread gets the value of count after entering the method, and when we just read this value and haven't changed the value of count, thread B also comes in, so thread An and thread B get the same count value.

So we can see that this is really not a thread-safe class because they all need to manipulate the shared variable. In fact, to give a clear definition of thread safety, or quite complex, we according to our program to summarize what is thread safety.

When multiple threads access a method, no matter how you call it, or how these threads execute alternately, we don't need to do any synchronization in the main program. The resulting behavior of this class is the correct behavior we imagine, so we can say that the class is thread-safe.

After figuring out what thread safety is, let's take a look at the two most common ways to ensure thread safety in Java. Let's take a look at the code first.

Do you think this code is thread-safe?

There is no doubt that it is absolutely thread-safe. Let's analyze why it is thread-safe.

We can see that this code does not have any state, that is to say, our code does not contain any scope, nor does it refer to fields in other classes. the scope and result of its execution only exist in the local variable of its thread and can only be accessed by the executing thread. The access of the current thread does not have any effect on another thread accessing the same method.

Two threads access this method at the same time, because there is no shared data, so the behavior between them will not affect the operations and results of other threads, so stateless objects are also thread-safe.

What about adding a status?

If we add a state to this code, add a count, to record the number of hits of this method, each time count+1 is requested, is the thread still safe at this time?

Public class ThreadDemo {int count = 0; / / number of hits of the recording method public void threadMethod (int j) {count++; int I = 1; j = j + I;}}

Obviously not, there is no problem with single thread running, but when multiple threads access this method concurrently, the problem arises. Let's analyze the count+1 operation first.

After entering this method, you first need to read the value of count, then modify the value of count, and then assign this value to count, which involves a total of three steps: "read" one > "modify" one > "assign". Since this process is step-by-step, let's first look at the following figure to see if you can see the problem:

It can be found that the value of count is not the correct result, when thread A reads the value of count, but has not yet modified it, thread B has already come in, and thread B still reads the value of count 1. Because of this, our count value has been deviated, so there are a lot of hidden dangers when such programs are put in our code.

In springboot, multithreading implements service.

First, take a look at the implementation of Dao:

Repository@Slf4jpublic class UserThreadDao {@ Autowired private JdbcTemplate jdbcTemplate; public void add (String username, int threadId, String thread_status) {String sql = "insert into userthread (username, thread_id, thread_status) values (?,?)"; jdbcTemplate.update (sql, new Object [] {username, threadId, thread_status}); log.info ("threadId: {}, jdbcTemplate: {}", threadId, jdbcTemplate) } public void update (String username, int threadId, String thread_status) {String sql = "update userthread set thread_status=? Where username=? And thread_id=? "; jdbcTemplate.update (sql, new Object [] {thread_status, username, threadId});}}

JDBCTemplate here is a thread-safe class because JdbcTemplate uses the ThreadLocal implementation to enable each thread to maintain its own independent object, which is actually a copy of the variable, which implements thread safety.

So there is no shared data in this UserThreadDao, no member variables (JdbcTemplate is thread-safe), and therefore thread-safe.

Use multithreading in service to call dao, the code is as follows:

@ Service@Slf4jpublic class UserThreadServiceImpl implements UserThreadService {@ Autowired UserThreadDao userThreadDao; @ Override @ Async ("asyncServiceExecutor") public void serviceTest (String username) {log.info ("enable execution of a Service with a Service execution time of 30s, threadId: {}", Thread.currentThread (). GetId ()); userThreadDao.add (username, Integer.parseInt (Thread.currentThread (). GetId () + ")," started ") Try {Thread.sleep (30000);} catch (InterruptedException e) {e.printStackTrace ();} log.info ("execute a Service, threadId: {}", Thread.currentThread (). GetId ()); userThreadDao.update (username, Integer.parseInt (Thread.currentThread (). GetId () + ")," ended ");}}

The serviceTest method here is a multithreaded method. The thread pool is configured as follows:

@ Configuration@EnableAsync@Slf4jpublic class ExecutorConfig {@ Autowired VisiableThreadPoolTaskExecutor visiableThreadPoolTaskExecutor; @ Bean public Executor asyncServiceExecutor () {log.info ("start asyncServiceExecutor"); ThreadPoolTaskExecutor executor = visiableThreadPoolTaskExecutor; / / configure core threads executor.setCorePoolSize (5); / / configure maximum number of threads executor.setMaxPoolSize (5); / / configure queue size executor.setQueueCapacity (5) / / configure the name prefix executor.setThreadNamePrefix ("async-service-") of the thread in the thread pool; / / rejection-policy: how to handle the new task when the pool has reached max size / / CALLER_RUNS: instead of executing the task in the new thread, the caller's thread executes the executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) / / initialize executor.initialize (); return executor;}} after reading the above, do you have any further understanding of how to use service to implement multithreading in springboot? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report