How do I prove programmatically that StringBuilder is not threadsafe?

后端 未结 3 1967
面向向阳花
面向向阳花 2020-11-30 00:41

How do I prove programmatically that StringBuilder is not threadsafe?

I tried this, but it is not working:

public class Threadsafe {
            


        
3条回答
  •  無奈伤痛
    2020-11-30 00:58

    Much simpler:

    StringBuilder sb = new StringBuilder();
    IntStream.range(0, 10)
             .parallel()
             .peek(sb::append) // don't do this! just to prove a point...
             .boxed()
             .collect(Collectors.toList());
    
    if (sb.toString().length() != 10) {
        System.out.println(sb.toString());
    }
    

    There will be no order of the digits (they will not be 012... and so on), but this is something you don't care about. All you care is that not all the digits from range [0..10] where added to StringBuilder.

    On the other hand if you replace StringBuilder with StringBuffer, you will always get 10 elements in that buffer (but out of order).

提交回复
热议问题