有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是并发请求的repo类线程安全吗?弹簧靴

我将SpringBoot与jetty嵌入式web服务器一起用于一个web应用程序。 我想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
public class RegistrationService {

  @Autowired
  private Provider<RegistrationGroupRepository> registrationGroupRepository;

  public List<RegistrationGroup> getRegistrationGroup() {
     return registrationGroupRepository.getRegistrationGroups(1);
  }

}

如果两个或多个请求执行getRegistrationGroups(1)方法,我是否可以有竞争条件? 我想我是出于安全考虑,因为我在原型bean中使用方法注入(提供者),每次我从调用中获得新实例时


共 (1) 个答案

  1. # 1 楼答案

    首先,使Bean成为原型Bean并不能确保为每次方法调用(或每次使用,等等)创建实例

    在您的情况下,由于Provider的使用,您在这一点上没有问题
    但是,我注意到您正在直接访问getRegistrationGroups

    return registrationGroupRepository.getRegistrationGroups(1);
    

    这段代码如何编译?您应该在Provider实例上调用get()

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

    回答您的问题时,您应该很好地使用此代码。我不喜欢你在RegistrationGroupRepositoryImpl中维护某种状态,但这是你的选择

    我总是喜欢将所有字段设置为final。如果其中一个要求我删除final修饰符,则说明设计有问题