亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

并發請求的 repo 類線程安全嗎?- 彈簧靴

并發請求的 repo 類線程安全嗎?- 彈簧靴

弒天下 2022-06-23 17:29:12
我正在為一個 Web 應用程序使用帶有 jetty 嵌入式 Web 服務器的 Spring Boot。我想 100% 確定 repo 類是線程安全的?;刭忣怈Repository@Scope("prototype")public class RegistrationGroupRepositoryImpl implements RegistrationGroupRepository {  private RegistrationGroup rg = null;  Integer sLastregistrationTypeID = 0;  private UserAccountRegistration uar = null;  private List<RegistrationGroup> registrationGroup = new ArrayList<>();  private NamedParameterJdbcTemplate jdbcTemplate;  @Autowired  public RegistrationGroupRepositoryImpl(DataSource dataSource) {     this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);  }  public List<RegistrationGroup> getRegistrationGroups(Integer regId) {    // Some logic here which is stored in stored in the instance variables and registrationGroup is returned from the method   return this.registrationGroup;  }以及從 repo 調用 getRegistrationGroups 方法的 Service 類。@Servicepublic class RegistrationService {  @Autowired  private Provider<RegistrationGroupRepository> registrationGroupRepository;  public List<RegistrationGroup> getRegistrationGroup() {     return registrationGroupRepository.getRegistrationGroups(1);  }}如果兩個或多個請求執行 getRegistrationGroups(1) 方法,我會出現競爭情況嗎?我想我是在安全方面,因為我正在使用帶有原型 bean 的方法注入(提供程序),并且每次我從調用中獲取新實例時?
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

首先,使您的 Bean 成為原型Bean 并不能確保為每個方法調用(或每次使用,等等)創建一個實例。

在您的情況下,由于使用情況,您在這一點上沒問題Provider
但是,我注意到您正在getRegistrationGroups直接訪問。

return registrationGroupRepository.getRegistrationGroups(1);

這段代碼如何編譯?您應該調用實例get()。Provider

return registrationGroupRepository.get().getRegistrationGroups(1);

回答您的問題,您應該很好地使用此代碼。我不喜歡你在內部保持某種狀態的事實RegistrationGroupRepositoryImpl,但這是你的選擇。

我總是喜歡將我的所有領域都作為final. 如果其中一個要求我刪除final修飾符,則說明設計有問題。


查看完整回答
反對 回復 2022-06-23
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號