Skip to content

Instantly share code, notes, and snippets.

@snobutaka
Created October 28, 2018 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snobutaka/4fddfd23e56e10d7d6bf901e0d152733 to your computer and use it in GitHub Desktop.
Save snobutaka/4fddfd23e56e10d7d6bf901e0d152733 to your computer and use it in GitHub Desktop.
Bad example: Use SimpleDateFormat with multi threads
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BreakDateFormat {
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static void main(String[] args) throws ParseException, InterruptedException {
final int numThreads = 10;
final int numLoops = 10;
final String dateString = "2001-07-04T12:08:56.235-0700";
final Set<Date> parsedDates = Collections.synchronizedSet(new HashSet<>());
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numLoops; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
for (int j = 0; j < numLoops; j++) {
parsedDates.add(dateFormat.parse(dateString));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("size=" + parsedDates.size());
System.out.println("values:");
for (Date date : parsedDates) {
System.out.println(dateFormat.format(date));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment