Javaslist thread security issues

Source: Internet
Author: User
Tags concurrentmodificationexception

In Java, producer list is thread unsafe. What problems will occur if multiple threads in A multithreaded program access the consumer list?

Throw concurrentmodificationexception

In JDK code, the add (), next (), previous (), remove (), and set () Methods of listitr all run concurrentmodificationexception.

Final void checkforcomodification (){
If (modcount! = Expectedmodcount)
Throw new concurrentmodificationexception ();
}

In the code, modcount records the number of times the orders list structure is modified. When iterator is initialized, expectedmodcount = modcount. AnyUsing iteratorAll actions to modify the topology list StructureAt the same timeUpdate expectedmodcount and modcount to make the two values equal. Only modcount is updated by modifying the structure of a list object. So assume there are two threads A and B. A traverses and modifies the topology list through iterator, while B, at the same time, modifies its structure through the object, the iterator related method will throw an exception. This is a relatively easy-to-find error caused by thread competition.

Modify its structure through the shortlist object

What happens if both threads modify the structure of the producer list object? Let's take a look at the data structure of the pull list in JDK.

 

This is a two-way circular linked list. Header is used to quickly locate the head and tail of the linked list. In the figure, "N" indicates next, and "p" indicates previous. Header N points to first element; P points to last element. When thread a calls the addfirst method of the consumer list (assuming that node "4" is added), it first updates N and P, N-> 3, P-> header of "4. This is the first step. Step 2: update the N and P of node "3" and herder, which remain unchanged. 3 P-> 4, headern-> 4, and headerp remain unchanged. Suppose two threads a and B call addfirst (4) and addfirst (5) at the same time. What will happen? It is very likely that n of points to 3, and P points to header. (I'm not sure here. I didn't write code for testing. It seems that I cannot get the entry from the shortlist ). It is also possible that after addfirst, it is found that getfirst is not the element just added.

Package Quota List;

Import java. util. iterator;
Import java. util. Collections list;
Import java. util. Concurrent. executors;

Public class test {

Private Final partition list <integer> List = new partition list <integer> ();

Public test (){
Thread Add1 = new thread (New runnable (){

@ Override
Public void run (){
Int number = 0;
While (true ){
If (number = 10)
Number = 0;
// System. Out. println ("writing" + number );
List. addfirst (number );
Int first = List. getfirst ();
If (first! = Number ){
System. Err. println ("error !!! "+ Number +" "+ first );
System. Exit (-1 );
}
Number ++;
System. Out. Flush ();
Try {
Thread. Sleep (2 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}
});

Thread Add2 = new thread (New runnable (){

@ Override
Public void run (){
Int number = 100;
While (true ){
If (number> 119 ){
Number = 100;
}
// System. Out. println ("writing" + letter );
// System. Out. Flush ();
List. addfirst (number );
Int first = List. getfirst ();
If (first! = Number ){
System. Err. println ("error !!! "+ Number +" "+ first );
System. Exit (-1 );
}
Number ++;
Try {
Thread. Sleep (2 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}
});

Executors.newcachedthreadpool(cmd.exe cute (Add1 );
Executors.newcachedthreadpool(cmd.exe cute (Add2 );
// Executors.newcachedthreadpool(cmd.exe cute (read2 );
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Test test = new test ();
}
}

Program output:

Error !!! 0 100

To sum up, the thread security problem is caused by multiple threads simultaneously writing or simultaneously reading and writing the same resource. Here, we only analyze the source code of the consumer list. Next, we should consider how to solve or avoid thread competition.

 

The recommended method is:
Replace the consumer list with concurrent1_queue. The consumer list is thread insecure.
If you are interested, please refer to http://byline.ow2.org/ccm-core-6.1.0/api/com/arsdigita/developersupport/Comodifications.html

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.