简体   繁体   中英

Are primitive types shared between threads in Java?

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, ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM