Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread-Safety problem #2

Open
jingglang opened this issue Jul 16, 2021 · 1 comment
Open

Thread-Safety problem #2

jingglang opened this issue Jul 16, 2021 · 1 comment

Comments

@jingglang
Copy link

jingglang commented Jul 16, 2021

Hi,
I use your example in my project but I found emf.getCurrentTenantIdentifierResolver() always returns the same instance. It is not thread safe since multiple racing threads might change the value of MultiTenantResolver.tenantIdentifier before calling emf.createEntityManager(). So to make it thread-safe, I use synchronized method to replace MultiTenantResolver.setTenantIdentifier() method to something like:

public class MultiTenantResolver implements CurrentTenantIdentifierResolver {
...
   public synchronized EntityManager createEntityManagerWithThreadSafety(String tenantIdentifier, EntityManagerFactory emf) {
      this.tenantIdentifier = tenantIdentifier;
      return emf.createEntityManager();
   }
...
}

Please let me know if you find a problem with my solution or if you have a better solution.

Thank you for this github project and your article. It saved me a lot of hours.

@rhuan080
Copy link
Owner

Hi,

Thank you for sharing it with me. I don't see any issue with your solution. Feel free to send a PR to solve that.

Maybe to a complete solution, we can set the tenantIdentifier as volatile as well. Look at this example:


public abstract class MuiltitenancyResolver implements CurrentTenantIdentifierResolver {

    protected volatile String tenantIdentifier;

    public synchronized void setTenantIdentifier(String tenantIdentifier) {
        this.tenantIdentifier = tenantIdentifier;
    }
}

Let me know what do you think about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants