不可变对象
- 对象创建以后其状态就不能修改
- 对象所有域是final类型
修饰类:不能被继承
修饰方法:1、锁定方法类不能被继承修改
2、效率
修饰变量: 基本数据类型变量,引用类型变量。
package com.mmall.example.immutable;
import com.google.common.collect.Maps;
import com.mmall.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* final 修饰变量 (map 非线程安全)
* Created by megan on 2018/3/31.
*/
@Slf4j
@NotThreadSafe
public class FinalExample {
private final static Integer a = 1 ;
private final static String b = "2";
private final static Map<Integer,Integer> map = Maps.newHashMap();
static{
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
map.put(7, 8);
}
public static void main(String[] args) {
// a = 2;
// b = "3";
// map = Maps.newHashMap();
map.put(1, 3);
log.info("{}",map.get(1));
}
private void test(final int a){
//a = 1 ;
}
}
- 对象是正确的创建的(在对象创建期间,this引用没有溢出)
![](https://img.haomeiwen.com/i10538467/6a52771d0a716c24.png)
不可变对象类
package com.mmall.example.immutable;
import com.google.common.collect.Maps;
import com.mmall.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.Collections;
import java.util.Map;
/**
* Collections.unmodifiableMap 修饰Map (线程安全)
* Created by megan on 2018/3/31.
*/
@Slf4j
@ThreadSafe
public class CollectionsExample {
private static Map<Integer, Integer> map = Maps.newHashMap();
static {
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
map.put(7, 8);
map = Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
/** 不允许这样做-》Collections.unmodifiableMap 保证了线程的安全 **/
map.put(1, 3);
log.info("{}", map.get(1));
}
}
package com.mmall.example.immutable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.mmall.annoations.ThreadSafe;
/**
* Immutable --> ImmutableList,ImmutableSet,ImmutableMap
* Created by megan on 2018/3/31.
*/
@ThreadSafe
public class GuavaImmutableExample {
private final static ImmutableList<Integer> list = ImmutableList.of(1,2,3,4,5);
private final static ImmutableSet set= ImmutableSet.copyOf(list);
private final static ImmutableMap<Integer,Integer> map = ImmutableMap.of(1,2,3,4,5,6);
private final static ImmutableMap<Integer,Integer> map2 = ImmutableMap.<Integer,Integer>builder().
put(1,2).put(3,4).put(4,5).build();
public static void main(String[] args) {
/** 不允许修改 **/
list.add(6);
set.add(7);
map.put(7,8);
map2.put(6,7);
}
}
线程封闭
- Ad-hoc 线程封闭: 程序控制实现,最糟糕,忽略。
- 堆栈封闭: 局部变量,无并发问题。
- ThreadLocal线程封闭: 特别好的封闭方法。
package com.mmall.example.threadLocal;
import com.mmall.annoations.ThreadSafe;
/**
* threadLocal ->线程封闭
* Created by megan on 2018/3/31.
*/
@ThreadSafe
public class RequestHolder {
private final static ThreadLocal<Long> requestHolder = new ThreadLocal<>();
public static void add(Long id){
requestHolder.set(id);
}
public static Long get(){
return requestHolder.get();
}
public static void remove(){
requestHolder.remove();
}
}
网友评论