What is the difference between Session.getDefaultInstance(props, authenticator)
and getInstance(props, authenticator)
? In general, when will you choose one over the other?
I also read Java doc on getDefaultInstance(props, authenticator), but still couldn't able to make out the difference distinctly/clearly.
Hope experts can help me in understanding this better.
UPDATE: Actual reason that triggered to ask this question is: We've used Session.getDefaultInstance()
method in some places within our web-based application. Sometimes, it throws java.lang.SecurityException: Access to default session denied
, on quick googling, it suggested to use Session.getInstance()
method instead. Hence, when one would choose one over the other?
The Session class represents a mail session and is not subclassed. It collects together properties and defaults used by the mail API's. A single default session can be shared by multiple applications on the desktop. Unshared sessions can also be created.
If you read the documentation, you will see that
getDefaultInstance Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default.
Therefore, if one does not already exist, it call getInstance()
getInstance Get a new Session object.
So, a new session object is created, regardless of whether one already exists.
FAQ says: https://javaee.github.io/javamail/FAQ#getdefaultinstance
Q: When should I use
Session.getDefaultInstance
and when should I useSession.getInstance
?A: Almost all code should use
Session.getInstance
. TheSession.getDefaultInstance
method creates a new Session the first time it's called, using the Properties that are passed. Subsequent calls will return that original Session and ignore any Properties you pass in. If you want to create different Sessions with different properties, Session.getDefaultInstance won't do that. If some other code in the same JVM (e.g., in the same app server) has already created the default Session with their properties, you may end up using their Session and your properties will be ignored. This often explains why your property settings seem to be ignored. Always useSession.getInstance
to avoid this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With