Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Java synchronization container and concurrency container

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is Java synchronization container and concurrency container". In daily operation, I believe many people have doubts about what Java synchronization container and concurrency container are. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is Java synchronization container and concurrency container". Next, please follow the editor to study!

Synchronization container

In Java, there are two main types of synchronization containers:

Classes created by static factory methods provided in Vector, Stack, HashTableCollections classes (by Collections.synchronizedXxxx, etc.) classes created by static factory methods provided in Collections class

Vector implements the List interface, and Vector is actually an array, similar to ArrayList, but the methods in Vector are synchronized methods, that is, synchronization measures are taken.

Stack is also a synchronization container, and its methods are also synchronized with synchronized, which actually inherits from the Vector class.

HashTable implements the Map interface, which is similar to HashMap, but HashTable is synchronized, while HashMap does not.

Defects of the synchronization container

The synchronization principle of the synchronization container is to decorate the method with synchronized. Then, these methods only allow one thread call at a time to execute.

Performance problem

Because of the method modified by synchronized, only one thread is allowed to execute at a time, and other threads trying to access the method can only wait. Obviously, this approach performs worse than containers that do not use synchronized.

Safety problem

Is the synchronization container really safe?

The answer is: not necessarily. The synchronization container may not be really secure. When doing composite operations, locks are still needed to protect them.

Common composite operations are as follows:

Iteration: repeatedly visit elements until all elements are traversed; jump: find the next (next n) elements of the current element according to the specified order; conditional operation: for example, add if not, etc.

Unsafe exampl

Public class Test {static Vector vector = new Vector (); public static void main (String [] args) throws InterruptedException {while (true) {for (int iOperation Thread starts execution); for (Integer key: map.keySet ()) {System.out.println (key + "-" + map.get (key);}}); wthread.start (); rthread.start (); Thread.sleep (1000);}}

CopyOnWriteArrayList

Keystone

Function: CopyOnWrite literally means copy on write. CopyOnWriteArrayList is a thread-safe ArrayList.

Principle:

In CopyOnWriteAarrayList, reads are out of sync because they work on snapshots of internal arrays, so multiple iterators can traverse at the same time without blocking each other. All writes are synchronized. They work on copies of the backup array (3). When the write operation is complete, the backup array is replaced with the replicated array and the lock is released. Supporting arrays becomes volatile, so the call to replace arrays is atomic (5). The iterator created after the write operation will be able to see the modified structure (6. 7). Iterators returned by copying the collection while writing do not throw ConcurrentModificationException because they work on snapshots of the array and will return elements exactly as they did when the iterator was created, regardless of subsequent modifications (2Power4).

Source code

Important attribute

Lock-to perform a write-time copy operation, you need to use a reentrant lock to lock array-an array of objects to store elements

/ * * The lock protecting all mutators * / final transient ReentrantLock lock = new ReentrantLock (); / * The array, accessed only via getArray/setArray. * / private transient volatile Object [] array

Important method

Add operation

The logic to add is simple: copy the original container, then write to the new copy, and then switch references. Of course, this process needs to be locked.

Public Boolean add (E e) {/ / ReentrantLock is locked to ensure thread safety final ReentrantLock lock = this.lock;lock.lock (); try {Object [] elements = getArray (); int len = elements.length;// copy the original container with the length of the original container plus an Object [] newElements = Arrays.copyOf (elements, len + 1); / / add operation newElementslen [] = ePlacement / point the original container reference to the new copy setArray (newElements); } finally {/ / unlock lock.unlock ();}}

Delete operation

In the same way to delete, copy elements other than those you want to delete to the new copy, and then switch references to point the original container reference to the new copy. It is also a write operation and needs to be locked.

Public E remove (int index) {/ / Lock final ReentrantLock lock = this.lock;lock.lock (); try {Object [] elements = getArray (); int len = elements.length;E oldValue = get (elements, index); int numMoved = len- index-1 if (numMoved = = 0) / / if you want to delete the data at the end of the list, copy the first len-1 data to the new copy, and then switch references setArray (Arrays.copyOf (elements, len-1)) Else {/ / otherwise, copy the elements other than those to be deleted into the new copy and switch references Object [] newElements = new Object [len-1]; System.arraycopy (elements, 0, newElements, 0, index); System.arraycopy (elements, index + 1, newElements, index,numMoved); setArray (newElements);} return oldValue;} finally {/ / unlock lock.unlock ();}}

Read operation

The read operation of CopyOnWriteArrayList is unlocked and has high performance.

Public E get (int index) {return get (getArray (), index);} private E get (Object [] a, int index) {return (E) a [index];}

Example

Public class CopyOnWriteArrayListDemo {static class ReadTask implements Runnable {List list;ReadTask (List list) {this.list = list;} public void run () {for (String str: list) {System.out.println (str);} static class WriteTask implements Runnable {List list;int index;WriteTask (List list, int index) {this.list = list;this.index = index;} public void run () {list.remove (index); list.add (index, "write_" + index) }} public void run () {final int NUM = 10 ArrayList / ArrayList throws a ConcurrentModificationException exception / / List list = new ArrayList (); CopyOnWriteArrayList list = new CopyOnWriteArrayList (); for (int I = 0; I < NUM; I +) {list.add ("main_" + I);} ExecutorService executorService = Executors.newFixedThreadPool (NUM); for (int I = 0; I < NUM; I +) {executorService.execute (new ReadTask (list)); executorService.execute (new WriteTask (list, I)) } executorService.shutdown ();} public static void main (String [] args) {new CopyOnWriteArrayListDemo () .run ();}}

At this point, the study on "what is the Java synchronization container and concurrency container" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report