服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

is it a problem on regex or static

i have met a problem, which will seriously cause jvm problem.

i try to build a class to solve string operation with regular expression (java.util.regex.*)

i define all the method as a static one, thus i can use the class to parse string without a instance. but when i use the method many times, just found the memory is quickly exhausted. ( i use java -verbose:gc to observe the status). finally , i focus on the return type of the method, i directly return the string with "m.group(1)" (m is a instance of java.util.regex.matcher). is it a problem of regex or static or both? i didn't know the answer.

the original code are:

    public static string getfirstgroup(string regex, string original) {
            pattern p = pattern.compile(regex, pattern.case_insensitive);
            matcher m = p.matcher(original);
            if (m.find()) {
                    string result = m.group(1);
                   m = null;
                   return result;
            } else {
                      return "";
             }
    }
the strange thing is when i use is to parse one same string for many times, on problem occurs.

then i make some change:

    public static string getfirstgroup(string regex, string original) {
            pattern p = pattern.compile(regex, pattern.case_insensitive);
            matcher m = p.matcher(original);
            if (m.find()) {
                    string result = new string(m.group(1));
                   m = null;
                   return result;
            } else {
                      return "";
             }
    }
the problem disappeared. so i confused with the problem.

may be it is a problem on static,  i will have a try later.  may be there still be a refernce in matcher, i will try to read the code of regex. anyway, if you know the answer, we may have a talk.

扫描关注微信公众号