0

I want to test my method for thread-safety. For that I am using an atomicboolean. If it is true, then an exception is thrown. Now i want to test this function. What is the best way to test this function??

public void startProcess() {
      if(inProcess.compareAndSet(false, true)) {
              service.startProcess();
              inProcess.set(false);
      } else {
          throw new SomeNewException("Process running.");
      }
      inProcess.set(false);
}

thanks in advance

trap
  • 2,550
  • 7
  • 21
  • 42
  • You forgot a closing parenthesis. Also, in Java, procedures are called *methods* rather than functions. – MC Emperor Feb 21 '19 at 23:07
  • https://stackoverflow.com/questions/17414924/how-to-test-atomicboolean-atomicity – Mebin Joe Feb 22 '19 at 07:32
  • just launch 2 threads calling that method – aran Feb 22 '19 at 07:34
  • take a look at https://dzone.com/articles/testing-multithreaded-code-in-java-1 – hovanessyan Feb 22 '19 at 09:32
  • You don’t need a test to see that this method is broken. At its end, there is a redundant `inProcess.set(false);`, which could overwrite the `true` state created by another thread between the two `inProcess.set(false);` statements. Besides that, the entire logic is questionable. How is the caller supposed to know that the call is invalid, i.e. a process is running? Even if you add a method like `isRunning()`, using it before the call would be subject to the check-then-act anti-pattern. And if the process may still run upon `startProcess()`’s return, as the name suggests, it’s even more broken… – Holger Apr 04 '19 at 12:53

0 Answers0