0

Hello i am working on a code and i get Fortify Race Condition:Format Flaw issue and i don't know how to fix it. I have searched on stackoverflow and i couldn't find an accurate way to fix it. I get this error from that part of codes:

Date date = new Date();
            newDevice.setCreationDate(dateFormat.format(date));

and

firstTrx.setTrxID(getSessionUser().getUserName() + dateFormat.format(date));

And i create the dateFormat instance here:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

I would be very happy if you help, thanks.

Murathan
  • 51
  • 1
  • 8
  • There’s not enough context to help but the [Fortify docs](https://vulncat.fortify.com/en/detail?id=desc.structural.java.race_condition_format_flaw) explain the problem in detail. TL;DR: create a new formatter at the point of use to avoid sharing them between threads. – Dave Newton Jan 22 '23 at 13:36
  • 1
    `SimpleDateFormat` is a stateful converter from `java.util.Date` to string. When you use it from multiple threads you will get unexpected results (i.e. parts of two different dates). The best way to solve this problem is to ditch **all** usages of the problematic `java.util.Date`, `DateFormat` and `SimpleDateFormat` and use the newer `java.time` API instead (i.e. `java.time.LocalDateTime` and `java.time.format.DateTimeFormatter`.) – Thomas Kläger Jan 22 '23 at 14:10
  • I strongly recommend you don’t use `Date`, `DateFormat` and `SimpleDateFormat`. Those classes are long outdated and notoriously troublesome. You have met just one of the very many problems with them. Use [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/index.html) instead. `ZonedDateTime.now(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))`. And a `DateTimeFormatter` is thread-safe. – Ole V.V. Jan 22 '23 at 19:41

0 Answers0