How to ensure the security of a collection in multi-threading

Source: Internet
Author: User

Threads and Processes

the concept of process. A narrow process is an instance of a running program; a generalized process is a program with a certain independent function. A running activity of a data set is a basic unit for the dynamic execution of the operating system.

thread, sometimes called a lightweight process (LWP), is the smallest unit of program execution flow; A standard thread consists of a thread ID, a current instruction pointer (PC), a collection of registers, and a stack .

Typically, a process consists of one or more threads, and each thread shares the program's memory space and some process-level resources.

In most software applications, the number of threads is more than one, multi-threaded programs in a volatile environment, accessible global variables and heap data can be changed at any time by other threads, which put the " Thread safety " issue on the agenda. So, How do you ensure thread safety?

ways to ensure thread safety

Generally speaking, there are several ways to ensure thread safety based on the Linux operating system: Competition and atomic manipulation, synchronization and locking, reentrant, over-optimization .

Competition and atomic manipulation
Multiple threads accessing and modifying one data at the same time can have serious consequences. The reason for the serious consequences is that many operations are compiled by the operating system into more than one instruction after the assembly code, so it is possible to execute half of the time when execution is interrupted by the dispatch system to execute other code. The operation of a single instruction is generally referred to as an atomic (Atomic) because, in any case, the execution of individual instructions is not interrupted.

Therefore, in order to avoid the occurrence of multithreading data anomalies, the Linux system provides some common operation of atomic instructions, to ensure the security of the thread. However, they are only suitable for relatively simple occasions, and in complex situations it is necessary to choose other methods.

Sync and lock
To avoid the unpredictable consequences of multiple threads reading and writing data at the same time, the developer synchronizes access to the same data for each thread, that is, the other thread must not access the same data at the end of a thread's access data.

The most common method of synchronization is to use lock , which is a non-mandatory mechanism where each thread attempts to acquire a lock before accessing the data or resource, and releases the lock after the end of the access, and when the lock is already occupied, the thread waits for the lock to be acquired. Until the lock is re-usable.

Binary semaphore is the simplest kind of lock, it has only two states: Occupy and non-occupied, it is suitable for only a single thread exclusive access to resources. For resources that allow concurrent access by multiple threads, use a multivariate semaphore (called semaphore).

can be re-entered
A function is re-entered to indicate that the function has not been completed, but because of external factors or internal factors, the function executes again. A function, called reentrant, indicates that the function is re-entered without any adverse consequences. Re-entry is a powerful guarantee of concurrency security, and a reentrant function can be used with confidence in multithreaded environments.

Over-optimization
In many cases, even if we reasonably use locks, it is not guaranteed to be thread-safe, so we may be overly optimized for code to ensure thread safety.

We can use the volatile keyword to try to block over-optimization, and it can do two things: first, prevent the compiler from caching a variable to register instead of writing it back in order to increase speed, and second, prevent the compiler from adjusting the order of instructions that manipulate the volatile variable.

In another case, the CPU's disorderly execution makes multithreading security difficult, and the usual solution is to invoke a CPU-supplied instruction called barrier, which prevents the CPU from swapping instructions before the instruction to barrier, and vice versa.

problems with modifying collection data in a loop

Look at the code:

Arrays. aslist ();    for (int  i:aslist) {  aslist.  Add(3);  System.err.println (i);}

We execute this code to throw this exception java.lang.UnsupportedOperationException , which tells us that it is not supported to modify the current collection (add or remove elements) in the iteration;

Why is that? So should we avoid this problem?

1, foreach in the loop is not supported to delete or add to the elements in the collection.

2, the use Arrays.asList of the resulting collection does not support changes in the loop , the use new ArrayList is possible , but we should not use this notation, because the addition of elements will cause the length of the collection to change, which is very easy to cause BUG, and not easy to troubleshoot.

3. If you do need to remove elements from the loop, consider using an Iterator iterator .

But if we were in aA shared collection is used in a multi-threaded program; wehow can I guarantee other lines and not change the elements in the collection? can useCollections.synchronizedListGets a thread-safe collection that, in order to ensure the security of the thread in the Loop collection, must add lock control to the collection of loops or iterations that are required on the outer layer of the loop;gets access control for the lock held by the current collection;Code:
Final Static ListAslist =Collections.synchronizedlist (NewArrayList (Arrays.aslist ("A", "B"))); Public Static voidMain (string[] args) {NewThread (New Runnable () {@Override Public void Run() {Try{
Thread.Sleep (150);
}
Catch(
Interruptedexception e) {} reload(); }}). Start ();
synchronized(aslist) { for(String e:aslist) {Try{thread.sleep (100);}
Catch(Interruptedexception E1) {} System.out.println (e); } }} Public Static void Reload() {aslist.clear (); Aslist.addall (Arrays.aslist ("A", "B", "C"));}

Note: If you do not use Collections.synchronizedList a collection that gets a thread-safe, you must synchronize the lock for the collection before you modify the collection, or you can use the java.util.concurrent associated thread-safe collection class under the package.

How to ensure the security of a collection in multi-threading

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.