Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between getDefaultInstance() and getInstance() in Session class?

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?

like image 601
Gnanam Avatar asked Nov 15 '10 12:11

Gnanam


People also ask

What is mail Session?

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.


2 Answers

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.

like image 87
Codemwnci Avatar answered Sep 28 '22 00:09

Codemwnci


FAQ says: https://javaee.github.io/javamail/FAQ#getdefaultinstance

Q: When should I use Session.getDefaultInstance and when should I use Session.getInstance?

A: Almost all code should use Session.getInstance. The Session.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 use Session.getInstance to avoid this problem.

like image 27
Yasin Okumuş Avatar answered Sep 28 '22 01:09

Yasin Okumuş