Spring解決創建單例bean,而存在線程不安全問題,的解決方案


一、線程安全問題都是由全局變量、靜態變量和類的成員變量引起的。若每個線程中對全局變量、靜態變量和類的成員變量只有讀操作,而無寫
操作,一般來說,這個全局變量是線程安全的,反之線程存在問題

二、因為Spring中的Bean默認是單例的,所以在定義成員變量時也有可能會發生線程安全問題。

三、解決方案

        A、在對應的類名上加上該注解@Scope("prototype")從而將默認的@Scope("")改為多例,表示每次調用該接口都會生成一個新的Bean。
        
        B、ThreadLocal解決問題
                 ThreadLocal作用:為每個使用該變量【全局變量、靜態變量和類的成員變量】的線程分配一個獨立的變量,從而互不影響
                 ThreadLocal底層原理:是一個Map,key:Thread.currentThread() value:變量
        
               @RestController
               //@Scope("prototype")
               public class BeanController {
                     private static ThreadLocal<Integer> content = new ThreadLocal<Integer>() {
                         @Override
                         protected Integer initialValue() {
                                return (int)(Math.random()*10+100);
                         }
              };
              private static ThreadLocal<String> test = new ThreadLocal<String>() {
                         @Override
                         protected String initialValue() {
                                return "單例模式是不安全的"+(int)(Math.random()*10+100);
                         }
               };

               @RequestMapping("testBean")
               public Object getSercurity(){
	                  System.out.println(content.get());
	                  System.out.println(test.get());		System.out.println();
	                  return test.get();
              }
               }

              C、三種解決方案:盡量不要使用成員變量 
              
              D、四種解決方案:
                    前提:該程序是web應用,可以使用Spring Bean的作用域中的request,就是說在類前面加上@Scope("request"),表明每次請求都會生成一個新的Bean對象。作用於@Scope("prototype")類似。
        
              鏈接地址:https://blog.csdn.net/weixin_42324471/article/details/90603651


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM