线程安全的Map的小Demo

2019-05-20 10:30:47 浏览数 (1)

代码语言:javascript复制
public class TempUser {

    private final ConcurrentHashMap<String, Future<String>> cache = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, FutureTask<String>> taskCache = new ConcurrentHashMap<>();


    public String setUser(String name, String content) {

        while (true) {
            Future<String> f = cache.get(name);
            if (f == null) {

                Callable<String> callable = new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return content;
                    }
                };

                FutureTask<String> ft = new FutureTask<String>(callable);

                Future<String> stringFuture = cache.putIfAbsent(name, ft);

                //如果放入成功 返回null
                if(stringFuture==null){
                    f = ft;
                    ft.run();
                }

                try {
                    return f.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }


            }


        }


    }

    public int getSize(){

       return cache.size();
    }


    public String setUser02(String name, String content) {

        while (true) {
            FutureTask<String> ft = taskCache.get(name);
            if (ft == null) {

                Callable<String> callable = new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return content;
                    }
                };
                FutureTask<String> ft2 = new FutureTask<String>(callable);

                Future<String> stringFuture = cache.putIfAbsent(name, ft2);

                //如果放入成功 返回null
                if(stringFuture==null){
                    ft = ft2;
                    ft2.run();
                }

                try {
                    return ft.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }


            }


        }


    }



}

0 人点赞