简体   繁体   English

Java Web App中每个用户的单例对象

[英]Singleton object per user in java web app

My Enterprise application requires an Singleton ShoppingCart object(per user),this cart object should not be technically static(which may lead to memory leak). 我的企业应用程序需要一个Singleton ShoppingCart对象(每个用户),此购物车对象在技术上不应是静态的(可能导致内存泄漏)。

do i need to make changes to the code (or) apply any pattern to the web application, to achieve singleton per user? 我是否需要对代码进行更改(或)将任何模式应用于Web应用程序,以实现每个用户的单身?

public final class ShoppingCartSingleTon {

    private static ShoppingCartSingleTon instance = null;

    private ShoppingCartSingleTon() {}

    public static ShoppingCartSingleTon getInstance() {
        if (instance == null) {
            synchronized(ShoppingCartSingleTon.class) {
                if (instance == null) {
                    instance = new ShoppingCartSingleTon();
                }
            }
        }
        return instance;
    }
}

A cart is usually stored in the session of the user. 购物车通常存储在用户会话中。 So the cart should be SessionScoped or ViewScoped. 因此,购物车应为SessionScoped或ViewScoped。

You can include it via injection (cdi, autowired, ...). 您可以通过注入(cdi,自动装配等)将其包括在内。 Spring and JavaEE have these well documented. Spring和JavaEE已对此进行了详细记录。

In a Web Application where multiple users can access the backend nothing should be static except explicitly wanted. 在多个用户可以访问后端的Web应用程序中,除非明确需要,否则什么都不应是静态的。 It may cause massive synchronization and concurrency problems. 这可能会导致大量的同步和并发问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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