Why use the `transient` keyword in java?

Sitansu picture Sitansu · Dec 20, 2013 · Viewed 45.1k times · Source

I have an issue related to the transient keyword's use before the private modifier in java .

variable declaration:

transient private ResourceBundle pageResourceBundle; 

My class looks like this :

public class LoginViewModel extends AbstractViewModel {

    transient private ResourceBundle pageResourceBundle;

    @AfterCompose
    public void afterCompose(@ContextParam(ContextType.VIEW) Component view) {
        initializeLoginValues();
        boolean timeout = BooleanUtils.toBoolean(getHttpServletRequest().getParameter("timeout"));
        if (timeout) {
            Messagebox.show(pageResourceBundle.getText("MSG_SESSION_HAS_EXPIRED_PLEASE_LOGIN"), pageResourceBundle.getText("LABEL_ALERT"),
                    Messagebox.OK, Messagebox.ERROR);
        }
        view.getPage().setTitle(CsdcLicence.get().getApplicationName());
    }

I have some questions.

1.why use the transient keyword before a private variable?

2.what is the purpose of using this keyword?

Answer

rachana picture rachana · Dec 20, 2013

transient variables are never serialized in java.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

please have a look at what serialization is.? and also refer this

Example

public class Foo implements Serializable
{
  private String saveMe;
  private transient String dontSaveMe;
  private transient String password;
  //...
}

In above example dontSaveMe & password are never get serialize as they are declare as a transient variables.