java8 on the use of thread-safe collection Set

Scene: simultaneous multi-threading, when storing data to Set collection, not the final number of results found, after investigation, did not lead to the use of thread-safe Set

 

Haha, will not describe, explain all the code, the following code, Sets.newHashSet use () and Collections.synchronizedSet (Sets.newHashSet ()) are two ways to declare a Set collection, the first of which is not thread-safe, first two thread-safe

Code:

 public static void main(String[] args) {
        ExecutorService executor = new ThreadPoolExecutor(
                10, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100000), threadFactory);

        // put 0-69999 numeric string, no duplicate 
        List <String> numlist = Lists.newArrayList ();
         for ( int I = 0; I <70000; I ++ ) {
            numList.add(String.valueOf(i));
        }

        // the partition set 2000 set 
        List <List <String >> tmpNumList = ToolsUtil.spliceArrays (numlist, 2000 );

        // multithreaded operation 
        List <Future <Integer >> futureList = new new ArrayList <> ();
        Set<String> numSet = Sets.newHashSet();
        Set<String> numSyncSet = Collections.synchronizedSet(Sets.newHashSet());
        tmpNumList.forEach(list -> futureList.add(executor.submit(() -> {
            list.forEach(num -> {
                numSet.add(num);
                numSyncSet.add(num);
            });
            return 1;
        })));

        futureList.forEach(future -> {
            try {
                future.get();
            } catch (Exception e) {
                logger.warn("error,", e);
            }
        });

        // result output 
        System.out.println ( "thread safe the Set:" + numSet.size ());
        System.out.println ( "thread safety of the Set:" + numSyncSet.size ());
    }

:( run multiple console output, thread-safe digital has changed, and incorrect)

 

Guess you like

Origin www.cnblogs.com/JoeyWong/p/11971810.html