The question is the following. Suppose I have a class A that works with multiple threads. In the class A constructor, I create an instance of another class B.
Instances of class B for each thread will be individual?
I will give for example the following code:
public class EmployeeService implements Service<Employee> { private Dao<Employee> employeeDao; private Dao<Phone> phoneDao; private static ThreadLocal<Connection> connectionTL = new ThreadLocal<>(); private void initTransaction() { try { connectionTL.set(pool.getConnection());//коннекшн берется из пула соединений } catch (PoolException e) { throw new ServiceException(e); } } @Override public void editEmployee(Employee obj) { initTransaction(); Connection connection = connectionTL.get(); //по логике в этом месте data race не должно быть ибо для каждого потока будет свой экземпляр дао. //и коннекшины не должны перетерться employeeDao.setConnection(connection); //проставляю connections для DAO слоя phoneDao.setConnection(connection); ...Логика вызова методов класса B } public class AbstractDao<T> implements DAO<T>{ private Connection connection; @Override public void setConnection(Connection connection) { this.connection = connection; } @Override public T edit(T obj) throws DaoException { try (PreparedStatement preparedStatement = connection.prepareStatement(getSqlStringEdit())) { ... логика запросов к БД } catch (SQLException e) { throw new DaoException(e); } return newObj; } }
editEmployeeconnection will be unique for each thread. ButemployeeDaoandphoneDaoare the same in all instances of theEmployeeServiceclass. IfeditEmployeeis launched from different streams, then one connection will be recorded inemployeeDao, then another (second stream). In this case, the first thread will write there without suspecting anything. - Mark ShevchenkoEmployeeServiceconstructor instances of theEmployeeDaoclass,public EmployeeService() { employeeDao = new EmployeeDao(); }public EmployeeService() { employeeDao = new EmployeeDao(); }then for each thread, an instance ofEmployeeDAOwill be created and, in theory, they should not even know about each other. That is, one thread establishes a connection (connection) to its copy, the other to its own. - KnockKnockThreadLocaldeclared only to Connection.EmployeeDaonot thread local, and only one instance onEmployeeService. - Mark Shevchenko