views:

83

answers:

2

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);
}
+4  A: 

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.

Marcus Johansson
Great! Thats what I thought, thanks for the LIGHTNING (literally 10 seconds or less) fast response!Is my assumption that I don't need to worry about synchronizing non-static methods correct? In fact, the only thing I need to worry about are static member variables?
dhackner
Since non-static methods can access shared data too, i would recommend always using a monitor.A monitor is a passive class, which only purpose is to hold variables. One important property the monitor must fulfill, is to be thread safe. I have only used semaphores to accomplish this in Java, but i guess synchronized methods work the same way. :)
Marcus Johansson
This assumes that `log.println()` is thread safe.
Marcus Adams
In this case, what non-static shared data could there be?
dhackner
I've defined it as private static final PrintStream log = System.out;Is the fear that the internal workings of log might not handle multiple threads accessing it at once? Should it be volatile instead of final?
dhackner
+1  A: 

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

Cedric Beust