J2EE Bad Practices: Direct Use of Threads

Thread management in a Web application is forbidden in some circumstances and is always highly error prone.


Description

Thread management in a web application is forbidden by the J2EE standard in some circumstances and is always highly error prone. Managing threads is difficult and is likely to interfere in unpredictable ways with the behavior of the application container. Even without interfering with the container, thread management usually leads to bugs that are hard to detect and diagnose like deadlock, race conditions, and other synchronization errors.

Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

In the following example, a new Thread object is created and invoked directly from within the body of a doGet() method in a Java servlet.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


  // Perform servlet tasks.
  ...

  // Create a new thread to handle background processing.
  Runnable r = new Runnable() {

    public void run() {


      // Process and store request statistics.
      ...

    }

  };

  new Thread(r).start();

}

See Also

Comprehensive Categorization: Poor Coding Practices

Weaknesses in this category are related to poor coding practices.

SFP Secondary Cluster: Use of an Improper API

This category identifies Software Fault Patterns (SFPs) within the Use of an Improper API cluster (SFP3).

7PK - Time and State

This category represents one of the phyla in the Seven Pernicious Kingdoms vulnerability classification. It includes weaknesses related to the improper management of t...

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.

Weaknesses in Software Written in Java

This view (slice) covers issues that are found in Java programs that are not common to all languages.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.