简体   繁体   中英

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

I have class named: ReceiptGenerateAgentDAO receiptGenerateAgentDAO = 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?

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 :

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() .

Can be solved in many ways..

Method 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.


Method 2:

Change the scope of the class to 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

Private Static ClassName staticClassName=null;

Step 2: Block the constructor so that ClassName obj= new ClassName() wont get you a new Object.

private ClassName() {....}

Step 3 Create another method findClassObject() that return the object of the class

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

Initialize the class Object using this, which will always return the same object.

ClassName obj= ClassName.findClassObject();

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