自我成长 - HashMap
type: channel
link: https://yanxizhu.com/index.php/tag/HashMap/
items: JAVA8-Stream源码
items: 线程安全-并发容器J.U.C
items: 线程安全-同步容器
items: 线程不安全的类与写法
items: 高并发中集合问题

JAVA8-Stream源码
type: item
date: 2022-09-06T15:03:00+00:00
description: Stream基本使用及特点Stream说明Stream操作分为：2组，//注意，流式管道操作，只能操作一次，否则报错。1、可连续操作： filter, map, and limit can be connected together to form a pipeline.2、操作中断collect causes the pipeline to be executed and closes it.使用范例：package com.example.study.java8.streams; import java.util.*; import java.util.stream.Stream; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; /** * Stream使用 * Stream操作分为：2组，//注意，流式管道操作，只能操作一次，否则报错 * You can see two groups of operations: * 1、可连续操作 *  filter, map, and limit can be connected together to form a pipeline. * 2、操作中断 *  collect causes the pipeline to be executed and closes it. */ public class SimpleStream { public static void main(String[] args) { List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT), new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER), new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH)); Stream<Dish> stream = menu.stream(); stream.forEach(System.out::println); //注意，流式管道操作，只能操作一次，否则报错 //stream has already been operated upon or closed // stream.forEach(System.out::println); System.out.println("===================================="); //原始调用 List<String> namesByCollections = getDishNamesByCollections(menu); namesByCollections.stream().forEach(System.out::println); System.out.println("===================================="); //lambda stream调用 List<String> lambdaStreamNames = lambdaStream(menu); lambdaStreamNames.stream().forEach(System.out::println); } //原始写法 public static List<String> getDishNamesByCollections(List<Dish> menu) { List<Dish> caloriesDis = new ArrayList<>(); for (Dish dish : menu) { if (dish.getCalories() < 400) { caloriesDis.add(dish); } } Collections.sort(caloriesDis, (dish1,…

