这应该是一个同步方法吗?
我正在使用 TestNG 并行运行测试,并希望小心帮助程序类和实用程序可能出现的同步问题。据我所知,每个测试都是它自己的对象,由测试运行者透明地创建。因此,我不需要担心同步任何非静态的东西,因为它将是在线程中创建的对象,因此对其他对象不可见。
但是,当我调用我编写的外部日志函数时,是否需要同步?是否存在可能的竞争条件,线程 1 进入并设置 threadName="Thread-1",然后线程 2 进入并设置 SAME threadName 变量 = "Thread-2",然后线程 1 重新拾起并打印出来“--foo | Thread-2”?我需要将其设为同步方法吗?
public static void log(String _message) {
String threadName = Thread.currentThread().getName();
log.println("--" + _message + " | Thread: " + threadName);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的变量threadName是一个局部变量。 每个线程都会存在一个实例,更准确地说,每个函数调用都会存在一个实例。这意味着它们不会互相影响。
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说的:这个日志字段是什么?确保它是线程安全的,否则您将看到混合的日志消息。
Emphasizing what Marcus said above: what is this log field? Make sure it is thread safe or you will see mixed up log messages.