共享模型之不可变

一、共享模型之不可变

1.日期转换的问题

@Slf4j
public class TestDate {
    public static void main(String[] args) {
        test3();
    }

    private static void test1() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    log.debug("{}", sdf.parse("2023-12-04"));
                } catch (Exception e) {
                    log.error("{}", e);
                }
            }).start();
        }
    }
    //java.lang.NumberFormatException: For input string: ""
    //java.lang.NumberFormatException: empty String


    /**
     * 加锁解决
     */
    private static void test2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (sdf) {
                    try {
                        log.debug("{}", sdf.parse("2023-12-04"));
                    } catch (Exception e) {
                        log.error("{}", e);
                    }
                }
            }).start();
        }
    }
    //15:12:41.511 [Thread-0] DEBUG juc.nochange.TestDate - Mon Dec 04 00:00:00 CST 2023


    /**
     * 如果一个对象在不能够修改其内部状态(属性),那么它就是线程安全的,因为不存在并发修改,这样的对象在
     * Java 中有很多,例如在 Java 8 后,提供了一个新的日期格式化类
     */
    private static void test3() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                LocalDate date = dtf.parse("2023-12-04", LocalDate::from);
                log.debug("{}", date);
            }).start();
        }
    }
    //15:13:54.269 [Thread-1] DEBUG juc.nochange.TestDate - 2023-12-04
}

二、不可变类设计

String类:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

1.final 的使用

发现该类、类中所有属性都是 final 的

  • 属性用 final 修饰保证了该属性是只读的,不能修改
  • 类用 final 修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性

2.保护性拷贝

使用字符串时,也有一些跟修改相关的方法,比如 substring 等,substring 的实现:

    public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }
//其内部是调用 String 的构造方法创建了一个新字符串,构造方法,没有对 final char[] value 做出修改:
    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {
                this.value = "".value;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

构造新字符串对象时,会生成新的 char[] value,对内容进行复制 。
这种通过创建副本对象来避免共享的手段称之为【保护性拷贝(defensive copy)】

三、无状态类设计

享元模式

1.包装类

避免对象重复创建:
在IDK中 Boolean,Byte, Short, Integer, Long,Character 等包装类提供了value0f方法,例如Long的value0f会缓存-128~127之间的Long对象,在这个范围之间会重用对象,大于这个范围,才会新建Long对象

    private static class LongCache {
        private LongCache(){}

        static final Long cache[] = new Long[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Long(i - 128);
        }
    }

    public static Long valueOf(String s) throws NumberFormatException
    {
        return Long.valueOf(parseLong(s, 10));
    }

    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }
  • Byte,Short,Long 缓存的范围都是-128~127
  • Character缓存的范围是0~127
  • Integer的默认范围是-128~127,最小值不能变,但最大值可以通过调整虚拟机参数-Djava.lang.Integer.IntegerCache.high来改变
  • Boolean 缓存了 TRUE 和 FALSE

四、连接池设计

public class TestPool {
    public static void main(String[] args) {
        Pool pool = new Pool(2);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Connection conn = pool.borrow();
                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                pool.free(conn);
            }).start();
        }
    }
}

@Slf4j
class Pool {
    // 1. 连接池大小
    private final int poolSize;

    // 2. 连接对象数组
    private Connection[] connections;

    // 3. 连接状态数组 0 表示空闲, 1 表示繁忙
    private AtomicIntegerArray states;

    // 4. 构造方法初始化
    public Pool(int poolSize) {
        this.poolSize = poolSize;
        this.connections = new Connection[poolSize];
        this.states = new AtomicIntegerArray(new int[poolSize]);
        for (int i = 0; i < poolSize; i++) {
            connections[i] = new MockConnection("连接" + (i+1));
        }
    }

    // 5. 借连接
    public Connection borrow() {
        while(true) {
            for (int i = 0; i < poolSize; i++) {
                // 获取空闲连接
                if(states.get(i) == 0) {
                    if (states.compareAndSet(i, 0, 1)) {
                        log.debug("borrow {}", connections[i]);
                        return connections[i];
                    }
                }
            }
            // 如果没有空闲连接,当前线程进入等待
            synchronized (this) {
                try {
                    log.debug("wait...");
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 6. 归还连接
    public void free(Connection conn) {
        for (int i = 0; i < poolSize; i++) {
            if (connections[i] == conn) {
                states.set(i, 0);
                synchronized (this) {
                    log.debug("free {}", conn);
                    this.notifyAll();
                }
                break;
            }
        }
    }
}

class MockConnection implements Connection {

    private String name;

    public MockConnection(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "MockConnection{" +
                "name='" + name + '\'' +
                '}';
    }
  // @Override....
}

以上实现没有考虑

  • 连接的动态增长与收缩
  • 连接保活 (可用性检测)
  • 等待超时处理
  • 分布式 hash

对于关系型数据库,有比较成熟的连接池实现,例如c3p0.druid等对于更通用的对象池,可以考虑使用apache commons pool,例如redis连接池可以参考jedis中关于连接池的实

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 不可变类 例子- 时间转换问题 SimpleDateFormat 为啥不是线程安全的 ? 可以看到,多个线程之间共...
    程序员札记阅读 215评论 0 1
  • 一.不可变 理论 1.什么是不可变 如果一个对象他里面的所有成员变量都是不可变的,那么这个对象可以认为他是线程安全...
    ywshi阅读 319评论 0 0
  • 本章内容 不可变类的使用 不可变类设计 无状态类设计 1、日期转换的问题 问题提出 下面的代码在运行时,由于 Si...
    zhemehao819阅读 261评论 0 0
  • @TOC 7.2 不可变设计 属性用final修饰保证了该属性是只读的,不能修改 类用final修饰保证了该类中的...
    小小一技术驿站阅读 181评论 0 0
  • 解决并发问题,其实最简单的办法就是让共享变量只有读操作,而没有写操作。这个办法如此重要,以至于被上升到了一种解决并...
    xuxw阅读 161评论 0 0