目录
- @Slf4j
- public class Test1 {
- public static void main(String[] args) {
- 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 (Exception e) {
- log.error("{}", e);
- }
- }).start();
- }
- }
- }
上面的代码在运行时,由于SimpleDateFormat不是线程安全的,有很大几率出现java.lang.NumberFormatException或者出现不正确的日期解析结果。有以下方法可以解决:
- @Slf4j
- public class Test1 {
- public static void main(String[] args) {
- method1();
- }
-
- // 方法1
- private static void method1() {
- 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 (Exception e) {
- log.error("{}", e);
- }
- }
- }).start();
- }
- }
-
- // 方法2
- private static void method2() {
- DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- for (int i = 0; i < 10; i++) {
- new Thread(()->{
- TemporalAccessor parse = dtf.parse("1951-04-21");
- log.debug("{}", parse);
- }).start();
- }
- }
- }
-
- 结果:
- 16:38:55.496 [Thread-3] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.496 [Thread-4] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.497 [Thread-9] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.495 [Thread-2] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.497 [Thread-6] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.496 [Thread-0] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.496 [Thread-1] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.497 [Thread-7] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.496 [Thread-5] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
- 16:38:55.497 [Thread-8] DEBUG com.multiThreads.Test17.Test1 - {},ISO resolved to 1951-04-21
另一个大家更为熟悉的String类也是不可变的,以它为例,说明以下不可变设计的要素。
- public final class String
- implements java.io.Serializable, Comparable
, 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的:
- 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)】。
定义:享元模式(Flyweight pattern),当需要重用数量有限的同一类对象时。
在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.Integer.IntegerCache.high来改变;Boolean缓存了TRUE和FALSE。
例如:一个线上商城应用,QPS达到数千,如果每次都重新创建和关闭数据库连接,性能会受到极大影响。这时预先创建好一批连接,放入连接池,一次请求到达后,从连接池获取连接,使用完毕后再还回连接池,这样既节约了连接的创建和关闭时间,也实现了连接的重用,不至于让庞大的连接数压垮数据库。
- public class Test2 {
- 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 {
- // 连接池大小
- private final int poolSize;
- // 连接数组
- private Connection[] conns;
- // 连接是否被占用 标记
- private AtomicIntegerArray states;
-
- // 初始化连接池
- public Pool(int poolSize) {
- this.poolSize = poolSize;
- this.conns = new Connection[poolSize];
- this.states = new AtomicIntegerArray(new int[poolSize]);
- for (int i = 0; i
- conns[i] = new MockConnection("连接" + (i + 1));
- }
- }
-
- // 从连接池暂借连接
- 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 {}", conns[i]);
- return conns[i];
- }
- }
- }
- // 如果没有空闲连接,当前线程进入等待,不让CPU空转
- synchronized (this) {
- try {
- log.debug("wait...");
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- // 归还连接至连接池
- public void free(Connection conn) {
- for (int i = 0; i < poolSize; i++) {
- if (conns[i] == conn) {
- states.set(i, 0);
- synchronized (this) {
- log.debug("free {}", conn);
- this.notifyAll();
- }
- break;
- }
- }
- }
- }
-
- @Data
- class MockConnection implements Connection {
- private String name;
-
- public MockConnection(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "MockConnection{" +
- "name='" + name + '\'' +
- '}';
- }
-
- @Override
- public Statement createStatement() throws SQLException {
- return null;
- }
-
- // ...
- }
-
- 结果:
- 10:46:30.387 [Thread-0] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
- 10:46:30.387 [Thread-2] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:30.387 [Thread-1] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接2'}
- 10:46:30.390 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:30.390 [Thread-3] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:30.486 [Thread-1] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接2'}
- 10:46:30.486 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:30.486 [Thread-3] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接2'}
- 10:46:30.486 [Thread-2] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:30.912 [Thread-0] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}
- 10:46:30.912 [Thread-2] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
- 10:46:30.913 [Thread-4] DEBUG com.multiThreads.Test17.Pool - wait...
- 10:46:31.361 [Thread-2] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}
- 10:46:31.361 [Thread-4] DEBUG com.multiThreads.Test17.Pool - borrow MockConnection{name='连接1'}
- 10:46:31.484 [Thread-3] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接2'}
- 10:46:31.924 [Thread-4] DEBUG com.multiThreads.Test17.Pool - free MockConnection{name='连接1'}
以上实现没有考虑:
- 连接的动态增长与收缩;
- 连接保活(可用性检测);
- 等待超时处理;
- 分布式hash。
对于关系型数据库,有比较成熟的连接池实现,例如:c3p0,druid等,对于更通用的对象池,可以考虑使用apache commons pool,例如redis连接池可以参考jedis中关于连接池的实现。
4、final原理
4.1、设置final变量的原理
理解了volatile原理,再对比final的实现就比较简单了。
- class TestFinal {
- final int a = 20;
- }
字节码:
- 0: aload_0
- 1: invokespecial #1 // Method java/lang/Object."
"()V - 4: aload_0
- 5: bipush 20
- 7: putfield #2 // Field a:I
- <-- 写屏障
- 10: return
发现final变量的赋值也会通过putfield指令来完成,同样在这条指令之后也会加入写屏障,保证在其它线程读到它的值时不会出现为0的情况。
5、无状态
在Web学习阶段时,设计Servlet时为了保证其线程安全,都会有这样的建议:不要为Servlet设置成员变量,这种没有任何成员变量的类是线程安全的。
因为成员变量保存的数据也可以称为状态信息,因此没有成员变量就称之为【无状态】。