-2

I am getting a big memory leak from char. This is not my writing and I am not good at cleaning up memory so help would be appreciated. This class uses char so I will start with it.

package server.util;

import java.text.NumberFormat;

import org.jboss.netty.buffer.ChannelBuffer;

public class Misc {

    public static String getRS2String(final ChannelBuffer buf) {
        final StringBuilder bldr = new StringBuilder();
        byte b;
        while (buf.readable() && (b = buf.readByte()) != 10)
            bldr.append((char) b);
        return bldr.toString();
    }

    public static double randomDouble(double min, double max) {
        return (Math.random() * (max - min) + min);
    }

    public static String formatPlayerName(String str) {
        str = ucFirst(str);
        str.replace("_", " ");
        return str;
    }

    public static int getCurrentHP(int i, int i1, int i2) {
        double x = (double) i / (double) i1;
        return (int) Math.round(x * i2);
    }

    public static String removeSpaces(String s) {
        return s.replace(" ", "");
    }

    public static String capitalize(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (i == 0) {
                s = String.format("%s%s", Character.toUpperCase(s.charAt(0)),
                        s.substring(1));
            }
            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format("%s%s%s", s.subSequence(0, i + 1),
                            Character.toUpperCase(s.charAt(i + 1)),
                            s.substring(i + 2));
                }
            }
        }
        return s;
    }

    public static boolean goodDistance(int objectX, int objectY, int playerX,
            int playerY, int distance) {
        return ((objectX - playerX <= distance && objectX - playerX >= -distance) && (objectY
                - playerY <= distance && objectY - playerY >= -distance));
    }

    public static int distanceToPoint(int pointX, int pointY, int pointX2, int pointY2) {
        return (int) Math.sqrt(Math.pow(pointX2 - pointX, 2)
                + Math.pow(pointY2 - pointY, 2));
    }

    public static String longToReportPlayerName(long l) {
        int i = 0;
        final char ac[] = new char[12];
        while (l != 0L) {
            final long l1 = l;
            l /= 37L;
            ac[11 - i++] = Misc.playerNameXlateTable[(int) (l1 - l * 37L)];
        }
        return new String(ac, 12 - i, i);
    }

    public static String longToPlayerName(long l) {
        int i = 0;
        char ac[] = new char[12];

        while (l != 0L) {
            long l1 = l;

            l /= 37L;
            ac[11 - i++] = xlateTable[(int) (l1 - l * 37L)];
        }
        return new String(ac, 12 - i, i);
    }

    public static final char playerNameXlateTable[] = { '_', 'a', 'b', 'c',
            'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
            'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '[', ']', '/', '-', ' ' };

    public static String longToPlayerName2(long l) {
        int i = 0;
        char ac[] = new char[99];
        while (l != 0L) {
            long l1 = l;
            l /= 37L;
            ac[11 - i++] = playerNameXlateTable[(int) (l1 - l * 37L)];
        }
        return new String(ac, 12 - i, i);
    }

    public static String format(int num) {
        return NumberFormat.getInstance().format(num);
    }

    public static String ucFirst(String str) {
        str = str.toLowerCase();
        if (str.length() > 1) {
            str = str.substring(0, 1).toUpperCase() + str.substring(1);
        } else {
            return str.toUpperCase();
        }
        return str;
    }

    public static void print_debug(String str) {
        System.out.print(str);
    }

    public static void println_debug(String str) {
        System.out.println(str);
    }

    public static void print(String str) {
        System.out.print(str);
    }

    public static void println(String str) {
        System.out.println(str);
    }

    public static String Hex(byte data[]) {
        return Hex(data, 0, data.length);
    }

    public static String Hex(byte data[], int offset, int len) {
        String temp = "";
        for (int cntr = 0; cntr < len; cntr++) {
            int num = data[offset + cntr] & 0xFF;
            String myStr;
            if (num < 16)
                myStr = "0";
            else
                myStr = "";
            temp += myStr + Integer.toHexString(num) + " ";
        }
        return temp.toUpperCase().trim();
    }

    public static int hexToInt(byte data[], int offset, int len) {
        int temp = 0;
        int i = 1000;
        for (int cntr = 0; cntr < len; cntr++) {
            int num = (data[offset + cntr] & 0xFF) * i;
            temp += num;
            if (i > 1)
                i = i / 1000;
        }
        return temp;
    }

    public static String basicEncrypt(String s) {
        String toReturn = "";
        for (int j = 0; j < s.length(); j++) {
            toReturn += (int) s.charAt(j);
        }
        // System.out.println("Encrypt: " + toReturn);
        return toReturn;
    }

    /**
     * 
     * @param range - range of random number
     * @return from 1 to specified range number
     */
    public static int random2(int range) {
        return (int) ((java.lang.Math.random() * range) + 1);
    }

    /**
     * 
     * @param range - range from 0 to specified range
     * @return from 0 to specified range
     */
    public static int random(int range) {
        return (int) (java.lang.Math.random() * (range + 1));
    }

    public static long playerNameToInt64(String s) {
        long l = 0L;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            l *= 37L;
            if (c >= 'A' && c <= 'Z')
                l += (1 + c) - 65;
            else if (c >= 'a' && c <= 'z')
                l += (1 + c) - 97;
            else if (c >= '0' && c <= '9')
                l += (27 + c) - 48;
        }
        while (l % 37L == 0L && l != 0L)
            l /= 37L;
        return l;
    }

    private static char decodeBuf[] = new char[4096];

    public static String textUnpack(byte packedData[], int size) {
        int idx = 0, highNibble = -1;
        for (int i = 0; i < size * 2; i++) {
            int val = packedData[i / 2] >> (4 - 4 * (i % 2)) & 0xf;
            if (highNibble == -1) {
                if (val < 13)
                    decodeBuf[idx++] = xlateTable[val];
                else
                    highNibble = val;
            } else {
                decodeBuf[idx++] = xlateTable[((highNibble << 4) + val) - 195];
                highNibble = -1;
            }
        }

        return new String(decodeBuf, 0, idx);
    }

    public static String optimizeText(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (i == 0) {
                s = String.format("%s%s", Character.toUpperCase(s.charAt(0)),
                        s.substring(1));
            }
            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format("%s%s%s", s.subSequence(0, i + 1),
                            Character.toUpperCase(s.charAt(i + 1)),
                            s.substring(i + 2));
                }
            }
        }
        return s;
    }

    public static void textPack(byte packedData[], java.lang.String text) {
        if (text.length() > 80)
            text = text.substring(0, 80);
        text = text.toLowerCase();

        int carryOverNibble = -1;
        int ofs = 0;
        for (int idx = 0; idx < text.length(); idx++) {
            char c = text.charAt(idx);
            int tableIdx = 0;
            for (int i = 0; i < xlateTable.length; i++) {
                if (c == xlateTable[i]) {
                    tableIdx = i;
                    break;
                }
            }
            if (tableIdx > 12)
                tableIdx += 195;
            if (carryOverNibble == -1) {
                if (tableIdx < 13)
                    carryOverNibble = tableIdx;
                else
                    packedData[ofs++] = (byte) (tableIdx);
            } else if (tableIdx < 13) {
                packedData[ofs++] = (byte) ((carryOverNibble << 4) + tableIdx);
                carryOverNibble = -1;
            } else {
                packedData[ofs++] = (byte) ((carryOverNibble << 4) + (tableIdx >> 4));
                carryOverNibble = tableIdx & 0xf;
            }
        }

        if (carryOverNibble != -1)
            packedData[ofs++] = (byte) (carryOverNibble << 4);
    }

    public static char xlateTable[] = { ' ', 'e', 't', 'a', 'o', 'i', 'h', 'n',
            's', 'r', 'd', 'l', 'u', 'm', 'w', 'c', 'y', 'f', 'g', 'p', 'b',
            'v', 'k', 'x', 'j', 'q', 'z', '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', ' ', '!', '?', '.', ',', ':', ';', '(', ')', '-',
            '&', '*', '\\', '\'', '@', '#', '+', '=', '\243', '$', '%', '"',
            '[', ']' };

    public static int direction(int srcX, int srcY, int x, int y) {
        double dx = (double) x - srcX, dy = (double) y - srcY;
        double angle = Math.atan(dy / dx);
        angle = Math.toDegrees(angle);
        if (Double.isNaN(angle))
            return -1;
        if (Math.signum(dx) < 0)
            angle += 180.0;
        return (int) ((((90 - angle) / 22.5) + 16) % 16);
    }

    public static byte directionDeltaX[] = new byte[] { 0, 1, 1, 1, 0, -1, -1,
            -1 };
    public static byte directionDeltaY[] = new byte[] { 1, 1, 0, -1, -1, -1, 0,
            1 };
    public static byte xlateDirectionToClient[] = new byte[] { 1, 2, 4, 7, 6,
            5, 3, 0 };
}
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Aleksandr
  • 29
  • 6
  • You don't manage memory in java. The only thing you can change is how often collection is done I believe. – jgr208 Sep 29 '14 at 17:04
  • why not use asci or unicode ? – Kick Buttowski Sep 29 '14 at 17:04
  • 1
    Where is this leaking memory, and how do you know? – Elliott Frisch Sep 29 '14 at 17:06
  • two things : 1) your code is WAY too long, noone will read it. 2) there is no such thing like "memory leak" with java. Its impossible. Thats a memory leak : http://en.wikipedia.org/wiki/Memory_leak – specializt Sep 29 '14 at 17:06
  • 4
    @specializt actually it is possible. However the only way to stop one is to change the code since you can not manage the memory. – jgr208 Sep 29 '14 at 17:07
  • Yes, you do manage memory in Java and there are memory leaks in Java. By referencing no longer used objects, you can create memory leaks of any size. – Codo Sep 29 '14 at 17:07
  • @Codo you can't manage memory. You don't control the collection with malloc and unmalloc. – jgr208 Sep 29 '14 at 17:10
  • Actually there is no memory leak in char, just uses up too much memory that is all. Thanks for your swift replies people. – Aleksandr Sep 29 '14 at 17:10
  • lol ... that link simply shows how one can store and access invalid references which will yield a NullPointerException. Sorry but that guy doesnt know what hes talking about. Read the wikipedia-article, please - it will enlighten you. Once more : It is impossible to generate memory leaks with languages like java; by design. – specializt Sep 29 '14 at 17:13
  • 1
    @specializt http://java.dzone.com/articles/java-memory-leak http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java http://www.oracle.com/technetwork/java/javase/memleaks-137499.html even oracle tells you how to trouble shoot them. – jgr208 Sep 29 '14 at 17:16
  • even if you post it three times in a row, it wont change the fact that these arent memory leaks. Memory leaks are fields which CANT BE ACCESSED and are NOT FREED. Every field is accessible in java, at least within its own scope - memleaks are only possible if you can actually ISOLATE MEMORY - via memory-pointers in C, for example. Java frees every field which is isolated / inaccessible. – specializt Sep 29 '14 at 17:19
  • @specializt However, automatic memory management can impose a performance overhead, and it does not eliminate all of the programming errors that cause memory leaks. – jgr208 Sep 29 '14 at 17:20
  • you cant "cause" them in any way in java, but yes : the GC will be unable to keep up if your code is extremely faulty. Thats the case with every algorithm in every language under any circumstance. – specializt Sep 29 '14 at 17:22
  • 1
    @specializt Memory leaks also encompass bugs wherein objects that are stale and no longer wanted stick around because an unintentional strong reference is kept around somewhere. – chrylis -cautiouslyoptimistic- Sep 29 '14 at 17:23
  • sorry, no. Im gonna go with the wikipedia-definition because its the one everyone uses and also the one i would come up with. If you can access it in _ANY_ way its not a memory leak - your GC may be able to catch up if you dont overdo it. – specializt Sep 29 '14 at 17:25
  • Thanks for the switch replies. I have checked visualvm for a 12 hour run and it actually utilizes too much memory that is all. – Aleksandr Sep 29 '14 at 17:11
  • 1
    This argument isn't really going any place productive, so I've cleaned it up. If you wish to carry this on, may I suggest you do so in a chat room? – Brad Larson Sep 29 '14 at 17:31
  • @BradLarson yes I concur. – jgr208 Sep 29 '14 at 17:31
  • 3
    @specializt [Here's an interesting question/answer](http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java). – Sotirios Delimanolis Sep 29 '14 at 17:32
  • @BradLarson these comments could do with _more_ cleanup - it's mostly nonsense. – Boris the Spider Sep 29 '14 at 22:31

1 Answers1

0

Please, note that substring method may be the cause for leaks.

substring method in String class causes memory leak

This is 'feature' is fixed in java 7u6

Community
  • 1
  • 1
kemenov
  • 409
  • 4
  • 13