简体   繁体   English

如何避免类java的相同实例多次运行

[英]How to avoid a same instance of class java is running many times

I have class named: ReceiptGenerateAgentDAO receiptGenerateAgentDAO = new ReceiptGenerateAgentDAO(); 我的类名为:ReceiptGenerateAgentDAO receiveGenerateAgentDAO = new ReceiptGenerateAgentDAO(); this class will be called from a jsp page, which has a method and in that i have a for loop which will execute for more then 5 min and the issue is I request the jsp to call the class and the class started executing,now i reload the jsp and again call the class now both the class are running it is not a thread,how it is possible and how to resolve it? 这个类将从一个有方法的jsp页面中调用,因为我有一个for循环,它将执行5分钟以上,而问题是我请求jsp调用该类,并且该类开始执行,现在我重新加载jsp并再次调用该类,现在这两个类都在运行,它不是线程,怎么可能以及如何解决?

for (String Key : list) {
        if (!"userDetailsCache".equals(Key)) {
            preparedStatement2.setString(1, Key);
            @Cleanup
            ResultSet rsCreditReceipt = preparedStatement2.executeQuery();
            if (rsCreditReceipt.next()
                    && rsCreditReceipt.getString("SUMMARY_DATE") != null) {
                String exBalance = rsCreditReceipt.getString("balance");
                /** Agent Current Balance */
                preparedStatement3.setString(1,
                        rsCreditReceipt.getString("SUMMARY_DATE"));
                preparedStatement3.setString(2, Key);
                @Cleanup
                ResultSet rsCreditBal = preparedStatement3.executeQuery();
                double creditDebit = Double.parseDouble(exBalance);
                if (rsCreditBal.next()) {
                    if (rsCreditBal.getString("creditdebit") != null) {
                        creditDebit += Double.parseDouble(rsCreditBal
                                .getString("creditdebit"));
                    }
                }
                if (creditDebit < 0) {
                    Element element = EhcacheManager.getUserDetailsCache()
                            .get(Key);
                    UserDetails details = (UserDetails) element
                            .getObjectValue();
                    /** Agent Opening Balance */
                    getZoneDetails(details, connection);
                    receiptGenerateTempDTOs.add(new ReceiptGenerateTempDTO(
                            details.getTerritoryId(), details
                                    .getSatelliteId(), details.getZoneId(),
                            rsCreditReceipt.getString(3),
                            NumericConstants.ZERO, String.valueOf(formatter
                                    .format((creditDebit * (-1)))), time,
                            receiptGenerateAgentDTO.getSelectedUserId(),
                            NumericConstants.ZERO));
                }
            } else {
                /** If no opening balance,only current Balance */
                preparedStatement4.setString(1, Key);
                @Cleanup
                ResultSet rsCreditBal = preparedStatement4.executeQuery();
                if (rsCreditBal.next()) {
                    Element element = EhcacheManager.getUserDetailsCache()
                            .get(Key);
                    UserDetails details = (UserDetails) element
                            .getObjectValue();
                    getZoneDetails(details, connection);
                    receiptGenerateTempDTOs
                            .add(new ReceiptGenerateTempDTO(
                                    details.getTerritoryId(),
                                    details.getSatelliteId(),
                                    details.getZoneId(),
                                    details.getUserId(),
                                    NumericConstants.ZERO,
                                    String.valueOf(formatter.format((Double.parseDouble(rsCreditBal
                                            .getString("creditdebit")) * (-1)))),
                                    time, receiptGenerateAgentDTO
                                            .getSelectedUserId(),
                                    NumericConstants.ZERO));
                }
            }
        }
        System.out.println(i++);
    }

You could use the Singleton Pattern to create a class which will have only one instance : 您可以使用Singleton Pattern创建一个仅包含一个实例的类:

public class Singleton {
private static Singleton instance = null;

private Singleton() {
    // Is private to be not accessible
}

public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
}

The if you want to call a method of the singleton class, use : Singleton.getInstance.someMethod() . 如果要调用singleton类的方法,请使用: Singleton.getInstance.someMethod()

Can be solved in many ways.. 可以用很多方法解决。

Method 1 : 方法1:

Change the scope of the class to session Scope. 将该类的范围更改为会话范围。 By this your class will not be Garbage collected after every request. 这样,您的课程将不会在每次请求后被收集。 The Class object will be kept until the session expires. Class对象将一直保留到会话期满为止。


Method 2: 方法2:

Change the scope of the class to Singleton. 将类的范围更改为Singleton。 By this you will be creating just one object for the entire user session. 这样,您将只为整个用户会话创建一个对象。 You can do this in these steps. 您可以在以下步骤中执行此操作。

Step 1: Create a static Object of the class, and initialize it with a null value 步骤1:创建该类的静态对象,并使用空值对其进行初始化

Private Static ClassName staticClassName=null;

Step 2: Block the constructor so that ClassName obj= new ClassName() wont get you a new Object. 步骤2:阻止构造函数,以使ClassName obj = new ClassName()不会为您带来新的对象。

private ClassName() {....}

Step 3 Create another method findClassObject() that return the object of the class 步骤3创建另一个方法findClassObject(),该方法返回类的对象

public static ClassName findClassObject(){
if(staticClassName==null){
staticClassName= new ClassName() ; //since the constructor method is called from within the class, it returns a new Object of the Class ClassName
}
return staticClassName;
}

Setp 4 Setp 4

Initialize the class Object using this, which will always return the same object. 使用此方法初始化Object类,它将始终返回相同的对象。

ClassName obj= ClassName.findClassObject();

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

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