DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. How to Kill Java with a Regular Expression

How to Kill Java with a Regular Expression

Andreas Haufler user avatar by
Andreas Haufler
·
Sep. 24, 13 · Interview
Like (0)
Save
Tweet
Share
7.07K Views

Join the DZone community and get the full member experience.

Join For Free

We recently stumbled upon a phenomen we absolutely weren't aware of: You can kill any Java IDE and also any Java process with a simple regular expression ...

Back in university, I was taught that regular expressions, which are called regular grammars or type 3 grammars, always end up in a finite state automaton and can therefore be processed in linear time (input length doubles, processing time doubles). However, that's only true for "sane" expressions. A regular expression can also result in an non-deterministic finite state automaton and things can get messed up quite badly.

Consider the expression (0*)*A. This is any number of zeros, followed by an upper case A. Now, if you use Matcher.find() for this expression, everything is fine as long as there is a match in the input. However, if you call this with "00000000000000000000" as input, your program will hang (and so will the regex console in Eclipse or IntelliJ and every Java-based online regex service).

What at first glance looks like an infinite loop turns out to be catastrophic backtracking. What this basically means is that the matcher detects that no A was found at the end of the input. Now the outer quantifier goes one step back, the inner one forward, and again, no result. Therefore, the matcher goes back step by step and tries all combinations to find a match. It will eventually return (without a match), but the complexity (and therefore the runtime) of this is exponential (adding one character to the input doubles the runtime). A detailed description can be found in this article on catastrophic backtracking.

Here are some runtimes I measured (which almost exactly double for each character added):

0000000000: 0.1ms
00000000000: 0.2ms
000000000000: 0.7ms
0000000000000: 1.3ms
00000000000000: 1.7ms
000000000000000: 3.5ms
0000000000000000: 7.2ms
00000000000000000: 13.9ms
000000000000000000: 27.5ms
0000000000000000000: 55.5ms
00000000000000000000: 113.0ms
000000000000000000000: 226.4ms
0000000000000000000000: 439.1ms
00000000000000000000000: 886.0ms

As a little side-note: For micro benchmarks like this, you always need to "warm" up the JVM, as the HotSpot JIT will jump in at some point and optimize the code. Therefore, the first run looks like this:

0000000000: 6.8ms
00000000000: 11.8ms
000000000000: 25.5ms
0000000000000: 39.5ms
00000000000000: 6.3ms  <- JIT jumped in and started to translate
000000000000000: 5.4ms  to native code.
0000000000000000: 7.1ms

00000000000000000: 14.2ms
000000000000000000: 26.8ms
0000000000000000000: 54.4ms
00000000000000000000: 109.6ms
000000000000000000000: 222.1ms
0000000000000000000000: 439.2ms
00000000000000000000000: 885.6ms

So, what's the take-away here? If you're running a server application or anything critical used by many users, don't let them enter regular expressions unless you really trust them. There are regex implementations that detect this problem and abort, but Java (up to JDK 8) doesn't.

Note: You can test this with your local IDE or a small Java program to your heart's content, but please don't start to knock out all the regex tester websites out there. Those guys provide a nice tool free of charge, so it would be quite unfair.

Here is the tiny benchmark I used:

public class Test {
  public static void main(String[] args) {
    for (int runs = 0; runs < 2; runs++) {
      Pattern pattern = Pattern.compile("(0*)*A");
      // Run from 5 to 25 characters
      for (int length = 5; length < 25; length++) {
        // Build input of specified length
  	String input = "";
  	for (int i = 0; i < length; i++) { input += "0"; }
          // Measure the average duration of two calls... 
  	  long start = System.nanoTime();
 	  for (int i = 0; i < 2; i++) {
	    pattern.matcher(input).find();
          }
          System.out.println(input + ": " 
            + ((System.nanoTime() - start) / 2000000d) 
            + "ms");
        }
      }
    }
  }
} 


Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Shift-Left: A Developer's Pipe(line) Dream?
  • Automated Testing With Jasmine Framework and Selenium
  • Public Key and Private Key Pairs: Know the Technical Difference
  • Unlock the Power of Terragrunt’s Hierarchy

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: