0

Well, I´m going to try to explain this problem in the better way I can, this is my first job after the university, I start like JR java programmer and my first task is update a large project, this project works fine, they only need a log in each method that saves all the important steps in a text file. Basically the project is, an HSM hardware that provides public keys, with that keys the users can encrypt and decrypt data, digest data, verify certificates and others methods across a socket that is running when the app is installed in the server, I added a loger to each method, but at the moment that we release the app, the app consumes most of the memory and the app does not release the memory, memory increases every time more. For the loger I utilized print writter, and I am not free to program like a I would wish and im not authorized to modify all the code, my first solution was open a local print writer variable in each method then add a try-catch for all the instructions in the method and the catch close obligatory the print I think this is the best solution but the director told me that the print writer have to be send like parameter at the moment that is invoked, this is the class that accept the petitions:

I´m sure that I close all the prints because I can see the result in the log, so I don´t know where is the problem, I tried to create the print in the method and fail, I tried to close the print in the catch clauses, it closes but the memory continues growing. With a few petitions the app consume 5 MB, and the app is supposed to receive much more petitions every day! Here is the class that accept petitions, first process the data sent by user and create the connection with the BD, then with a ID given by the DB create a log for that petition, each log file has one unique ID, if the method returns a good request "satisfactorio", the file is renamed with one "s" at the end, my duty is only add a log, i cant modify other things, but if you tell me what can I do I can tell my director where the code is wrong and modify it.

public class TProcess extends Thread {    
private java.net.Socket socket = null;
public static java.security.PrivateKey InePrivateKey = null;
public static java.security.cert.X509Certificate IneCertificate = null;
public static String NameServer = "Server1";
public static java.security.Provider HmsProvider = null;
public static com.ncipher.km.nfkm.SecurityWorld SecurityWord = null;
public static TKeyProperties[] KeysProperties = null;
public static int[] Modules = null;
public static String PathLog = "";
    public static String PathLicense = "";
    public static String ActiveLog = "";
    public static String TimeLapse = "";
public static String HsmCardName = "";
public static String HsmFilter = "";
public static String HsmModules = "";   
public static String UrlServerCertificates = "";
@Override 
public void run() {
java.io.PrintWriter writer = null;
TStores stores = new TStores ();

    //TUtil util = new TUtil ();
    java.io.ObjectOutputStream objectOutputStream = null;
    try {
        this.socket.setKeepAlive (false);
        java.io.ObjectInputStream objectInputStream = new java.io.ObjectInputStream(this.socket.getInputStream ());
        Object[] data = (Object[])objectInputStream.readObject (); //Lee los datos enviados desde el cliente
        Class instance = TImplementation.class;
        Object object = instance.newInstance ();
        System.out.println("Datos enviados " + data.length);
                    System.out.println("ID al inicio de Tstores es " + stores.Transfer);
        Class[] paramsTypes = new Class[data.length + 0x01];
        Object[] params = new Object[data.length + 0x01];

        params[0x00] = stores;
        params[0x01] = writer;
        paramsTypes[0x00] = TStores.class;
        paramsTypes[0x01] = java.io.PrintWriter.class;

        String methodName = data[0x00].toString ();
        //util.SaveInfoLog ("Metodo: " + methodName);

        for (int n = 2; n < params.length; n++) {
            paramsTypes[n] = data[n - 1].getClass();
            params[n] = data[n - 1];
            System.out.println ("pos: " + n + " value: " + params[n] + " :: " + paramsTypes[n]);
        }

                    identify(stores, methodName, params[2].toString(), params[3].toString(), params[4].toString(), params[5].toString());

                    if(TProcess.ActiveLog.equals("not")){
                        writer = new java.io.PrintWriter(new java.io.FileOutputStream(TProcess.PathLog+" "));
                    }else{
                        writer = new java.io.PrintWriter(new java.io.FileOutputStream(TProcess.PathLog+"Bitacora"+stores.Transfer+".log"));
                    }  
                    params[0x01] = writer;

                    java.lang.reflect.Method method = instance.getDeclaredMethod(methodName, paramsTypes);
        Object[] response = (Object[])method.invoke(object, params);
                    if(response[0x01].equals("Satisfactorio") && TProcess.ActiveLog.equals("not")){
                        java.io.File file = new java.io.File(TProcess.PathLog+"Bitacora"+stores.Transfer+".log");
                        file.delete();
                    }
                    if(response[0x01].equals("Satisfactorio") && TProcess.ActiveLog.equals("yes")){
                        java.io.File file = new java.io.File(TProcess.PathLog+"Bitacora"+stores.Transfer+".log");
                        java.io.File Newfile = new java.io.File(TProcess.PathLog+"Bitacora"+stores.Transfer+"s"+".log");
                        file.renameTo(Newfile);   
                    }

        objectOutputStream = new java.io.ObjectOutputStream(this.socket.getOutputStream());
        objectOutputStream.writeObject(response);
                    stores.CloseConnection();
                    stores = null;
        objectOutputStream.close();

    } catch (Exception ee) {
        //util.SaveWarningLog ("General " + ee.toString () + ee.getLocalizedMessage());
        try {
            objectOutputStream = new java.io.ObjectOutputStream (this.socket.getOutputStream ());
            objectOutputStream.writeObject (new Object[]{-99, "El método solicitado no existe"});
        } catch (Exception ae) { ae.toString (); }
    }
    try {writer.close(); writer=null; } catch (Exception ee) { System.out.println(ee.toString()); }
    try {objectOutputStream.close(); } catch (Exception ee) { ee.toString (); }
    try { this.socket.close(); } catch (Exception ee) {ee.toString (); }
    this.socket = null;
}

