Perfectly solve the problem of lazy thread safety in singleton design mode

First, write a single example:

Write a test class:

The running result is always true, indicating that there is no problem under single thread. Here is a multi thread to access a single instance

Use multithreaded concurrent access singleton:

The running results are as follows: [com. Persagy. Thread SingleDemo@1bc4459 ,com. persagy. thread. SingleDemo@150bd4d ]

or

[com.persagy.thread. SingleDemo@12b6651 ]

It shows that there is a thread concurrent access security problem. Not all the obtained instances are the same

How to solve the thread safety problem?

Of course, the synchronous lock mechanism is used

The following improvement example:

After adding the synchronization function, the thread safety problem is solved

Running multiple times is to obtain the same instance, and there will be no two instances

[com.persagy.thread. SingleDemo@12b6651 ]

However, in the case of multi-threaded concurrent access, each thread must judge the lock every time it obtains an instance, which is inefficient. In order to improve efficiency, I added the method of double judgment to solve the problem of efficiency

The code is as follows:

In this way, the lazy thread safety problem is solved and the efficiency is improved, but there are still many hungry men in the actual development. After all, this code is more and cumbersome.

The above is the whole content of Xiaobian's perfect solution to the problem of lazy thread safety in single example design mode. I hope you can support more programming tips~

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>