In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "case analysis of security policy in Java thread". In daily operation, I believe that many people have doubts about the case analysis of security policy in Java thread. The editor has 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 of "case analysis of security policy in Java thread". Next, please follow the editor to study!
Immutable objects
Conditions to be satisfied for immutable objects
(1) the state of an object cannot be modified after it is created
(2) all fields of the object are of final type.
(3) the object is created correctly (the this reference does not overflow during object creation)
For immutable objects, see the String class in JDK
Final keywords: classes, methods, variables
(1) modifier class: this class cannot be inherited. String classes and wrapper classes of basic types (such as Integer, Long, etc.) are all final types. Member variables in the final class can be set to the final type as needed, but all member methods in the final class are implicitly specified as final methods.
(2) Modification methods: locking methods are not modified by inherited classes; efficiency. Note: the private method of a class is implicitly specified as the final method
(3) modifier variables: basic data type variables (values cannot be modified after initialization), reference type variables (after initialization, you can no longer point to other objects)
A Collections class is provided in JDK, which provides a number of methods that start with unmodifiable, as follows:
Collections.unmodifiableXXX: Collection, List, Set, Map...
The XXX in the Collections.unmodifiableXXX method can be Collection, List, Set, Map.
At this point, passing the Collection, List, Set, Map that we created into the Collections.unmodifiableXXX method becomes immutable. At this point, if you modify the elements in Collection, List, Set, and Map, a java.lang.UnsupportedOperationException exception will be thrown.
In Google's Guava, there are many classes that start with Immutable, as follows:
ImmutableXXX,XXX can be Collection, List, Set, Map...
Note: to use Google's Guava, you need to add the following dependency package to Maven:
Com.google.guava guava 23.0 II. Thread closure
(1) Ad-hoc thread closure: program control implementation, at worst, ignore
(2) Stack closure: local variables, no concurrency problem
(3) ThreadLocal thread closure: a good way to close.
Thread unsafe class and writing method
1. StringBuilder-> StringBuffer
StringBuilder: thread is not safe
StringBuffer: thread is not safe
When string concatenation involves multithreading, use StringBuffer to implement
In a specific method, a string concatenation object is defined, which can be implemented using StringBuilder. Because when a local variable is defined inside a method for use, it is stack-closed, and only one thread will use the variable, which does not involve multithreading operations on the variable, just use StringBuilder.
2. SimpleDateFormat-> JodaTime
SimpleDateFormat: thread is not safe. Instantiation of its objects can be put into specific time formatting methods to achieve thread safety.
JodaTime: thread safety
Examples of SimpleDateFormat thread-unsafe code are as follows:
Package io.binghe.concurrency.example.commonunsafe;import lombok.extern.slf4j.Slf4j;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;@Slf4jpublic class DateFormatExample {private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyyMMdd"); / / Total number of requests public static int clientTotal = 5000; / / number of threads executing concurrently public static int threadTotal = 200 Public static void main (String [] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool (); final Semaphore semaphore = new Semaphore (threadTotal); final CountDownLatch countDownLatch = new CountDownLatch (clientTotal); for (int I = 0; I
< clientTotal; i++){ executorService.execute(() ->{try {semaphore.acquire (); update (); semaphore.release ();} catch (Exception e) {log.error ("exception", e);} countDownLatch.countDown ();}) } countDownLatch.await (); executorService.shutdown ();} public static void update () {try {simpleDateFormat.parse ("20191024");} catch (ParseException e) {log.error ("parse exception", e);}
Just change it to the following code.
The total number of package io.binghe.concurrency.example.commonunsafe;import lombok.extern.slf4j.Slf4j;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;@Slf4jpublic class DateFormatExample2 {/ / requests public static int clientTotal = 5000; / / the number of threads executing concurrently public static int threadTotal = 200 Public static void main (String [] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool (); final Semaphore semaphore = new Semaphore (threadTotal); final CountDownLatch countDownLatch = new CountDownLatch (clientTotal); for (int I = 0; I
< clientTotal; i++){ executorService.execute(() ->{try {semaphore.acquire (); update (); semaphore.release ();} catch (Exception e) {log.error ("exception", e);} countDownLatch.countDown ();}) } countDownLatch.await (); executorService.shutdown ();} public static void update () {try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyyMMdd"); simpleDateFormat.parse ("20191024");} catch (ParseException e) {log.error ("parse exception", e);}
For JodaTime, you need to add the following dependency package to Maven:
Joda-time joda-time 2.9
The sample code is as follows:
Total number of package io.binghe.concurrency.example.commonunsafe;import lombok.extern.slf4j.Slf4j;import org.joda.time.DateTime;import org.joda.time.format.DateTimeFormat;import org.joda.time.format.DateTimeFormatter;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;@Slf4jpublic class DateFormatExample3 {/ / requests public static int clientTotal = 5000 / / number of threads executing concurrently public static int threadTotal = 200; private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern ("yyyyMMdd"); public static void main (String [] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool (); final Semaphore semaphore = new Semaphore (threadTotal); 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 (Exception e) {log.error ("exception", e);} countDownLatch.countDown ();}) } countDownLatch.await (); executorService.shutdown ();} public static void update (int I) {log.info ("{}-{}", I, DateTime.parse ("20191024", dateTimeFormatter);}}
3. ArrayList, HashSet, HashMap and other Collections collection classes are thread-unsafe classes.
4. Check before executing: if (condition (a)) {handle (a);}
Note: this way of writing is not thread-safe!
Two threads perform this operation at the same time, and the if condition is judged at the same time, and the variable an is shared by the thread. If both threads meet the if condition, both threads will execute the handle (a) statement at the same time, so the handle (a) statement may not be thread-safe.
The unsafe point lies in the two operations, even if the previous execution process is thread-safe, the latter process is thread-safe, but the gap between the front and back execution process is not atomic, therefore, it will also cause thread unsafe problems.
In the actual process, when you encounter the processing of the if (condition (a)) {handle (a);} class, consider whether an is shared by threads. If it is shared by threads, you need to lock the entire execution method, or make sure that the two operations before and after if (condition (a)) {handle (a);} (if judgment and code execution) are atomic.
4. Thread safety-synchronization container 1. ArrayList-> Vector, Stack
ArrayList: thread is not safe
Vector: synchronous operations, but thread unsafe situations may occur. Examples of thread-unsafe code are as follows:
Public class VectorExample {private static Vector vector = new Vector (); public static void main (String [] args) throws InterruptedException {while (true) {for (int I = 0; I)
< 10; i++){ vector.add(i); } Thread thread1 = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < vector.size(); i++){ vector.remove(i); } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < vector.size(); i++){ vector.get(i); } } }); thread1.start(); thread2.start(); } }} Stack:继承自Vector,先进后出。 2. HashMap ->HashTable (neither Key nor Value can be null)
HashMap: thread is not safe
HashTable: thread safe. Note that Key and Value cannot be null when using HashTable.
3. Collections.synchronizedXXX (List, Set, Map)
Note: do not update the collection when traversing the collection. When you need to delete the elements in the collection, you can traverse the collection, mark the elements that need to be deleted first, and then delete the elements after the traversal of the collection. For example, the following sample code:
Public class VectorExample3 {/ / this method throws: java.util.ConcurrentModificationException private static void test1 (Vector v1) {for (Integer I: v1) {if (I = = 3) {v1.remove (I);} / / this method throws: java.util.ConcurrentModificationException private static void test2 (Vector v1) {Iterator iterator = v1.iterator () While (iterator.hasNext ()) {Integer I = iterator.next (); if (I = = 3) {v1.remove (I);} / / normal private static void test3 (Vector v1) {for (int I = 0; I)
< v1.size(); i++){ if(i == 3){ v1.remove(i); } } } public static void main(String[] args) throws InterruptedException { Vector vector = new Vector(); vector.add(1); vector.add(2); vector.add(3); //test1(vector); //test2(vector); test3(vector); }}五、线程安全-并发容器J.U.C J.U.C表示的是java.util.concurrent报名的缩写。 1. ArrayList ->CopyOnWriteArrayList
ArrayList: thread is not safe
CopyOnWriteArrayList: thread safety
Copy during the write operation, when a new element is added to the CopyOnWriteArrayList array, copy a copy from the original array, then write in the new array, and then point the original array to the new array. The whole operation is carried out under the protection of the lock.
Disadvantages of CopyOnWriteArrayList:
(1) A copy is required for each write operation, which consumes memory. If there are too many elements, it may lead to GC.
(2) scenarios that cannot be used for real-time reading are suitable for scenarios with more reading and less writing.
CopyOnWriteArrayList design ideas:
(1) Separation of reading and writing
(2) final consistency
(3) to open up another space when using it to solve concurrency conflicts.
Note: CopyOnWriteArrayList read operations are carried out on the original array, do not need to lock, write operation to copy, when there are new elements added to the CopyOnWriteArrayList array, copy a copy from the original set, and then write in the new array, and then point the original array to the new array after writing. The whole operation is carried out under the protection of the lock.
2.HashSet, TreeSet-> CopyOnWriteArraySet, ConcurrentSkipListSet
CopyOnWriteArraySet: thread-safe, the underlying implementation uses CopyOnWriteArrayList.
A new class added by ConcurrentSkipListSet:JDK6, which supports sorting. You can customize the comparator at construction time, based on the Map collection. In a multithreaded environment, the contains () method, add (), remove (), retain () and other operations in ConcurrentSkipListSet are thread-safe. However, batch operations, such as containsAll (), addAll (), removeAll (), retainAll (), etc., do not guarantee that the whole operation is atomic, but can only guarantee that each operation in the batch operation is atomic, because the batch operation is a single-step operation called in the form of a loop, such as calling the remove () operation in a circular way under the removeAll () operation. The following code is shown:
/ / Source code of removeAll () method in ConcurrentSkipListSet type public boolean removeAll (Collection c) {/ / Override AbstractSet version to avoid unnecessary call to size () boolean modified = false; for (Object e: C) if (remove (e)) modified = true; return modified;}
Therefore, when performing batch operations in ConcurrentSkipListSet, you need to consider the locking problem.
Note: the ConcurrentSkipListSet class does not allow the use of empty elements (null).
3. HashMap, TreeMap-> ConcurrentHashMap, ConcurrentSkipListMap
ConcurrentHashMap: thread safe, null values are not allowed
ConcurrentSkipListMap: thread-safe version of TreeMap, internally implemented using SkipList jump table structure
4.ConcurrentSkipListMap and ConcurrentHashMap are compared as follows
(1) the Key in ConcurrentSkipListMap is ordered and the Key in ConcurrentHashMap is disordered.
(2) ConcurrentSkipListMap supports higher concurrency, and the access time of data has almost nothing to do with the number of threads, that is to say, in the case of a certain amount of data, the more concurrent threads, the more ConcurrentSkipListMap can reflect its advantages.
Note: try to use TreeMap in non-parallel threads, in addition, for parallel programs with relatively low concurrency, you can use Collections.synchronizedSortedMap to wrap TreeMap; for high concurrency programs, use ConcurrentSkipListMap to provide a higher degree of concurrency; in a multi-threaded environment with high concurrency, you need to sort the key-value pairs of Map and use ConcurrentSkipListMap as much as possible.
At this point, the study on "instance analysis of security policy in Java threads" is over. I hope to be able to solve your 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.
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.