加入依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
具体类:
@Slf4j
public class UnsafePublish {
private static final String[] states = {"a", "b", "c"};
public String[] getStates() {
return this.states;
}
public static void main(String[] args) {
// String[] str={"a", "b", "c"};
// System.out.println(str);
// System.out.println(Arrays.toString(str));
UnsafePublish unsafePublish = new UnsafePublish();
log.info(Arrays.toString(unsafePublish.getStates()));
unsafePublish.getStates()[0] = "d";
//private的属性遭到了修改,私有属性不再是确定的属性,所以线程不再安全
log.info(Arrays.toString(unsafePublish.getStates()));
List<String> stringA = Arrays.asList(unsafePublish.getStates());
ImmutableList immutableList = ImmutableList.copyOf(stringA);
log.info("" + immutableList.get(0));
immutableList.add(0, "e");
log.info("" + immutableList.get(0));
}
}
输出结果:
:46:28.323 [main] INFO com.wangzhou.highconcurrent.publish.UnsafePublish - [a, b, c]
10:46:28.332 [main] INFO com.wangzhou.highconcurrent.publish.UnsafePublish - [d, b, c]
10:46:28.352 [main] INFO com.wangzhou.highconcurrent.publish.UnsafePublish - d
Exception in thread "main" java.lang.UnsupportedOperationException
at com.google.common.collect.ImmutableList.add(ImmutableList.java:524)
at com.wangzhou.highconcurrent.publish.UnsafePublish.main(UnsafePublish.java:43)
前面三行结果可以表明,虽然states是private但是依然实现了对数组里内容的修改,但是如果我们使用guava下的ImmutableList类,immutableList里内容就不可修改了。强行修改编译时会报错UnsupportedOperationException。
guava里没有提供专门实现String[]不可变的类,但是提供了关于map,set,list,long[],int[]等等的不可变对象。我们如果需要实现不可变对象,String[]尽量不要用。