6、共享模型之不可变

12 篇文章 0 订阅

本章内容

  • 不可变类的使用
  • 不可变类设计
  • 无状态类设计

1、日期转换问题

问题提出

下面代码在运行时,由于SimpleDateFormat 不是线程安全的

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    log.debug("{}",sdf.parse("1951-04-21"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }

有很大几率出现java.lang.NumberFormatException

Exception in thread "Thread-1" Exception in thread "Thread-5" Exception in thread "Thread-2" Exception in thread "Thread-3" java.lang.NumberFormatException: multiple points
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at notchange.Test1.lambda$main$0(Test1.java:19)
	at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: empty String
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at notchange.Test1.lambda$main$0(Test1.java:19)
	at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: multiple points
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at notchange.Test1.lambda$main$0(Test1.java:19)
	at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: multiple points
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at notchange.Test1.lambda$main$0(Test1.java:19)
	at java.lang.Thread.run(Thread.java:748)
2022/03/13-01:00:11.983 [Thread-8] c.Test1 - Sat Apr 21 00:00:00 CST 1951
2022/03/13-01:00:11.983 [Thread-9] c.Test1 - Sat Apr 21 00:00:00 CST 1951
2022/03/13-01:00:11.983 [Thread-6] c.Test1 - Fri Aug 21 00:00:00 CST 176769542
2022/03/13-01:00:11.983 [Thread-7] c.Test1 - Sat Mar 31 00:00:00 CST 1951
2022/03/13-01:00:11.983 [Thread-4] c.Test1 - Fri Aug 21 00:00:00 CST 176769542
2022/03/13-01:00:11.983 [Thread-0] c.Test1 - Fri Aug 21 00:00:00 CST 176769542

思路-同步锁

这样虽然能解决问题,但带来的是性能的损失,并不算好:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (sdf) {
                    try {
                        log.debug("{}",sdf.parse("1951-04-21"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

思路-不可变

如果对象在一个不能修改其内部状态(属性),那么它就是线程安全的,因为不存在并发修改,这样的对象在java中有很多,例如java8之后,提供了一个新的日期格式化类:

		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                log.debug("{}", dtf.parse("1951-04-21"));
            }).start();
        }

可以看DateTimeFormatter

 * @implSpec
 * This class is immutable and thread-safe.

2、不可变设计

另一个大家更为熟悉的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
 
 	// ...
 
}

final的使用

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

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

保护性拷贝

但有同学会说,使用字符串时,也有一些跟修改相关的方法啊,比如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;
 }
 }
 if (offset > value.length - count) {
 throw new StringIndexOutOfBoundsException(offset + count);
 }
 this.value = Arrays.copyOfRange(value, offset, offset+count);
}

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

3、模式之享元

1、简介

定义 英文名称:Flyweight pattern,当需要重用数量有线的同一类对象映射时

wikipedia: A flyweight is an object that minimizes memory usage by sharing as much data as
possible with other similar objects

出自 “Gang of Four”design patterns
归类 Structual patterns

2、体现

2.1、包装类

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

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.IntegerCache.high来改变
  • Boolean缓存了TRUE和FALSE

2.2 String 串池

2.3 Bigdecimal BigInteger

3、DIY

例如:一个线上商城应用,QPS达到数千,如果每次都重新传建和关闭数据库连接,性能会受到极大影响。这是预先创建好一批连接,放入连接池。一次请求到达后,从连接池获取连接,使用完毕后再还给连接池,这样既节约了连接的创建和关闭时间,也实现了连接的重用,不至于让庞大的连接数压垮数据库。

@Slf4j(topic = "c.Pool")
public class Pool {
    // 1.连接池大小
    private final int poolSize;

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

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

    // 4.构造方法初始化
    public Pool(int poolSize) {
        this.poolSize = poolSize;
        this.connections = new Connection[poolSize];
        this.states = new AtomicIntegerArray(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 {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

}

class MockConnection implements Connection {
    String name;

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

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

interface Connection {

}

测试

Pool pool = new Pool(2);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Connection connection = pool.borrow();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                pool.free(connection);
            }).start();
        }

输出

2022/03/13-01:46:50.896 [Thread-1] c.Pool - borrow MockConnection{name='连接2'}
2022/03/13-01:46:50.896 [Thread-0] c.Pool - borrow MockConnection{name='连接1'}
2022/03/13-01:46:51.903 [Thread-1] c.Pool - free MockConnection{name='连接2'}
2022/03/13-01:46:51.903 [Thread-0] c.Pool - free MockConnection{name='连接1'}
2022/03/13-01:46:51.903 [Thread-4] c.Pool - borrow MockConnection{name='连接1'}
2022/03/13-01:46:51.903 [Thread-3] c.Pool - borrow MockConnection{name='连接2'}
2022/03/13-01:46:52.908 [Thread-4] c.Pool - free MockConnection{name='连接1'}
2022/03/13-01:46:52.908 [Thread-3] c.Pool - free MockConnection{name='连接2'}
2022/03/13-01:46:52.908 [Thread-2] c.Pool - borrow MockConnection{name='连接1'}
2022/03/13-01:46:53.918 [Thread-2] c.Pool - free MockConnection{name='连接1'}

以上实现没有考虑:

  • 连接池的动态增长与收缩
  • 连接保活(可用性检测)
  • 等待超时处理
  • 分布式hash
    对于关系型数据库,有比较成熟的连接池实现,例如c3p0,druid等 ,对于更通用的对象池,可以考虑apache commons pool,例如redis连接池可以参考jedis中关于连接池的实现

原理之final

1、设置final变量的原理

理解了volatile原理,再对比final的实现就比较简单了

public vlass TestFinal{
	final int a = 20;
}

字节码

0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 20
7: putfield #2 // Field a:I
 <-- 写屏障
10: return

发现final变量的赋值也会通过putfield指令完成,同样在这条指令之后也会加入写屏障,保证其他线程读到它的值时不会出现0的情况

2、获取final变量的原理

5、无状态

在web学习阶段时,设计Servlet时为了保证其线程安全,都会有这样的建议,不要为Servlet设置成员变量,这种没有任何成员变量的类是线程安全的

因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为【无状态】

本章小结

  • 不可变类使用
  • 不可变类设计
  • 原理方面
    • final
  • 模式方面
    • 享元模式
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值