当前位置:网站首页>Concurrent programming ----------- set
Concurrent programming ----------- set
2022-07-24 13:56:00 【Book King, middle King】
1. Multithreaded List
- Mode one : Use thread safe Vector class .
- Mode two : adopt Collections.synchronizedList(List<T> list) hold List Combine classes converted to thread safe .
- Mode three : Use CopyOnWriteArrayList
difference : The first two methods are through synchronized The synchronization of , This method is a coarse-grained lock , You need to obtain locks when reading and writing , Efficiency is very low . Mode 3 passed cow Copy on write strategy . When reading, it will not be locked . when written , First of all get lock lock , Then create a copy of the original container , Write by operating on the copy , The original container can still be read , After the copy is written , By changing list References to , Change the reference from the original container to a copy .
Advantages and disadvantages of mode 3 :
advantage : Efficient , There will be no ConcurrentModificationException abnormal .
shortcoming :
1. Memory consumption is too high , You need to create a copy every time you write , Too much data will cause problems
2. Copy on write policy , At the expense of real-time data , Ensure the final consistency of data .
2. Multithreaded set
- Mode one :Collections.synchronizedSet(Set<T> s) hold set Combine conversion to thread safe .
- Mode two :CopyOnWriteArraySet
3. Multithreaded Map
- Mode one : Use Vector perhaps HashTable
- Mode two : Use ConcurrentHashMap
A hash table that supports full concurrency of retrieval and high expected concurrency of updates . This class follows the same functional specification, such as
Hashtable, And includes a method version corresponding to each methodHashtable. however , Although all operations are thread-safe , Retrieval operation Does not It means locking , and No, To prevent any support for locking the entire table in all access ways . This class can be used with... In programs that rely on thread safetyHashtableCompletely mutualHashtable, But it doesn't depend on its synchronization details .Retrieval operation ( Include
get) Usually don't stop , Therefore, it may overlap with the update operation ( Includeputandremove). The search reflects the recent Accomplished The result of the update operation . ( More formally , For the update operation of a given key It happened before With any ( Non empty relation ) Retrieve this key to report the updated value .) For aggregation operations , such asputAllandclear, Concurrent retrieval may reflect the insertion or removal of only a few entries . Similarly , iterator , Splitters and enumerations are returned in the reflection iterator / Enumerate the elements that reflect the state of the hash table during or after creation . they No Throw outConcurrentModificationException. However , Iterators are designed to be used by only one thread at a time . please remember , Results of the aggregate state method , Includesize,isEmptyandcontainsValueIt's usually useful , Only when a map is not updated concurrently in other threads . otherwise , The results of these methods reflect transient states that may be sufficient for monitoring or estimation purposes , But it is not applicable to program control .When there are too many conflicts ( namely , Keys that have different hash codes but fall into the same time slot based on the size of the table ) when , The table is dynamically extended , And each mapping keeps roughly two bin Expected average effect of ( Corresponding to 0.75 Load factor threshold sizing ). Because mappings are added and deleted , This average can vary greatly , But overall , This preserves a generally accepted time for hash tables / Space trade-offs . However , Adjusting this or any other type of hash table can be a relatively slow operation . If possible , It is best to provide a size estimate as an optional
initialCapacityconstructors parameters . Additional optionalloadFactorConstructor parameters provide another means , Customize the initial table capacity by specifying the table density used when calculating the amount of space to be allocated for a given number of elements . Besides , For compatibility with previous versions of this class , Constructors can optionally specify the expectedconcurrencyLevelAs an additional hint for internal resizing . Please note that , Use exactly the same number of keyshashCode()Is to lower any hash tablehashCode()A reliable method of . To improve the impact , When the key isComparablewhen , This class can use the comparison order between keys to help break the relationship .nail
SetProject a ConcurrentHashMap Sure ( Use the creatednewKeySet()ornewKeySet(int)), Or observation ( UsekeySet(Object)Only keys are of interest , And the mapped value is ( May be instantaneous ) Do not use or take all the same mapping values .ConcurrentHashMap By using
LongAdderValue and passcomputeIfAbsentTo initialize , Use it as a scalable frequency mapping ( Histogram or multi set form ). for example , Want toConcurrentHashMap<String,LongAdder> freqsAdd count , have access tofreqs.computeIfAbsent(k -> new LongAdder()).increment();This class and its views and iterators implement all of the Optional Method
MapindividualIteratorInterface .image
HashtableBut not likeHashMap, This class Don't allownullUse as key or value .ConcurrentHashMaps Support a set of sequential and parallel batch operations , With most
StreamThe method is different , They are designed to be safe and often used wisely , Even if the mapping is updated by other threads at the same time ; for example , When calculating the snapshot summary of values in the shared registry . There are three operations , Each has four forms , Accept key , value , Items and ( key , value ) Parameters and / Or a function that returns a value . because ConcurrentHashMap The elements of are not sorted in any particular way , And it may be processed in different order in different parallel execution , Therefore, the correctness of the provided function should not depend on any sort , Nor should it rely on any other object or value that may change instantaneously... The calculation is in progress ; Except for every action , Ideally, there are no side effects . YesMap.EntryMethod... Is not supported for batch operation of objectsetValue.
- forEach: Perform the given operation on each element . The variable form applies the given transformation to each element before performing the operation .
- search: Returns the first available non null result of applying the given function on each element ; Skip further searches when results are found .
- reduce: Accumulate each element . The reduction provided cannot depend on sorting ( More formally , It should be association and exchange ). There are five variants :
- The plains have decreased ( Because there is no corresponding return type , therefore (key,value) Function arguments do not take the form of this method )
- The reduction in mapping accumulates the results of a given function applied to each element .
- Reduce to scalar double using the given base value , Long and int.
Accept these operations in batch
parallelismThresholdParameters . If the estimated current map size is less than a given threshold , Then the methods are carried out in turn . UseLong.MAX_VALUEValueLong.MAX_VALUESuppress all parallelism . Use1The value of can be fully utilized for all parallel computing by dividing into enough subtasksForkJoinPool.commonPool()To achieve maximum parallelism . Usually , You will initially choose one of the extremes , Then measure the performance between using intermediate values , Thus reducing the relationship between overhead and throughput .The concurrency attribute of batch operation follows ConcurrentHashMap Concurrency properties of : from
get(key)Any non null result returned and the associated access method have a pre occurrence relationship with the associated insert or update . The results of any batch operation reflect the composition of each element relationship ( But unless it is known in some way to be static , They are not necessarily atoms relative to the entire map ). contrary , Because the keys and values in the map are never empty , therefore null As a reliable atomic indicator of the current lack of any results . To keep this property ,null Used as an implicit basis for all non scalar reduction operations . about double,long and int edition , The basis should be to return other values when combined with any other value ( More formally , It should be a reduced identification element ). Most common reductions have these properties ; for example , Use cardinality 0 Or minimum value and reference value MAX_VALUE The calculation and .The search and transformation functions provided as arguments should similarly return null To indicate the absence of any results ( Not used in this case ). In the case of mapping reduction , This also allows the transformation to be used as a filter , If you shouldn't combine elements , return null( Or in the case of original specialization , Identity Foundation ). Before using them for search or reduction operations , You can use the “null It means there's nothing right now ” Build composite transformation and filtering under rules .
Acceptance and / Or return Entry Parameter methods maintain key value associations . for example , When you find the most valuable key , They may be useful . Please note that , have access to
new AbstractMap.SimpleEntry(k,v)Provide “plain”Entrynew AbstractMap.SimpleEntry(k,v).Batch operations can suddenly complete , Throw an exception encountered in the application . When dealing with such exceptions , Please note that , Other functions executed concurrently may also throw exceptions , Or if the first exception does not occur , Will do this .
Compared with the sequential form , Acceleration ratio is common , But there is no guarantee . If the basic work of parallel computing is more expensive than computing itself , Parallel operations involving short functions on a small map may be slower than sequential forms . Similarly , If all processors are busy performing unrelated tasks , Parallelization may not lead to too much actual parallelism .
4. Multithreaded queue
4.1 queue Inheritance graph

4.2 BlockingQueue Method introduction
| operation | This method will throw an exception | Does not throw an exception | Block waiting , Death etc. | Overtime waiting |
| add to | add() Insert successful return true,true Return after success IllegalStateException If no space is currently available | offer() If the insertion is successful, return true, Otherwise return to false | put() Inserts the specified element into this queue , Wait for spaces to become available . | offer(E e,long timeout, TimeUnit unit) |
| Delete | remove() If the deletion is successful, it will return true, Otherwise, throw an exception . | poll() Delete successful return true, Otherwise return to false | take() Retrieve and delete the headers of this queue , If necessary, , Wait for the element to be available . | poll(long timeout, TimeUnit unit) |
| Judge header element | element | peek |
边栏推荐
- Wildcard (Pan domain name) SSL certificate
- 网络安全——文件上传白名单绕过
- Flink容错机制(五)
- 第六章 总线
- Solve the problem of repeated clicking of button uibutton
- JS execution mechanism
- Why are there "two abstract methods" in the functional interface comparator?
- Network security - file upload competitive conditions bypass
- The latest and complete Flink series tutorials in 2021_ Preliminary exploration of Flink principle and flow batch integration API (II. V) V2
- uni-app 背景音频 熄屏或者退回桌面之后不在播放
猜你喜欢

Game thinking 04 summary: a summary of frame, state and physical synchronization (it was too long before, and now it's brief)

【无标题】rhcsa第一次作业
![[untitled] rhcsa first operation](/img/ba/6b9c11edbc18ffb52f6046360b5b10.png)
[untitled] rhcsa first operation

Network security - file upload penetration test

Hcip day 13

网络安全——文件上传竞争条件绕过

天然气潮流计算matlab程序

2021-07-09

Chapter VI bus

Network security - use exchange SSRF vulnerabilities in combination with NTLM trunking for penetration testing
随机推荐
Nessus安全测试工具使用教程
Flink comprehensive case (IX)
Network security -- Service Vulnerability scanning and utilization
Solve the problem that the ARR containsobject method returns no every time
The R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graphs, uses the by parameter to specify the groupi
uni-app 背景音频 熄屏或者退回桌面之后不在播放
Chapter VI bus
Wildcard (Pan domain name) SSL certificate
Game thinking 04 summary: a summary of frame, state and physical synchronization (it was too long before, and now it's brief)
OWASP ZAP安全测试工具使用教程(高级)
数据湖系列文章
微信小程序 TODO案例
R语言使用epiDisplay包的summ函数计算dataframe中指定变量在不同分组变量下的描述性统计汇总信息并可视化有序点图、自定义cex.main参数配置标题文本字体的大小
Data formatting widget
Flink综合案例(九)
JS get object attribute value
Csp2021 T1 corridor bridge distribution
R语言ggpubr包的ggarrange函数将多幅图像组合起来、annotate_figure为组合图像添加注释、注解、标注信息、使用left参数在可视化图像左侧添加注解信息(字体颜色、旋转角度等)
CSP2021 T3 回文
申请了SSL数字证书如何进行域名验证?