Thread safety for Java member variables

Source: Internet
Author: User

This article explains thread-safety issues about Java member variables, including static and instance variables. Static variables are well understood, all instances share a single memory, and any modification of static variables raises thread-safety issues. However, for instance variables, access and modification are thread-safe in most cases. However, when this class, implemented in the system as a singleton mode, because the entire system, only one object memory, so the system's various threads of the instance variable modification will cause thread safety problems. This is not to say that Java novice easy to commit negligence, a Java programmer with some experience is also careless in making mistakes, and sometimes, because of knowledge or other reasons, programmers simply do not know that the instance being used is a single example (for example, an instance obtained from a factory, The action in Struts1, the default scope in the Spring container is singleton, and so on.

This is explained in code below. The code consists of three classes: FIELDSVO contains two member variables (static and instance) that are used to access in multiple threads, fieldvaluewatcher inherit from thread to simulate access to FIELDSVO classes, test testing classes.

First, let's take a look at the first Vo class, very simple, only two member variables: static and instance, and two corresponding modifier and accessor

public class Fieldsvo {private string value, private static string Staticvalue public static string Getstaticvalue () {R Eturn Staticvalue; public static void Setstaticvalue (String staticvalue) {fieldsvo.staticvalue = Staticvalue;} public String GetValue () { return value; public void SetValue (String value) {this.value = value;}}

Thread Detection class: Fieldvaluewatcher

         public class Fieldvaluewatcher extends Thread {private String Staticvalue; Private String Instancevalue; Public Fieldvaluewatcher () {this.staticvalue = "static--" + getName (); this.instancevalue = "instance--" + GetName ();} p Rivate FIELDSVO Vo; Public FIELDSVO Getvo () {return VO;} public void Setvo (Fieldsvo vo) {this.vo = vo;} public void Run () {System.out.pri Ntln (GetName () + "start setting the value [static value=" + This.staticvalue + "; instancevalue=" + This.instancevalue + "]"); Fieldsvo.setstaticvalue (This.staticvalue); Vo.setvalue (This.instancevalue); System.out.println (GetName () + "To do something else, may take a long time"); Random r = new Random (2000); try {sleep (Math.Abs (r.nextint ()% 10000))//length of hibernation affects the detection effect, the longer the time, the greater the likelihood of data being incomplete} catch (Interruptedexception e) {System. Out.print (GetName () + "terminated"); } if (!this.staticvalue.equals (Fieldsvo.getstaticvalue ())) {System.out.println (GetName () +) FIELDSVO static data is disrupted, now the data is : "+ fieldsvo.getstaticvalue ());} else {SystEm.out.println ("lucky.") static data integrity: "+ fieldsvo.getstaticvalue ()); The instance data of the IF (!this.instancevalue.equals (Vo.getvalue ()) {System.out.println (GetName () +) FIELDSVO is disrupted, and now the data is: "+ Vo.getvalue ()); else {System.out.println (lucky). Instance data complete: "+ vo.getvalue ()); } } }

Test class: Generates 4 Fieldvaluewatcher instances, and gets the FIELDSVO instance individually from the spring container (configuration reference Part IV code) and sets the instance to the VO member of the Fieldvaluewatcher instance, starting the thread.

public class Test {public static final String vo_bean_id = ' blog.fieldsafty.vo '; public static void Main (string[] args) { fieldvaluewatcher[] ths = new fieldvaluewatcher[] {new Fieldvaluewatcher (), New Fieldvaluewatcher (), New Fieldvaluewatch ER (), New Fieldvaluewatcher ()}; for (int i = 0, j = ths.length I < J; i++) {Fieldsvo vo = (FIELDSVO) servicelocator.getapplicationcontext (). Getbean ( VO_BEAN_ID); System.out.println (VO); Ths[i].setvo (VO); Ths[i].start (); } } }

Spring Configuration:

<bean class= "Blog.threadsafe.field.FieldsVo" scope= "singleton" id= "Blog.fieldsafty.vo" > </bean>

Run Result:

Blog.threadsafe.field.fieldsvo@691f36
Blog.threadsafe.field.fieldsvo@691f36
Blog.threadsafe.field.fieldsvo@691f36
Thread-0 start setting value [Static value=static--thread-0;instancevalue=instance--thread-0]
Blog.threadsafe.field.fieldsvo@691f36
Thread-0 to do something else, it could take a long time.
Thread-2 start setting value [Static Value=static--thread-2;instancevalue=instance--thread-2]
Thread-2 to do something else, it could take a long time.
Thread-1 start setting value [Static Value=static--thread-1;instancevalue=instance--thread-1]
Thread-1 to do something else, it could take a long time.
Thread-3 start setting value [Static value=static--thread-3;instancevalue=instance--thread-3]
Thread-3 to do something else, it could take a long time.
Thread-2 FIELDSVO static data is disrupted, now the data is: static--thread-3
Thread-0 FIELDSVO static data is disrupted, now the data is: static--thread-3
Thread-1 FIELDSVO static data is disrupted, now the data is: static--thread-3
Thread-2 FIELDSVO's instance data is disrupted, and now the data is: instance--thread-3
Thread-0 FIELDSVO's instance data is disrupted, and now the data is: instance--thread-3
Thread-1 FIELDSVO's instance data is disrupted, and now the data is: instance--thread-3
Lucky. static data integrity: Static--thread-3
Lucky. Instance data complete: instance--thread-3

From the results of the operation can be three conclusions: 1, Spring container to obtain the FIELDSVO instances are the same one, that FIELDSVO is indeed a singleton, 2, in a multi-threaded environment, static data is unsafe; 3, Instance variables for BLOG.THREADSAFE.FIELD.FIELDSVO@691F36 instances are also unsafe in multi-threaded environments.

Modify the scope configuration of the FIELDSVO to prototype, and then observe the results of the operation:

Blog.threadsafe.field.fieldsvo@1d05c81
Thread-0 start setting value [Static value=static--thread-0;instancevalue=instance--thread-0]
Thread-0 to do something else, it could take a long time.
Blog.threadsafe.field.fieldsvo@691f36
Thread-1 start setting value [Static Value=static--thread-1;instancevalue=instance--thread-1]
Thread-1 to do something else, it could take a long time.
blog.threadsafe.field.fieldsvo@18020cc
Thread-2 start setting value [Static Value=static--thread-2;instancevalue=instance--thread-2]
Thread-2 to do something else, it could take a long time.
Blog.threadsafe.field.fieldsvo@e94e92
Thread-3 start setting value [Static value=static--thread-3;instancevalue=instance--thread-3]
Thread-3 to do something else, it could take a long time.
Thread-2 FIELDSVO static data is disrupted, now the data is: static--thread-3
Thread-1 FIELDSVO static data is disrupted, now the data is: static--thread-3
Lucky. static data integrity: Static--thread-3
Thread-0 FIELDSVO static data is disrupted, now the data is: static--thread-3
Lucky. Instance data complete: instance--thread-1
Lucky. Instance data complete: instance--thread-3
Lucky. Instance data complete: instance--thread-0
Lucky. Instance data complete: instance--thread-2

From the results of the operation there can be three conclusions:

1. Each FIELDSVO instance obtained in the spring container is not the same;

2, in the multi-threaded environment, static data is not safe;

3, non-singleton instance variables are thread-safe.
In summary, the single case model should not use the very variable member variables, or the change of the member variable and the accessor synchronization control, however, this will affect the access to the single example and modify performance.

Similar code can extend findbugs plug-ins so that findbugs can find similar code problems. Details Visible article: http://www.51testing.com/?uid-294525-action-viewspace-itemid-211629

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.