    private void identify(TStores stores, String methodName, String entity, String user, String password, String reference){

        if(methodName.equals("EncryptData")){
         stores.PwsTransferRg(entity, user, password, "s006", reference, TProcess.NameServer);
        } if(methodName.equals("DecryptData")){
           stores.PwsTransferRg(entity, user, password, "s008", reference, TProcess.NameServer);
        } if(methodName.equals("VerifyDataPkcs1")){
           stores.PwsTransferRg(entity, user, password, "u031", reference, TProcess.NameServer);
        } if(methodName.equals("GeneratePkcs10")){
           stores.PwsTransferRg(entity, user, password, "u032", reference, TProcess.NameServer);
        } if(methodName.equals("SignDataPkcs1")){
           stores.PwsTransferRg(entity, user, password, "u032", reference, TProcess.NameServer);
        } if(methodName.equals("CheckConsistency")){
           stores.PwsTransferRg(entity, user, password, "s002", reference, TProcess.NameServer);
        } if(methodName.equals("EncryptDataExternal")){
           stores.PwsTransferRg(entity, user, password, "s007", reference, TProcess.NameServer);
        } if(methodName.equals("RequestOcsp")){
            stores.PwsTransferRg(entity, user, password, "s002", reference, TProcess.NameServer);
        } if(methodName.equals("RequestTimeStamping")){
            stores.PwsTransferRg(entity, user, password, "s003", reference, TProcess.NameServer);
        } if(methodName.equals("VerifyTimeStamping")){
            stores.PwsTransferRg(entity, user, password, "s012", reference, TProcess.NameServer);
        } if(methodName.equals("RequestOcspTorrent")){
            stores.PwsTransferRg(entity, user, password, "s002", reference, TProcess.NameServer);
        } if(methodName.equals("VerifyDataPkcs1Torrent")){
           stores.PwsTransferRg(entity, user, password, "u031", reference, TProcess.NameServer);
        } if(methodName.equals("VerifyDataPkcs1Torrent")){
           stores.PwsTransferRg(entity, user, password, "u031", reference, TProcess.NameServer);
        } if(methodName.equals("GetCertificateTorrent")){
           stores.PwsTransferRg(entity, user, password, "u031", reference, TProcess.NameServer);
        }          
    }  
    }     

And this is a method with a Log implemented

