How do static and member variables behave in a. stateful batch classes?












2















Suppose I have a batch job and I want to maintain state (i.e. want to keep a log of the record ids that I've processed, or keep a running total, or something).



When would I use class variables vs. static variables in my batch class?



After the batch job finishes, do I have access to those variables in the class anymore?










share|improve this question





























    2















    Suppose I have a batch job and I want to maintain state (i.e. want to keep a log of the record ids that I've processed, or keep a running total, or something).



    When would I use class variables vs. static variables in my batch class?



    After the batch job finishes, do I have access to those variables in the class anymore?










    share|improve this question



























      2












      2








      2








      Suppose I have a batch job and I want to maintain state (i.e. want to keep a log of the record ids that I've processed, or keep a running total, or something).



      When would I use class variables vs. static variables in my batch class?



      After the batch job finishes, do I have access to those variables in the class anymore?










      share|improve this question
















      Suppose I have a batch job and I want to maintain state (i.e. want to keep a log of the record ids that I've processed, or keep a running total, or something).



      When would I use class variables vs. static variables in my batch class?



      After the batch job finishes, do I have access to those variables in the class anymore?







      apex batch asynchronous






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 18 at 21:14







      user11235813

















      asked Jan 18 at 20:37









      user11235813user11235813

      4,520647128




      4,520647128






















          2 Answers
          2






          active

          oldest

          votes


















          4














          There's a maximum amount of data you can serialize before the batch will fail (and also counts against your heap limits during execution). Static variables serve the same purpose as transient variables in Visualforce; they will not be serialized and therefore not count against heap. On the downside, static variables are reset between each transaction, so they will be null or set to their default initialization value, if any.



          In general, if you need to track the data, make sure it is not static, and if you do not need to track the data, make sure it is static. The more data you have to serialize, the slower your batch will run (serialization/deserialization requires more CPU time).



          The static variables will be available in unit tests after the batch execution, but the instance variables will not. None of these variables will be observable after the finish method returns in normal execution (e.g. execute anonymous scripts or Visualforce page contexts). If you need access to the results, you need to persist the data somewhere, such as the Platform Cache, a database record, etc.



          Static variables generally have two purposes: unit tests and sharing data across methods. The unit test bit is obvious; if you want to see what happened during the execution, you need a place to store it. The static variable can be accessed by the unit test after execution. As far as sharing data between methods, some developers prefer this method, but should probably be used sparingly, since it makes it less obvious which bits of data belong to which method.





          Edit:




          Alternatively, if I have a batch job that doesn't maintain state (doesn't use Database.Stateful ) how do member and static variables behave?




          In this mode, static variables work as before (they are not serialized and reset to null/default value), while instance variables are reloaded from the batch's initial state when it was placed in the queue using Database.executeBatch. No changes to instance variables are preserved between start, each execute, and finish calls.






          share|improve this answer


























          • This is great! thanks!

            – user11235813
            Jan 18 at 21:12













          • @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

            – sfdcfox
            Jan 18 at 21:22











          • you rock!!! thanks

            – user11235813
            Jan 18 at 21:24



















          3














          Per documentation (emphasis mine):




          If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.




          If you are looking to maintain state, then you will need to implement Database.Stateful and that utilize an instance variable to calculate any value.



          Because these are instance variables, you will have access to these variables during the life cycle of the class, e.g., you will be able to access these variables in finish method as well.





          Class Variables (are same as Static Variables) can be used to share a value between different instances of the same class. You can find more on Static variable on its documentation here.




          To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable.







          share|improve this answer


























          • so, when would I want to use a static variable in a stateful batch class?

            – user11235813
            Jan 18 at 20:45













          • You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

            – Jayant Das
            Jan 18 at 20:49











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "459"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f247224%2fhow-do-static-and-member-variables-behave-in-a-stateful-batch-classes%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          There's a maximum amount of data you can serialize before the batch will fail (and also counts against your heap limits during execution). Static variables serve the same purpose as transient variables in Visualforce; they will not be serialized and therefore not count against heap. On the downside, static variables are reset between each transaction, so they will be null or set to their default initialization value, if any.



          In general, if you need to track the data, make sure it is not static, and if you do not need to track the data, make sure it is static. The more data you have to serialize, the slower your batch will run (serialization/deserialization requires more CPU time).



          The static variables will be available in unit tests after the batch execution, but the instance variables will not. None of these variables will be observable after the finish method returns in normal execution (e.g. execute anonymous scripts or Visualforce page contexts). If you need access to the results, you need to persist the data somewhere, such as the Platform Cache, a database record, etc.



          Static variables generally have two purposes: unit tests and sharing data across methods. The unit test bit is obvious; if you want to see what happened during the execution, you need a place to store it. The static variable can be accessed by the unit test after execution. As far as sharing data between methods, some developers prefer this method, but should probably be used sparingly, since it makes it less obvious which bits of data belong to which method.





          Edit:




          Alternatively, if I have a batch job that doesn't maintain state (doesn't use Database.Stateful ) how do member and static variables behave?




          In this mode, static variables work as before (they are not serialized and reset to null/default value), while instance variables are reloaded from the batch's initial state when it was placed in the queue using Database.executeBatch. No changes to instance variables are preserved between start, each execute, and finish calls.






          share|improve this answer


























          • This is great! thanks!

            – user11235813
            Jan 18 at 21:12













          • @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

            – sfdcfox
            Jan 18 at 21:22











          • you rock!!! thanks

            – user11235813
            Jan 18 at 21:24
















          4














          There's a maximum amount of data you can serialize before the batch will fail (and also counts against your heap limits during execution). Static variables serve the same purpose as transient variables in Visualforce; they will not be serialized and therefore not count against heap. On the downside, static variables are reset between each transaction, so they will be null or set to their default initialization value, if any.



          In general, if you need to track the data, make sure it is not static, and if you do not need to track the data, make sure it is static. The more data you have to serialize, the slower your batch will run (serialization/deserialization requires more CPU time).



          The static variables will be available in unit tests after the batch execution, but the instance variables will not. None of these variables will be observable after the finish method returns in normal execution (e.g. execute anonymous scripts or Visualforce page contexts). If you need access to the results, you need to persist the data somewhere, such as the Platform Cache, a database record, etc.



          Static variables generally have two purposes: unit tests and sharing data across methods. The unit test bit is obvious; if you want to see what happened during the execution, you need a place to store it. The static variable can be accessed by the unit test after execution. As far as sharing data between methods, some developers prefer this method, but should probably be used sparingly, since it makes it less obvious which bits of data belong to which method.





          Edit:




          Alternatively, if I have a batch job that doesn't maintain state (doesn't use Database.Stateful ) how do member and static variables behave?




          In this mode, static variables work as before (they are not serialized and reset to null/default value), while instance variables are reloaded from the batch's initial state when it was placed in the queue using Database.executeBatch. No changes to instance variables are preserved between start, each execute, and finish calls.






          share|improve this answer


























          • This is great! thanks!

            – user11235813
            Jan 18 at 21:12













          • @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

            – sfdcfox
            Jan 18 at 21:22











          • you rock!!! thanks

            – user11235813
            Jan 18 at 21:24














          4












          4








          4







          There's a maximum amount of data you can serialize before the batch will fail (and also counts against your heap limits during execution). Static variables serve the same purpose as transient variables in Visualforce; they will not be serialized and therefore not count against heap. On the downside, static variables are reset between each transaction, so they will be null or set to their default initialization value, if any.



          In general, if you need to track the data, make sure it is not static, and if you do not need to track the data, make sure it is static. The more data you have to serialize, the slower your batch will run (serialization/deserialization requires more CPU time).



          The static variables will be available in unit tests after the batch execution, but the instance variables will not. None of these variables will be observable after the finish method returns in normal execution (e.g. execute anonymous scripts or Visualforce page contexts). If you need access to the results, you need to persist the data somewhere, such as the Platform Cache, a database record, etc.



          Static variables generally have two purposes: unit tests and sharing data across methods. The unit test bit is obvious; if you want to see what happened during the execution, you need a place to store it. The static variable can be accessed by the unit test after execution. As far as sharing data between methods, some developers prefer this method, but should probably be used sparingly, since it makes it less obvious which bits of data belong to which method.





          Edit:




          Alternatively, if I have a batch job that doesn't maintain state (doesn't use Database.Stateful ) how do member and static variables behave?




          In this mode, static variables work as before (they are not serialized and reset to null/default value), while instance variables are reloaded from the batch's initial state when it was placed in the queue using Database.executeBatch. No changes to instance variables are preserved between start, each execute, and finish calls.






          share|improve this answer















          There's a maximum amount of data you can serialize before the batch will fail (and also counts against your heap limits during execution). Static variables serve the same purpose as transient variables in Visualforce; they will not be serialized and therefore not count against heap. On the downside, static variables are reset between each transaction, so they will be null or set to their default initialization value, if any.



          In general, if you need to track the data, make sure it is not static, and if you do not need to track the data, make sure it is static. The more data you have to serialize, the slower your batch will run (serialization/deserialization requires more CPU time).



          The static variables will be available in unit tests after the batch execution, but the instance variables will not. None of these variables will be observable after the finish method returns in normal execution (e.g. execute anonymous scripts or Visualforce page contexts). If you need access to the results, you need to persist the data somewhere, such as the Platform Cache, a database record, etc.



          Static variables generally have two purposes: unit tests and sharing data across methods. The unit test bit is obvious; if you want to see what happened during the execution, you need a place to store it. The static variable can be accessed by the unit test after execution. As far as sharing data between methods, some developers prefer this method, but should probably be used sparingly, since it makes it less obvious which bits of data belong to which method.





          Edit:




          Alternatively, if I have a batch job that doesn't maintain state (doesn't use Database.Stateful ) how do member and static variables behave?




          In this mode, static variables work as before (they are not serialized and reset to null/default value), while instance variables are reloaded from the batch's initial state when it was placed in the queue using Database.executeBatch. No changes to instance variables are preserved between start, each execute, and finish calls.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 18 at 21:21

























          answered Jan 18 at 20:45









          sfdcfoxsfdcfox

          255k11200441




          255k11200441













          • This is great! thanks!

            – user11235813
            Jan 18 at 21:12













          • @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

            – sfdcfox
            Jan 18 at 21:22











          • you rock!!! thanks

            – user11235813
            Jan 18 at 21:24



















          • This is great! thanks!

            – user11235813
            Jan 18 at 21:12













          • @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

            – sfdcfox
            Jan 18 at 21:22











          • you rock!!! thanks

            – user11235813
            Jan 18 at 21:24

















          This is great! thanks!

          – user11235813
          Jan 18 at 21:12







          This is great! thanks!

          – user11235813
          Jan 18 at 21:12















          @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

          – sfdcfox
          Jan 18 at 21:22





          @user11235813 Edited answer to the question. In summary, the only difference is that changes to instance variables are instead lost and reset back to the moment database.executebatch was called.

          – sfdcfox
          Jan 18 at 21:22













          you rock!!! thanks

          – user11235813
          Jan 18 at 21:24





          you rock!!! thanks

          – user11235813
          Jan 18 at 21:24













          3














          Per documentation (emphasis mine):




          If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.




          If you are looking to maintain state, then you will need to implement Database.Stateful and that utilize an instance variable to calculate any value.



          Because these are instance variables, you will have access to these variables during the life cycle of the class, e.g., you will be able to access these variables in finish method as well.





          Class Variables (are same as Static Variables) can be used to share a value between different instances of the same class. You can find more on Static variable on its documentation here.




          To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable.







          share|improve this answer


























          • so, when would I want to use a static variable in a stateful batch class?

            – user11235813
            Jan 18 at 20:45













          • You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

            – Jayant Das
            Jan 18 at 20:49
















          3














          Per documentation (emphasis mine):




          If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.




          If you are looking to maintain state, then you will need to implement Database.Stateful and that utilize an instance variable to calculate any value.



          Because these are instance variables, you will have access to these variables during the life cycle of the class, e.g., you will be able to access these variables in finish method as well.





          Class Variables (are same as Static Variables) can be used to share a value between different instances of the same class. You can find more on Static variable on its documentation here.




          To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable.







          share|improve this answer


























          • so, when would I want to use a static variable in a stateful batch class?

            – user11235813
            Jan 18 at 20:45













          • You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

            – Jayant Das
            Jan 18 at 20:49














          3












          3








          3







          Per documentation (emphasis mine):




          If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.




          If you are looking to maintain state, then you will need to implement Database.Stateful and that utilize an instance variable to calculate any value.



          Because these are instance variables, you will have access to these variables during the life cycle of the class, e.g., you will be able to access these variables in finish method as well.





          Class Variables (are same as Static Variables) can be used to share a value between different instances of the same class. You can find more on Static variable on its documentation here.




          To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable.







          share|improve this answer















          Per documentation (emphasis mine):




          If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.




          If you are looking to maintain state, then you will need to implement Database.Stateful and that utilize an instance variable to calculate any value.



          Because these are instance variables, you will have access to these variables during the life cycle of the class, e.g., you will be able to access these variables in finish method as well.





          Class Variables (are same as Static Variables) can be used to share a value between different instances of the same class. You can find more on Static variable on its documentation here.




          To store information that is shared across instances of a class, use a static variable. All instances of the same class share a single copy of the static variable.








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 18 at 20:50

























          answered Jan 18 at 20:43









          Jayant DasJayant Das

          14.3k2824




          14.3k2824













          • so, when would I want to use a static variable in a stateful batch class?

            – user11235813
            Jan 18 at 20:45













          • You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

            – Jayant Das
            Jan 18 at 20:49



















          • so, when would I want to use a static variable in a stateful batch class?

            – user11235813
            Jan 18 at 20:45













          • You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

            – Jayant Das
            Jan 18 at 20:49

















          so, when would I want to use a static variable in a stateful batch class?

          – user11235813
          Jan 18 at 20:45







          so, when would I want to use a static variable in a stateful batch class?

          – user11235813
          Jan 18 at 20:45















          You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

          – Jayant Das
          Jan 18 at 20:49





          You will normally use a static variable when you want to share the value of say a variable across different instances of the same class. I have added some references around this in my answer.

          – Jayant Das
          Jan 18 at 20:49


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f247224%2fhow-do-static-and-member-variables-behave-in-a-stateful-batch-classes%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Human spaceflight

          Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

          張江高科駅