4 Replies Latest reply: Nov 19, 2013 9:52 PM by Murray9654 RSS

    is this the way stack works ?

    Murray9654

      Hi i have been working with programming from long time and today when i have gone through some piece of code i am really struck. The point where i struck is, the way the stack memory works. So suppose we have the following example:-

       

      public class Car{
      
           private static int count=0;
      
           public static void main (String [] args){
                count++;
           }
      }
      
      
      

       

      So the above code works the following way on the stack:-

       

      --------Man method stack begins----------

      int count=0;                         // the variable is copied on to the stack first and initialized to zero

      //count++  ;                          // mathematical operation happens

      //now the count changes to 1;

      //after addition happened on the local variable the current value of local "count" will be 1 so now the variable value is as below

      count=1;

      // remaining operations goes on (if any)

      _______________end of main method stack------------

       

      So my question is "does all the variables required for the method for successful execution does first gets copied or copied when ever required on to the stack ? and  If all the stack operations( I mean mathematical operations in the method) happens on this local copies when will the original variables (i mean class variable count (according to my example) ) gets updated?

       

      I am into this dilemma because i am trying to understand how "volatile" data works. Thanking you so much.

        • 1. Re: is this the way stack works ?
          rp0428
          I am into this dilemma because i am trying to understand how "volatile" data works.

          Two comments: first you don't really need to get into that level of detail to understand what 'volatile' fields are and what effect they have on operations.

           

          Second there is more to it that just stack operations. Volatile fields are used as part of certain multi-threaded operations to ensure the order in which data is processed (to some degree).

           

          Review section 8.3.1.4 volatile Fields in the Java Language Specification

          http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4

          The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.


          The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.


          A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

          You also need to read that referenced section 17.4 Memory Model which should help you understand things a bit more.

           

          If you really, really, really want to get into the instruction set details they are all documented in the Java Virtual Machine Spec. You will need to search the doc for specific examples of interest but Section 3.2 Use of Constants, Local Variables, and Control Constructs

          http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.2

          Java Virtual Machine code exhibits a set of general characteristics imposed by the Java Virtual Machine's design and use of types. In the first example we encounter many of these, and we consider them in some detail.

          The spin method simply spins around an empty for loop 100 times:

          void spin() {  int i;  for (i = 0; i < 100; i++) {  ;    // Loop body is empty  }  }    

          A compiler might compile spin to:

          0   iconst_0       // Push int constant 0  1   istore_1       // Store into local variable 1 (i=0)  2   goto 8         // First time through don't increment  5   iinc 1 1       // Increment local variable 1 by 1 (i++)  8   iload_1        // Push local variable 1 

           

            9   bipush 100     // Push int constant 100  11  if_icmplt 5    // Compare and loop if less than (i < 100)  14  return         // Return void when done  

          The Java Virtual Machine is stack-oriented, with most operations taking one or more operands from the operand stack of the Java Virtual Machine's current frame or pushing results back onto the operand stack. A new frame is created each time a method is invoked, and with it is created a new operand stack and set of local variables for use by that method (§2.6). At any one point of the computation, there are thus likely to be many frames and equally many operand stacks per thread of control, corresponding to many nested method invocations. Only the operand stack in the current frame is active.

          • 2. Re: is this the way stack works ?
            Murray9654

            rp0428 wrote:

             

            I am into this dilemma because i am trying to understand how "volatile" data works.

            Two comments: first you don't really need to get into that level of detail to understand what 'volatile' fields are and what effect they have on operations.

            I am not sure why you think it is not necessary to understand what volatile keyword is. If there is a keyword in language it is not there because the designers of the language just wants to have a fancy name in their language. The volatile keyword has not properly explained anywhere. Even if you google you may find example code but none provided a decent explanation and understanding this keyword makes sense when you are designing a multithreaded application. To that matter even highly experienced people fail to explain this.

             

             

             

            Review section 8.3.1.4 volatile Fields in the Java Language Specification

            http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4

            The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.


            The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.


            A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

            You also need to read that referenced section 17.4 Memory Model which should help you understand things a bit more.

             

            If you really, really, really want to get into the instruction set details they are all documented in the Java Virtual Machine Spec. You will need to search the doc for specific examples of interest but Section 3.2 Use of Constants, Local Variables, and Control Constructs

            http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.2

            Java Virtual Machine code exhibits a set of general characteristics imposed by the Java Virtual Machine's design and use of types. In the first example we encounter many of these, and we consider them in some detail.

            The spin method simply spins around an empty for loop 100 times:

            void spin() {  int i;  for (i = 0; i < 100; i++) {  ;    // Loop body is empty  }  }    

            A compiler might compile spin to:

            0   iconst_0       // Push int constant 0  1   istore_1       // Store into local variable 1 (i=0)  2   goto 8         // First time through don't increment  5   iinc 1 1       // Increment local variable 1 by 1 (i++)  8   iload_1        // Push local variable 1 

             

              9   bipush 100     // Push int constant 100  11  if_icmplt 5    // Compare and loop if less than (i < 100)  14  return         // Return void when done  

            The Java Virtual Machine is stack-oriented, with most operations taking one or more operands from the operand stack of the Java Virtual Machine's current frame or pushing results back onto the operand stack. A new frame is created each time a method is invoked, and with it is created a new operand stack and set of local variables for use by that method (§2.6). At any one point of the computation, there are thus likely to be many frames and equally many operand stacks per thread of control, corresponding to many nested method invocations. Only the operand stack in the current frame is active.

            I am not sure what you are talking about. If everything can be understood just by reading specs then every developer on this earth regardless of his experience would have been a jem (highly talented)  and no company needs to hunt for talent which could save lot of time, money and effort for companies in the market.

             

            At last there is nothing relevant to my question except some part copied from the java spec which i already knew. Anyway thanks for your time.

            • 3. Re: is this the way stack works ?
              rp0428
              I am not sure why you think it is not necessary to understand what volatile keyword is.

              And I am 'not sure' where you got the notion that I think 'it is not necessary to understand what volatile keyword' is especially because you quoted EXACTLY what I actually did say:

              Two comments: first you don't really need to get into that level of detail to understand what 'volatile' fields are and what effect they have on operations.

              There is NOTHING in that that either says, or implies that  'it is not necessary to understand what volatile' means. Your post was discussing things like stack operations which aren't even applicable to 'volatile' operations. So I commented that you don't need to understand the actual internals. Perhaps English is not your primary language?

               

              Let me say it a different way: all that is needed is a FUNCTIONAL understanding; not a technical understanding of how 'volatile' is actually implemented.

              If there is a keyword in language it is not there because the designers of the language just wants to have a fancy name in their language. The volatile keyword has not properly explained anywhere.

              And again you are making assumptions that are NOT supported by anything that I said.

               

              The documentation, and quotes, that I provided show that the volatile keyword has, indeed, benn 'properly explained' somewhere. That is why I gave you those links; so you could see for yourself exactly how the inventors of Java defined 'volatile', discussed its purpose and defined the requirements for its implementation.

               

              Because you were wanting to understand how the access to volatiles is achieved I also stressed this:

              You also need to read that referenced section 17.4 Memory Model which should help you understand things a bit more.

              After all this is EXACTLY what you said in your original post:

              The point where i struck is, the way the stack memory works.

              And section 17.4 is about EXACTLY that: the Memory Model. That section has several references to 'volatile' and if you read it you will find that it  not only presents use cases for volatile it provides a couple of detailed examples showing how it can be used to properly synchronize the actions of two threads.

               

              Your original post also included an example of a simple postfix ++ operation and you said this:

              So my question is "does all the variables required for the method for successful execution does first gets copied or copied when ever required on to the stack ? and  If all the stack operations( I mean mathematical operations in the method) happens on this local copies when will the original variables (i mean class variable count (according to my example) ) gets updated?

              Again - you mention stack operations; this time in the context of your postfix ++ example.

               

              So I provided the link to the JVM spec document because it has an example showing EXACTLY that: how a postfix ++ operation is ACTUALLY implemented using stack operations.

              At last there is nothing relevant to my question except some part copied from the java spec which i already knew.

              Clearly EVERYTHING I said and referenced is precisely relevant to your question and what you posted in the way of supporting information.

               

              It totally escapes me how you can not see that.

               

              My contribution above is relevant to your question even if you can't understand why. Also, the forums are to help everyone, not just the one creating the thread. The supporting documentation I provided will help others understand the concept of volatile better and provides links to two very important documents that explain a great deal of Javas underpinnings.

              Anyway thanks for your time.

              You're welcome! I wish there was some other way to present the same information in a way that would make it clearer for you. Perhaps others will be more successful at that.

              • 4. Re: is this the way stack works ?
                Murray9654

                rp0428 wrote:

                 

                I am not sure why you think it is not necessary to understand what volatile keyword is.

                And I am 'not sure' where you got the notion that I think 'it is not necessary to understand what volatile keyword' is especially because you quoted EXACTLY what I actually did say:

                Sorry for misunderstanding. I did understood your context. When u said you dont need to get to that detail some how i sensed that u  are saying it is not necessary to spent time on understanding the keyword.

                 

                 

                Two comments: first you don't really need to get into that level of detail to understand what 'volatile' fields are and what effect they have on operations.

                 

                I don't agree on this. if you have to understand volatile the best way is to understand the situation where actually it is required and for that understanding how stack works gives you the opportunity. According to you is to understand the memory model. At once you are saying that understanding stack is not required and at the same time u are providing pointers to specs where stack operations are explained

                 

                My contribution above is relevant to your question even if you can't understand why. Also, the forums are to help everyone, not just the one creating the thread. The supporting documentation I provided will help others understand the concept of volatile better and provides links to two very important documents that explain a great deal of Javas underpinnings.

                .I completely agree that the discussion that happens on the thread is not only for the creator of the thread but expect to be relevant and helpful who have come here with a problem and it is.

                Finally thank you so much for all the time you gave for this thread and i am posting an answer for my question which explains why understanding stack operations are important to understand volatile. Thank you so much for everything.