This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I think you should rephrase your question: the "need" and "optionally" words don't go well together. Anyways, here's your answer:
A stateful session bean class can optionally implement the javax.ejb.SessionSynchronization interface. This interface provides the session bean instances with transaction synchronization notifications. The instances can use these notifications, for example, to manage database data they may cache within transactions�e.g., if the Java Persistence API is not used.
Some times you write a stateful Session Bean which does some database operations like.. Insert update and delete and for these operations you have written some methods in your bean class say.. goInsert(), goUpdate(),goDelete().
Since it is stateful session bean for your business logic you'll declare some instance variables in your class and those are nothing but the database fields, values of which you are going to take as parameters of these methods (goInsert,goUpdate,goDelete). It may have one more method called getData(id) which selects the data populates it inside the bean variables.
For this bean container is managing the transaction.
Consider that For the first time when client wants do to some processing it selects the data. so it calls getData(id), all the variables will be populated with data from database. Data has given to client through some DTO. Client modifies that data and calls ....
... goUpdate by passing changed values to it.. the container first will start a new transaction then it'll invoke the method. After the method call container is going to commit.
During this method invocation suppose you've updated few values in database and something goes wrong at runtime and exception occurs... so what will happen to the data inside the database and to the values of instance variables
to handle such situations... the bean has to implement SessionSynchronization interface where some callbacks will get called before start of Tx after end of Tx etc...
just correlate this example after applying SessionSynchronization and follow the specs