Search code examples
javamultithreadingspring-bootsingletonprototype

How @prototype scope helps in multithreading


I was given a single threaded application and asked to make it multithreaded. There are many singleton instances used.

I know that when a singleton instance is shared between multiple threads, all the variables of that instance will be shared between multiple threads.

For example, there is a count variable, it is a singleton instance variable. My idea is that each thread should increment the 'count' .Each thread increments only once. So the counter should be 1. If I increment this variable of the shared object, all the threads will get that value. So when the 2nd thread does it, the value will not be 1, but 2. For the nth thread that increments it, the value it sees will be n, not 1.

Inorder to prevent this, I used a prototype scope on that class. Now I will get a new object for each thread and the counter will remain 1 for each thread.

This is how I thought I would use prototype scope. Does this makes sense? I gave an example for counter, there are many, many such variables of different types in that shared instance. Is my use of prototype justified?


Solution

  • You can use a local variable for the above-said purpose, it doesn't have to be an instance variable.

    In order to prevent this, I used a prototype scope on that class. Now I will get a new object for each thread and the counter will remain 1 for each thread.

    This is how I thought I would use prototype scope. Does this makes sense?

    This makes sense, but only thing is, I don't see a case for an instance variable, as I said before, you can easily pull this off with a local variable. Be careful with a prototype scoped bean injected into a singleton scoped bean. Spring Prototype scoped bean in a singleton