Beer Gupta Beer Gupta - 3 months ago 24
Java Question

Transaction in Spring

I am new to Spring and have a question about transactions.

I know that for each http request there is a servlet thread which has its own stack. As far I know all the local variables and method reside on the stack. So if I have a method

public void A();
then both the servlet thread A and thread B have a copy of a function in their stack.

Now If I annotated a method with
@Transactional(propagation=Propagation.REQUIRED ,timeout=1,isolation=Isolation.READ_COMMITTED)
then I would like to know the following points:


  1. Does each thread A and thread B have their own stack and work independently?

  2. If thread A is updating something and B is reading something because of in different stack is Isolation will work? or B will read the data with out any information about the thread A?



I want to know this by the diagram so that I can understand how end to end things work?

Answer

Each thread has its own stack, you're right here. But they don't have copies of methods. Method is just a series of operations. But they have copies of variables inside this method (local variables).

Speaking about isolation level, actually it has nothing to do with threads and stacks. It refers to a database isolation level notion. Spring asks your database for that level to be used for database transaction. PostreSQL has a great doc page explaining transaction isolation.

So it's not quite right here to ask how threads see each other, because in the sense of data they see what they get from the database. And the database returns data accordingly to current transaction isolation level. Each thread starts its own transaction, i.e. it creates a new connection to the database and tells it to start a new transaction.

Example

To feel what's going on under the hood, here is an example. Suppose you have such method:

@Transactional
public Person getPerson(int id) {
    Person person = em.find(Person.class, id);
    return person;
}

Here is what's going on under the Spring's hood per each line:

@Transactional
public Person getPerson(int id) {
// SQL sent to the database:
// Begin transaction

Person person = em.find(Person.class, id);
// SQL sent to the database:
// select p from person p where p.id = id
// the data from the database then gets converted to Java Person class

return person;
}
// after end of the method Spring automatically commits the transaction (not always, it depends on the `propagation` setting)
// SQL sent to the database:
// commit

Please, read PostgreSQL docs that explains transaction isolation in depth. Java threads only receive data accordingly to it.