规范代码示例

1. 编程-并发处理

线程池

/**
 * 【强制】创建线程、线程池时需要指定有意义的线程名称[eg. 机房号],方便出错回溯  ??TODO 怎么回溯
 * 【示例】自定义线程工厂, 并根据外部特征进行分组。比如:机房号、IP地址等
 *
 * @author qiaoba.ty
 */
public class UserThreadFactory implements ThreadFactory {

    private final String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger(1);

    /**
     * 可以通过工具类获取,eg. ZoneClientUtils
     *
     * @param whatFeatureOfGroup 分组的特征
     */
    public UserThreadFactory(String whatFeatureOfGroup) {
        this.namePrefix = "From UserThreadFactory's" + whatFeatureOfGroup + "-Worker-";
    }

    @Override
    public Thread newThread(Runnable task) {
        String name = namePrefix + nextId.getAndIncrement();
        return new Thread(null, task, name, 0);
    }

    public static void main(String[] args) {
        // 【强制】线程资源必须通过线程池提供,不允许在应用自行创建线程
        // 【强制】创建线程池通过ThreadPoolExecutor,不允许使用Executors,因为Executors参数设置有点问题
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2),
            new UserThreadFactory("local")
            //new BizThreadFactory(AmapClientUtil.getHost)
        );

        /**
         * 线程池执行流程:
         * step1. 如果线程池大小 <  corePoolSize, 创建新线程执行任务
         * step2. 任务进入workQueue中等待, 等待释放后的线程执行
         * step3. 任务加入workQueue失败,若线程池大小 < maxPoolSize, 创建新线程执行任务。若已达到maxPoolSize则拒绝任务
         */
        pool.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("hah");
            }
        });
    }
}

ThreadLocal 

public class TestContextHolder {

    /**
     * ThreadLocal用static修饰,避免重复创建变量。 为该类的每个实例,都创建新变量
     */
    public static ThreadLocal<String> test = new ThreadLocal<>();

    public static void main(String[] args) {
        try {
            boolean bool = test.get() == null;
        } catch (Exception e) {
        } finally {
            // 【强制】必须回收自定义的ThreadLocal变量,因为线程可能会重复使用。可能导致数据串了的问题
            test.remove();
        }
    }
}

Redis实现的分布式锁怎么可重入?

 

2. 编程-集合处理

map 

        List<Pair<String, Double>> pairArrayList = new ArrayList<>(3);
        pairArrayList.add(new Pair<>("version", 10.24));
        pairArrayList.add(new Pair<>("version", 13.14));
        // 【强制】在使用java.util.stream.Collectors的toMap方法时,一定要指定mergeFunction, 合并相同KEY的VALUE。否则会抛出IllegalStateException。{version=13.14}
        Map<String, Double> map = pairArrayList.stream().collect(
            Collectors.toMap(Pair::getKey, Pair::getValue, (aDouble, aDouble2) -> aDouble2));

        // 【强制】在使用java.util.steam.Collectors的toMap方法时,若value=null, 会抛出NPE异常。HashMap.merge()里有value非空判断
        pairArrayList.add(new Pair<>("version", null));
        Map<String, Double> map2 = pairArrayList.stream().collect(
            Collectors.toMap(Pair::getKey, Pair::getValue, (aDouble, aDouble2) -> aDouble2));

        // 【强制】Collections返回的对象,如emptyList()/emptyMap()等都是final对象,不可对其进行修改
        List<Object> emptyList = Collections.emptyList();
        emptyList.add("23333333");

 

posted @ 2021-04-06 11:06  大美da美  阅读(153)  评论(0)    收藏  举报