public Object[] EncryptData(TStores stores, PrintWriter writer, String        entity, String user, String password, String reference, String idRsa, byte[] data, Integer algorithm) {
        TUtil util = new TUtil("EncryptData: " + entity + "," + user + "," + reference + "," + idRsa + "," + data.length + "," + algorithm);           
        //Object[] result = stores.PwsTransferRg(entity, user, password, "s006", reference, TProcess.NameServer);
        System.out.println("en la prueba con encryptdata");
        Object result [];

        writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                + new Throwable().getStackTrace()[0].getLineNumber());
        writer.println(TLogFunctions.info + "Estoy entrando al método");
        writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                + new Throwable().getStackTrace()[0].getLineNumber());
        writer.println(TLogFunctions.info + "DEL USUARIO");
        writer.println("Obteniendo datos de usuario\nEntidad " + entity + "\nUsuario " + user + "\nReferencia " + reference + "\nIDRSA: " + idRsa);
        writer.println(TLogFunctions.info + "DEL USUARIO");

        int state = (Integer) stores.state;
        if (state != 0x00) {
            writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                    + new Throwable().getStackTrace()[0].getLineNumber());
            writer.println(TLogFunctions.severe + "PwsTransferRg: " +stores.des);
            writer.println("//////////////////////////////////////////////////");
            writer.close();
            return stores.PwsTransferEstadoRgExt(state, "PwsTransferRg: " + stores.des, "");
        }

        writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                + (new Throwable().getStackTrace()[0].getLineNumber() + 4));
        writer.println(TLogFunctions.warning + "Entrando al dispositivo Thales");

        byte[] dataEncrypted = null;
        TSecure secure = new TSecure();
        TThales thales = new TThales();
        if ((algorithm == 0x0b) || (algorithm == 0x0c)) {
            com.ncipher.km.nfkm.Key general = thales.GetGeneral(TProcess.KeysProperties, idRsa);
            if (general == null) {
                writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                        + new Throwable().getStackTrace()[0].getLineNumber());
                writer.println(TLogFunctions.severe + "GetGeneral: No se ha podido obtener la Llave");
                writer.println("//////////////////////////////////////////////////");
                writer.close();
                return stores.PwsTransferEstadoRgExt(-0x07, "GetGeneral: No se ha podido obtener la Llave", "");
            }

            try {
                dataEncrypted = secure.EncryptSimetric(general, data, algorithm);
            } catch (Exception ee) {
                writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                        + new Throwable().getStackTrace()[0].getLineNumber());
                writer.println(TLogFunctions.severe + "Encrypt: No se ha Encriptado la información");
                writer.println("//////////////////////////////////////////////////");
                writer.close();
                return stores.PwsTransferEstadoRgExt(-0x06, "Encrypt: No se ha Encriptado la informacion", ee.toString());
            }
        } else {
            writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                    + new Throwable().getStackTrace()[0].getLineNumber());
            writer.println(TLogFunctions.severe + "Algoritmo " + algorithm);
            java.security.PublicKey publicKey = thales.GetPublicKey(TProcess.KeysProperties, idRsa);
            if (publicKey == null) {
                writer.println(TLogFunctions.severe + "GetPublicKey: No se ha podido obtener la Llave Pública\n" + "Estado " + -0x07);
                writer.println("//////////////////////////////////////////////////");
                writer.close();
                return stores.PwsTransferEstadoRgExt(-0x07, "GetPublicKey: No se ha podido obtener la Llave Publica", "");
            }

            try {
                dataEncrypted = secure.Encrypt(publicKey, data, algorithm);
            } catch (Exception ee) {
                writer.println(TLogFunctions.severe + "Encrypt: No se ha Encriptado la información \n" + ee.toString());
                writer.println("//////////////////////////////////////////////////");
                writer.close();
                return stores.PwsTransferEstadoRgExt(-0x06, "Encrypt: No se ha Encriptado la informacion", ee.toString());
            }

        }

        writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                + (new Throwable().getStackTrace()[0].getLineNumber() + 2));
        result = stores.PpoProcCifraHsmRg(idRsa, data, dataEncrypted, algorithm, ".");
        state = (Integer) result[0x00];
        if (state != 0x00) {
            writer.println(TLogFunctions.severe + "PpoProcCifraHsmRg: " + result[0x01].toString() + result[0x02].toString());
            writer.println("//////////////////////////////////////////////////");
            writer.close();
            return stores.PwsTransferEstadoRgExt(state, "PpoProcCifraHsmRg: " + result[0x01].toString(), result[0x02].toString());
        }

        String b64DataEncrypted = util.BinToBase64(dataEncrypted);
        util.SaveInfoLog("BinToBase64: " + b64DataEncrypted);
        writer.println(TLogFunctions.date() + new Throwable().getStackTrace()[0].getMethodName() + " Line "
                + (new Throwable().getStackTrace()[0].getLineNumber() - 2));
        writer.println(TLogFunctions.warning + "Satisfactorio:\n " + b64DataEncrypted);
        writer.println("//////////////////////////////////////////////////"); 
        writer.close();
        stores.CloseConnection();
        return stores.PwsTransferEstadoRgExt(0x00, "Satisfactorio", b64DataEncrypted);
}

Print writer is sent by parameter and is closed when in the class TProcess, I am sure that the file is closed because all that I want to save is in the log file

I cant see the memory when increases in the server because the server is located in another place, they only told me the problem with the memory, but I did a memory test in my lap and its true the memory is not released,

Is my first job and I really want to do my best work but I am trying to resolve this problem one month and I´m working only for two months (I am on trial for two months), surely I`m not going to conserve this job but at least I want to resolve this. I accept all the help that you can provide me, I have tried many solutions and the state of the memory is always the same, please excuse me for my bad English.

  • 2
    Use a profiler (like [jProfiler](https://stackoverflow.com/questions/40119/how-to-find-a-java-memory-leak?rq=1)) to see where your memory is going - and comment your code – Benjamin Urquhart Apr 23 '19 at 23:09
  • Your strategy of writing the exception log to the socket is deeply flawed. If the exception was on the socket, that will also fail and you will have no idea what the original exception was. Log it locally. Your code is too large to post here. Cut it down to an example that still leaks, if indeed this leaks at all, which isn't clear. – user207421 Apr 23 '19 at 23:48

0 Answers0