Question

I'm using TestNG to run tests in parallel and want to be careful about possible synchronization issues with helper classes and utilities. To my knowledge, each test is its own object, transparently created by the test runner. Thus, I don't need to worry about synchronizing anything non-static, since it would be an object created in a Thread, and therefore not visible to the other ones.

However, when I make calls to this outside log function I wrote, does it need to be synchronized? Is there a possible race condition where thread-1 enters and sets threadName="Thread-1", then thread-2 enters and sets the SAME threadName variable = "Thread-2", and then thread-1 picks back up and prints out "--foo | Thread-2"? Do I need to make this a synchronized method?

public static void log(String _message) {
  String threadName = Thread.currentThread().getName();
  log.println("--" + _message + " | Thread: " + threadName);
}
Was it helpful?

Solution

Your variable threadName is a local variable. There will exist one instance for each thread, more correctly, there will exist one instance for every function call. This means they can not affect each other.

OTHER TIPS

Emphasizing what Marcus said above: what is this log field? Make sure it is thread safe or you will see mixed up log messages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top