Java threads are not secure. java threads

Source: Internet
Author: User

Java threads are not secure. java threads
Threads that are not secure cause conflicts when they access resources.

For example

package com.test.thread;public class TestConfilict {/** * @param args */public static void main(String[] args) {Counter counter=new Counter();for(int i=0;i<10000;i++){(new TestThread(counter)).start();}}}class TestThread extends Thread{private Counter counter;public TestThread(Counter counter){this.counter=counter;}public void run(){counter.add(1);System.out.println(counter.get());}}class Counter{protected int count=0;public void add(int value){count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;}public int get(){return count;}}


The original intention of this example is to increase from 0 to 10000. If it is a single thread, the output result is 100000. We use multi-threaded methods. Each thread is responsible for increasing by 10, with a total of 10000 threads.

We can see that






We can see that the output results are different, and none of them are 100000. This shows that the thread is insecure, that is, a conflict occurs when operations on the same resource. Specifically, this means that when there is no resource protection, multiple threads enter the added code at the same time.

Then, we can use the locking method to solve the problem.

package com.test.thread;public class TestConfilict {/** * @param args */public static void main(String[] args) {Counter counter=new Counter();for(int i=0;i<10000;i++){(new TestThread(counter)).start();}}}class TestThread extends Thread{private Counter counter;public TestThread(Counter counter){this.counter=counter;}public void run(){counter.add(1);System.out.println(counter.get());}}class Counter{protected int count=0;public synchronized void add(int value){count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;count=count+value;}public int get(){return count;}}


We can see that the output result


The lock method is used to ensure thread security.


In java, the array, thread-safe and insecure are

For example, if two threads operate on the same ArrayList variable, the data read by one thread at this time may change at the next moment.

Thread security is generally considered in a scenario similar to the following:

ArrayList products = new ArrayList ();
Products is used to store the products produced.
Now suppose there are three consumer threads and two producer threads.
Each producer thread produces a product and executes
Products. add (new Product ());
Each consumer thread consumes a product for execution.
If (products. size ()> = 1) {products. remove (0 );}

If there is only one product in products that can be consumed, but there are two consumer threads requesting consumption, there may be a problem of simultaneous consumption of a product, which is inconsistent with the actual situation.

However, this error does not occur when different threads access the Vector, Because java has a mechanism that only one thread operates on this variable at the same time.

This is called:
Vector: thread-safe
ArrayList: Not thread-safe

What is thread security in java?

If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe.
In other words, the interface provided by a class or program is an atomic operation for a thread or the switching between multiple threads does not lead to ambiguity in the execution result of this interface, that is to say, we do not need to consider synchronization issues.
Thread security issues are caused by global variables and static variables.
If each thread only performs read operations on global variables and static variables without write operations, this global variable is generally thread-safe. If multiple threads execute write operations at the same time, generally, thread synchronization needs to be considered; otherwise, thread security may be affected.

For example, an ArrayList class may take two steps to add an element: 1. Store this element at the Items [Size] position; 2. Increase the Size value.
When a single thread is running, if the Size is 0, after an element is added, the element is in the position 0 and the Size is 1;
In the case of multithreading, for example, if there are two threads, thread A first stores the elements in the position 0. However, at this time, the CPU scheduling thread A is paused, and thread B gets the chance to run. Thread B also adds an element to this ArrayList, because the Size is still equal to 0 (note that we assume that two steps are required to add an element, thread A only completes step 1), so thread B also stores the elements in the position 0. Then, both thread A and thread B continue to run, increasing the Size value.
Well, now let's take a look at the ArrayList. There is actually only one element, which is stored in the position 0, but the Size is equal to 2. This is "thread unsafe.
To edit this thread security class to become thread-safe, you must first have the correct behavior in the single-threaded environment. If a class is implemented correctly (this is another way to say it complies with the specifications ), there is no operation sequence (read or write public fields and call public methods) for the objects of this class to make the objects invalid, it is observed that the object is in an invalid state, or violates any non-variable, pre-condition, or post-condition of the class.
In addition, a class should be thread-safe. When accessed by multiple threads, no matter what time sequence arrangement or staggered the running environment executes these threads, it must still have the correct behavior as described above, and there is no additional synchronization in the called code. The effect is that, in the view of all threads, operations on thread-safe objects occur in a fixed and globally consistent order.
The relationship between correctness and thread security is very similar to the relationship between consistency and independence used to describe ACID (atomicity, consistency, independence, and durability) Transactions: from the perspective of a specific thread, object operations executed by different threads are sequential (although in an indefinite order) rather than parallel operations.

Thread security is not a true or false proposition. The Vector method is synchronous, and the Vector is clearly designed to work in a multi-threaded environment. However, its thread security is limited, that is, there is a State dependency between some methods (Similarly, if the Vector is modified by other threads during iteration, it is determined by the Vector. the iterator returned by iterator () will throw ConcurrentModifiicationException ).
No classification system is widely accepted for common thread security levels in Java classes. However, it is important to record their thread security behaviors when writing classes.
Bloch provides a classification method for describing five types of thread security: immutable, thread security, conditional thread security, thread compatibility, and thread opposition. As long as you clearly record the thread security features, it does not matter whether you use this system. This system has its limitations-the boundaries between various categories are not exactly clear, and in some cases it is not taken care of-but this system is a good starting point. The core of this classification system is whether the caller can or must be surrounded by external synchronization operations (...... The Rest Of The full text>

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.