线程安全-并发容器J.U.C
type: item
date: 2022-04-24T08:12:31+00:00
description: 线程安全-并发容器J.U.CArrayList -> CopyOnWriteArrayListHashSet、TreeSet -> CopyOnWriteArraySet 、ConcurrentSkipListSetHashMap、TreeMap -> ConcurrentHashMap 、ConcurrentSkipListMapCopyOnWriteArrayList适合读多写少的场景。读的时候再原数组读不需要加锁，写的时候会copy一份会单独加锁。代码示例：package com.yanxizhu.demo.concurrency.concurrent; import com.yanxizhu.demo.concurrency.annotation.ThreadSafety; import com.yanxizhu.demo.concurrency.annotation.UnThreadSafety; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; /** * @description: 线程安全容器：CopyOnWriteArrayList * @author: 清风 * @date: 2022/4/24 9:52 * @version: 1.0 */ @Slf4j @ThreadSafety public class DemoCopyOnWriteArrayList { // 请求总数 public static int clientTotal = 5000; // 同时并发执行的线程数 public static int threadTotal = 200; private static List<Integer> list = new CopyOnWriteArrayList<>(); 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(); log.info("size:{}", list.size()); } private static void update(int i) { list.add(i); } }输出结果：5000CopyOnWriteArraySet线程安全，代码示例package com.yanxizhu.demo.concurrency.concurrent; import com.yanxizhu.demo.concurrency.annotation.ThreadSafety; import lombok.extern.slf4j.Slf4j; import java.util.Set; import java.util.concurrent.*; /** * @description: 线程安全容器：CopyOnWriteArraySet * @author: 清风 * @date: 2022/4/24 9:52 * @version: 1.0 */ @Slf4j @ThreadSafety public class DemoCopyOnWriteArraySet { // 请求总数 public static int clientTotal = 5000; // 同时并发执行的线程数 public static int threadTotal = 200; pr…

线程安全-同步容器
type: item
date: 2022-04-24T04:21:00+00:00
description: 线程安全-同步容器主要包括ArrayList -> Vector，Stack HashMap->HashTable（key、value不能为null）Collections.synchronizedXXX（List、Set、Map）都是使用Synchronized进行修饰的，性能不是特别好。可以使用并发容器代替。注意：同步容器也可能是线程步安全的。同步容器线程步安全，代码示例：package com.yanxizhu.demo.concurrency.synContainer; import com.yanxizhu.demo.concurrency.annotation.UnThreadSafety; import java.util.Vector; /** * @description: 同步容器，也可能出现线程不安全情况 * @author: 清风 * @date: 2022/4/24 10:32 * @version: 1.0 */ @UnThreadSafety public class DemoVecotNo { private static final Vector<Integer> vector = new Vector<>(); public static void main(String[] args) { //一直循环 while(true) { //向vector容器放入值 for(int i=0; i <10; i++){ vector.add(i); } //线程1，向vector容器移除值 new Thread(()->{ for(int i=0; i <vector.size(); i++){ vector.remove(i); } }).start(); //线程2，向vector中获取值 new Thread(()->{ for(int i=0; i <vector.size(); i++){ vector.get(i); } }).start(); } } }输出结果：Exception in thread "Thread-478" Exception in thread "Thread-1724" Exception in thread "Thread-1918" Exception in thread "Thread-1769" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10 at java.base/java.util.Vector.remove(Vector.java:875) at com.yanxizhu.demo.concurrency.synContainer.DemoVecotNo.lambda$main$0(DemoVecotNo.java:27) at java.base/java.lang.Thread.run(Thread.java:834) java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 62 at java.base/java.util.Vector.remove(Vector.java:875) at com.yanxizhu.demo.concurrency.synContainer.DemoVecotNo.lambda$main$0(DemoVecotNo.java:27) at java.base/java.lang.Thread.run(Thread.java:834) java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 2 at java.base/java.util.Vector.get(Vector.java:781) at com.yanxizhu.demo.concurrency.synContainer.DemoVecotNo.lambda$main$1(DemoVecotNo.java:34) at java.base/java.lang.Thread.run(Thread.java:834) java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10 at java.base/java.util.Vector.remove(Vector.java:875) at com.yanxizhu.demo.concurrency.synContainer.DemoVecotNo.lambda$main…

线程不安全的类与写法
type: item
date: 2022-04-24T02:11:00+00:00
description: 线程不安全的类与写法线程不安全的类：类的对象可以同时被多个线程访问，比如抛出异常，逻辑错误。下面介绍一些常见的类。StringBuilderStringBuilder线程不安全的类代码示例package com.yanxizhu.demo.concurrency.threadUnSafetyClass; import com.yanxizhu.demo.concurrency.annotation.UnThreadSafety; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * @description: 线程不安全的类：StringBuilder * @author: 清风 * @date: 2022/4/24 9:01 * @version: 1.0 */ @Slf4j @UnThreadSafety public class DemoStringBuilder { //用户数量 private static final int clientsTotal = 5000; //并发数量 private static final int concurrencyTotal = 200; //累加总和 private static StringBuilder stringBuilder = new StringBuilder(); public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); //信号量 final Semaphore semaphore = new Semaphore(concurrencyTotal); //闭锁 final CountDownLatch countDownLatch = new CountDownLatch(clientsTotal); for (int i = 0; i < clientsTotal; i++) { executorService.execute(()->{ try { semaphore.acquire(); update(); semaphore.release(); } catch (InterruptedException e) { log.error("出现错误:【{}】", e.getMessage()); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("字符长度Length=【{}】",stringBuilder.length()); } /** * 累加 */ private static void update(){ stringBuilder.append(1); } }每次输出字符长度不一样，也不等于5000StringBuffer线程安全的类代码示例package com.yanxizhu.demo.concurrency.threadUnSafetyClass; import com.yanxizhu.demo.concurrency.annotation.ThreadSafety; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * @description: 线程安全的类：StringBuffer * @author: 清风 * @date: 2022/4/24 9:06 * @version: 1.0 */ @Slf4j @ThreadSafety public class DemoStringBuffer { //用户数量 private static final int cli…

高并发中集合问题
type: item
date: 2022-03-08T14:14:00+00:00
description: 第一代线程安全集合类Vector、Hashtable是怎么保证线程安排的：使用synchronized修饰方法缺点：效率低下第二代线程非安全集合类ArrayList、HashMap线程不安全，但是性能好，用来替代Vector、Hashtable使用ArrayList、HashMap，需要线程安全怎么办呢？使用Collections.synchronizedList（list）；Collections.synchronizedMap（m）；底层使用synchronized代码块锁虽然也是锁住了所有的代码，但是锁在方法里边，并所在方法外边性能可以理解为稍有提高吧。毕竟进方法本身就要分配资源的第三代线程安全集合类在大量并发情况下如何提高集合的效率和安全呢？java.util.concurrent.*ConcurrentHashMap：CopyOnWriteArrayList：CopyOnWriteArraySet：注意不是CopyOnWriteHashSet*底层大都采用Lock锁（1.8的ConcurrentHashMap不使用Lock锁），保证安全的同时，性能也很高。