Skip to main content
fix spelling of title
Link
Nathan Hughes
  • 96.7k
  • 21
  • 193
  • 288

Is the pre-incrimentincrement operator thread-safe? (java)

Source Link
TPXL
  • 327
  • 1
  • 3
  • 12

Is the pre-incriment operator thread-safe? (java)

I'm making a program in java that races a few cars against each other. Each car is a separate thread.

When cars complete the race, each one all calls this method. I've tested the method at varying timer speeds, and it seems to work fine. But I do realize that each thread is accessing the variable carsComplete, sometimes at the exact same time (at least at the scope the date command is giving me).

So my question is: is this method thread-safe?

 public static String completeRace() { Date accessDate = new Date(); System.out.println("Cars Complete: " + carsComplete + " Accessed at " + accessDate.toString()); switch(++carsComplete) { case 1: return "1st"; case 2: return "2nd"; case 3: return "3rd"; default: return carsComplete + "th"; } }