Static variables, instance variables, local variables for Java thread safety issues

Source: Internet
Author: User

Static variable: thread is not secure.

The variable with the static keyword can only be placed in a class and cannot be placed in a method.

A static variable is a class variable, located in the method area, shared for all objects, shares a portion of memory, and once the static variable is modified, the other objects are visible to the modification, so the thread is not secure.

Instance variables: Singleton mode (only one object instance exists) thread is not secure, not singleton thread safe.

Variables that do not have a static keyword can only be placed in a class and cannot be placed in a method.

Instance variables are private to the object instance, allocated in the heap of the virtual machine, if there is only one instance of this object in the system, in multi-threaded environment, "like" static variable, after being modified by a thread, other threads are visible to the modification, so the thread is not safe, if each thread executes in a different object, The modification of the instance variable between the object and the object will not affect each other, so thread safety.

Local variables: thread safety.

A local variable is a variable within a method.

Each thread executes a local variable in the working memory of its own stack frame and is not shared between threads, so there is no thread-safety issue.

Static variables, instance variables, local variables for Java thread safety issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.