Should it be a synchronized method?

I use TestNG to run tests in parallel and want to be careful about possible synchronization issues with helper classes and utilities. As far as I know, each test is its own object, transparently created by the tester. Thus, I do not need to worry about synchronizing anything non-static, since it would be an object created in the stream and therefore not visible to others.

However, when I call this external journal function, I wrote, do I need to synchronize it? Is there a possible race condition when thread-1 enters and sets threadName = "Thread-1", then thread-2 enters and sets SAME threadName variable = "Thread-2", and then thread-1 selects the backup and prints "- -foo | thread-2 "? Do I need to synchronize this method?

public static void log(String _message) { String threadName = Thread.currentThread().getName(); log.println("--" + _message + " | Thread: " + threadName); } 
+4
source share
2 answers

Your threadName variable is a local variable . There will be one instance for each thread , or rather, for each function call, there will be one instance. This means that they may not influence each other.

+4
source

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

+1
source

All Articles