In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what the java high concurrency synchronization container refers to. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
There are two main types of synchronization containers in java:
ArrayList-> Vector,Stack; HashMap-> HashTable (key,value cannot be null)
Collections.synchronizedXXX (List, Set, Map)
Vector
Vector implements the List interface, which is actually an array. Very similar to ArrayList. But all the methods in Vector are decorated with synchronized methods and are synchronized. Therefore, when using ArrayList objects in a multithreaded environment, thread-safe (rather than fully thread-safe) is better if it is shared by multiple threads and can be replaced with synchronous Vector.
@ Slf4j@ThreadSafepublic class VectorExample1 {/ / Total number of requests public static int clientTotal = 5000; / / number of threads executing concurrently public static int threadTotal = 200; private static List list = new Vector (); public static void main (String [] args) throws InterruptedException {/ / thread pool ExecutorService executorService = Executors.newCachedThreadPool (); / / define semaphore final Semaphore semaphore = new Semaphore (threadTotal) / / define counter final CountDownLatch countDownLatch = new CountDownLatch (clientTotal); for (int I = 0; I
< clientTotal; i++) { final int count = i; executorService.execute(() ->{try {semaphore.acquire (); update (count); semaphore.release ();} catch (InterruptedException e) {log.error ("exception", e);} countDownLatch.countDown ();}) } countDownLatch.await (); executorService.shutdown (); log.info ("size: {}", list.size ());} public static void update (int I) {list.add (I);}}
The result of this output is the expected result.
Why is the synchronization container not thread-safe? @ NotThreadSafepublic class VectorExample2 {private static Vector vector = new Vector (); public static void main (String [] args) {while (true) {for (int I = 0 int I < 10 X I +) {vector.add (I) } Thread thread1 = new Thread () {@ Override public void run () {for (int I = 0polii < vector.size (); iTunes +) {vector.remove (I);} Thread thread2 = new Thread () {@ Override public void run () {for (int I = 0politic I < vector.size (); iTunes +) {vector.get (I);}; thread1.start () Thread2.start ();}
Run, throw an exception:
Exception in thread "Thread-611" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 5 at java.util.Vector.get (Vector.java:748) at com.vincent.example.syncContainer.VectorExample2 $2.run (VectorExample2.java:25) Exception in thread "Thread-1759" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 21 at java.util.Vector.get (Vector.java:748) at com.vincent.example.syncContainer.VectorExample2 $2.run (VectorExample2.java:25)
Reason: get out of bounds must be caused by the remove method, although vector can guarantee that only one thread can access him at a time, but it does not rule out this possibility: when a thread executes to int I = 0 vector.size () at a certain time, vector.size () returns 10 vector.size 9; while another thread happens to remove iTunes 9's vector, then the get method wants to call iThreads 9 elements will have an array out of bounds exception.
This example demonstrates that the two synchronization methods of two synchronization containers may trigger thread unsafety problems in different threads because of the difference in operation order. Therefore, in order to ensure thread safety, some additional synchronization measures must be taken on the method calling side. It is not thread-safe in all situations when using synchronization containers.
Stack
The methods in Stack are also decorated with synchronized. In fact, the Stack class inherits the Vector class.
HashTable
HashTable implements the Map interface, which is similar to HashMap, but HashTable is synchronized, and the method is decorated with synchronized. However, when using HashTable, it is important to note that key and value cannot be null.
Collections
The new ArrayList, HashSet and HashMap objects will be generated by Collections:
Private static List list = Collections.synchronizedList (new ArrayList ()); private static Set set = Collections.synchronizedSet (new HashSet ()); private static Map map = Collections.synchronizedMap (new HashMap ()); delete operation public class VectorExample3 {/ / Exception in thread "main" java.util.ConcurrentModificationException private static void test1 (Vector v1) {/ / foreach for (Integer I: v1) {if (i.equals (3)) {v1.remove (I) during collection traversal }} / / Exception in thread "main" java.util.ConcurrentModificationException private static void test2 (Vector v1) {/ / iterator Iterator integerIterator = v1.iterator (); while (integerIterator.hasNext ()) {Integer I = integerIterator.next (); if (i.equals (3)) {v1.remove (I) } / / success private static void test3 (Vector v1) {for (int I = 0; I < v1.size ()) {if (v1.equals (3)) {v1.remove (I);} public static void main (String [] args) {Vector vector = new Vector () Vector.add (1); vector.add (2); vector.add (3); test1 (vector);}}
If you use Foreach or iterator to loop our collection, try not to delete the collection in the loop. If you want to do the remove operation, it is recommended to find the value that needs to be deleted during the traversal and then make a tag, and perform the corresponding remove operation after the traversal ends. Exceptions are more likely to occur in the case of multithreading.
So much for sharing what the java high concurrency synchronization container refers to. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.