并发学习记录13:不可变

问题的提出

日期转换的问题

在多线程的环境下做日期转换很可能出现线程安全问题:
代码:

@Slf4j(topic = "ch.UnchangeTest01")
public class UnchangeTest01 {
    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("1955-05-22"));
                } catch (ParseException e) {
                    log.debug("error: {}",e);
                }
            }).start();
        }
    }
}

输出:

Exception in thread "Thread-4" Exception in thread "Thread-0" 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 cha7Unchange.Introduce.UnchangeTest01.lambda$main$0(UnchangeTest01.java:16)
	at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: For input string: "22E2"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.parseLong(Long.java:631)
	at java.text.DigitList.getLong(DigitList.java:195)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2051)
	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 cha7Unchange.Introduce.UnchangeTest01.lambda$main$0(UnchangeTest01.java:16)
	at java.lang.Thread.run(Thread.java:748)
22:36:08.929 ch.UnchangeTest01 [Thread-6] - Mon Feb 22 00:00:00 CST 19552140
22:36:08.929 ch.UnchangeTest01 [Thread-2] - Mon Feb 22 00:00:00 CST 19552140
22:36:08.929 ch.UnchangeTest01 [Thread-8] - Sun May 22 00:00:00 CST 1955
22:36:08.929 ch.UnchangeTest01 [Thread-1] - Sun May 22 00:00:00 CST 1
22:36:08.929 ch.UnchangeTest01 [Thread-5] - Fri Apr 22 00:00:00 CST 1955
22:36:08.929 ch.UnchangeTest01 [Thread-9] - Sun May 22 00:00:00 CST 1955
22:36:08.929 ch.UnchangeTest01 [Thread-7] - Sun May 22 00:00:00 CST 1
22:36:08.929 ch.UnchangeTest01 [Thread-3] - Thu Nov 22 00:00:00 CST 222384

首先我们可以想到同步锁的方式解决这个问题,
代码:

@Slf4j(topic = "ch.UnchangeTest02")
public class UnchangeTest02 {
    public static void main(String[] args) {
        //带锁的实现可以规避线程问题
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (sdf) {
                    try {
                        log.debug("{}", sdf.parse("2001-05-25"));
                    } catch (ParseException e) {
                        log.debug("error:{}", e);
                    }
                }
            }, "t" + i).start();
        }
    }
}

这样虽然可以解决问题,但是带来的是性能上的损失。

除此之外,还有一种不可变的方法:
代码:

@Slf4j(topic = "ch.UnchangeTest03")
public class UnchangeTest03 {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                LocalDate date = dtf.parse("2021-09-21", LocalDate::from);
                log.debug("{}", date);
            }).start();
        }
    }
}

由于DateTimeFormatter is immutable and thread-safe.
所以可以通过不可变的方式解决并发安全性问题

不可变设计: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
 
 // ...
 
}

可以看到String类是final修饰的,value[]数组也是final修饰的。
属性用final修饰可以保证该属性是只读的,不能修改
类用final修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性

保护性拷贝

在String类中,也会有一些修改方法,比如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,而是创建了一个新的字符串。而进入String的构造方法

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);
    }

可以发现value数组也并没有被修改,而是通过Array.copyOfRange方法对内容进行复制,从而避免共享,这种方法就是保护性拷贝

享元模式

享元模式主要指的就是重用现有的同类对象,用于减少创建对象的数量,以减少内存占用和提高性能。

享元模式的体现

包装类

在JDK中Boolean,Byte,Short,Integer,Long,Character等包装类提供了valueOf方法,比如

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);
    }

可以在代码中看到,当你传入的值属于-128到127之间时,它会返回一个cache数组中的值,下面是cache的初始化,这样做就避免了反复创建新的对象

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);
        }
    }

注意

Byte,Short,Long缓存的范围是-128~127
Character的缓存范围是0~127
Integer的缓存范围是-128~127

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

上面是Integer Cache的初始化代码,其实可以看到最低的确实是-128,但是最大值可以通过调整参数来改变的

享元模式的应用

从包装类中的应用我们可以看出,有时候如果等需要再去创建对象可能会造成内存的浪费,所以我们可以事先准备一些对象供使用,使用完毕放到一个容器中暂存,等要用了再取,这样既可以节约对象创建和关闭的时间,也实现了对象的重用。典型的例子就是连接池。

final原理

1.设置final变量的原理
final的实现和volatile的实现类似,例如

public class TestFinal {
    final int = 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

//跟写屏障有关,待补充

无状态

设计servlet时为了保证servlet的线程安全,不要为servlet设置成员变量,这种没有任何成员变量的类是线程安全的。
因为成员变量保存的数据是状态信息,因此没有成员变量就可以称为无状态。

posted @   理塘DJ  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示