How do I prove programmatically that StringBuilder is not threadsafe?
I tried this, but it is not working:
public class Threadsafe {
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).