英文:
Are primitive types shared between threads in Java?
问题
我正在运行一个SpringBoot 2.0的Web应用,我的控制器调用我的单例类如下:
@RestController
public class MyCallerClass{
private int count=0;
@PutMapping(/test)
incrementCount()
{
increaseCount()
}
}
如果我有一个如下所示的单例类
@Component
public class MyClass{
private int count=0;
@async
increaseCount()
{
count++;
}
}
我首先有一个疑问,即RestController本身是否是多线程的,即控制器的多个实例是否存在以共享负载,还是所有调用只会路由到一个RestController的实例?
其次,由于increaseCount()方法将以异步方式(已注解为async)由控制器调用,一个线程写入**原始**变量count的值是否对其他线程可见,还是所有线程只会写入自己的局部副本?
英文:
I am running a SpringBoot 2.0 webapp my controller calls my singleton class as follows:
@RestController
public class MyCallerClass{
private int count=0;
@PutMapping(/test)
incrementCount()
{
increaseCount()
}
}
If I have a singleton class like below
@Component
public class MyClass{
private int count=0;
@async
increaseCount()
{
count++;
}
}
The first doubt I have is that will the RestController itself be multithreaded, i.e. multiple instance of the controller will exist to share the load or will all calls route to only one instance of the rest controller?
Second, As the increaseCount() method will be called in a async (its annotated as async) way by the controller, will the values written by one thread to the primitive variable count be visible to other threads or will all threads only write to its local copy?
答案1
得分: 1
如果您正在使用默认的Spring行为,那么这些类是不线程安全的。Spring默认情况下,bean是在整个应用程序中被注入的单例实例。所有路由到您的控制器的请求都将发送到那个单一实例。
是的,它们将对其他线程可见,但实际值的准确性不能得到保证。对于其原子性没有保证。考虑对变量进行同步写访问(在某些情况下会降低性能),或者如果该值是“只读”的,则将其设置为volatile。
您还可以考虑使用AtomicInteger。
英文:
If you are using the default Spring behavior, then those classes are not thread-safe. Spring beans by default are singleton instances that are injected throughout your application. All requests routed to your controller will go to that single instance.
Yes, they will be visible to other threads but the actual value is not guaranteed to be accurate. There is no guarantee as to its atomicity. Consider synchronizing write access to the variable (will degrade performance in certain circumstances) or if the value is 'read-only' make it volatile.
You might also want to consider using an AtomicInteger
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论