2010/11/10 Emmanuel Lecharny <[email protected]>: > On 11/10/10 9:27 PM, Jason Weinstein wrote: >> >> Is the method >> >> public void messageReceived(final IoSession session, final Object >> message) throws Exception { >> >> threadsafe per IoSession? > > yes. >> >> That is can the same IoSession under any circumstance receive messages at >> the same time? > > No. Not while a message is being processed by a thread. Unless you added an > ExecutorFilter in the chain. > > Note although that if you have a split message, you may have some > discontinuity in the processing. >> >> >> If it is threadsafe, then i am curious if this should work for accessing >> EM in a threadsafe way? > > Give it a try :) >> >> And if it is assured to close? And/or under what circumstances >> sessionDestroyed might not be called? > > It is assured to close, yes, as soon as the client safely close the session, > or if you handle the idle time to close the session after a timeout occured. >> >> ie OutOfMemoryError, etc > > It's up to you to handle such an exception in the ExceptionCaught handler. >> >> public void sessionCreated(final IoSession session) throws Exception { >> session.setAttribute("EM", >> entityManagerFactory.createEntityManager()); >> >> public void sessionDestroyed(final IoSession session) throws Exception { >> final EntityManager entityManager = (EntityManager) >> session.getAttribute("EM"); >> entityManager.close(); >> >> public void messageReceived(final IoSession session, final Object >> message) throws Exception { >> final EntityManager entityManager = (EntityManager) >> session.getAttribute("EM"); >> // do something with EM >> >> I am also wondering, bar Spring, etc, thoughts on whether this would be >> considered a good practice?
You can read this in Hibernate configuration: An EntityManager is an inexpensive, non-threadsafe object that should be used once, for a single business process, a single unit of work, and then discarded. An EntityManager will not obtain a JDBC Connection (or a Datasource) unless it is needed, so you may safely open and close an EntityManager even if you are not sure that data access will be needed to serve a particular request. (This becomes important as soon as you are implementing some of the following patterns using request interception.) This said, I don't know if it stills hold true for JPA 2.0. If you are using Spring to inject your EntityManager, you don't have to worry about thread-safeness and it's ok to have a @PersistenceContext ( If it's not a extended persistence context). I'm of course talking about a hypothetical case in which you have an ExecutionFilter in the chain.
