language large_string | page_id int64 | page_url large_string | chapter int64 | section int64 | rule_id large_string | title large_string | intro large_string | noncompliant_code large_string | compliant_solution large_string | risk_assessment large_string | breadcrumb large_string |
|---|---|---|---|---|---|---|---|---|---|---|---|
java | 88,487,848 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487848 | 2 | 15 | SEC01-J | Do not allow tainted variables in privileged blocks | Do not operate on unvalidated or
untrusted data
(also known as
tainted data
) in a privileged block. An attacker can supply malicious input that could result in privilege escalation attacks. Appropriate mitigations include hard coding values rather than accepting arguments (when appropriate) and validating or
sanitizin... | private void privilegedMethod(final String filename)
throws FileNotFoundException {
try {
FileInputStream fis =
(FileInputStream) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public FileInputStream run() throws FileNotFoundException {
... | private void privilegedMethod(final String filename)
throws FileNotFoundException {
final String cleanFilename;
try {
cleanFilename = cleanAFilenameAndPath(filename);
} catch (/* exception as per spec of cleanAFileNameAndPath */) {
// Log or forward to handler as appropriate... | ## Risk Assessment
Allowing tainted inputs in privileged operations can result in privilege escalation attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC01-J
High
Likely
No
No
P9
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,773 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487773 | 2 | 15 | SEC02-J | Do not base security checks on untrusted sources | Security checks based on untrusted sources can be bypassed. Any untrusted object or argument must be defensively copied before a security check is performed. The copy operation must be a deep copy; the implementation of the
clone()
method may produce a shallow copy, which can still be compromised. In addition, the impl... | public RandomAccessFile openFile(final java.io.File f) {
askUserPermission(f.getPath());
// ...
return (RandomAccessFile)AccessController.doPrivileged(new PrivilegedAction <Object>() {
public Object run() {
return new RandomAccessFile(f, f.getPath());
}
});
}
public class BadFile extends java.io.... | public RandomAccessFile openFile(java.io.File f) {
final java.io.File copy = new java.io.File(f.getPath());
askUserPermission(copy.getPath());
// ...
return (RandomAccessFile)AccessController.doPrivileged(new PrivilegedAction <Object>() {
public Object run() {
return new RandomAccessFile(copy, copy.ge... | ## Risk Assessment
Basing security checks on untrusted sources can result in the check being bypassed.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC02-J
High
Probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,677 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487677 | 2 | 15 | SEC03-J | Do not load trusted classes after allowing untrusted code to load arbitrary classes | The Java classes used by a program are not necessarily loaded upon program startup. Many Java Virtual Machines (JVMs) load classes only when they need them.
If untrusted code is permitted to load classes, it may possess the ability to load a malicious class. This is a class that shares a fully-qualified name with a ben... | protected static Digester webDigester = null;
if (webDigester == null) {
webDigester = createWebDigester();
}
// This method exists in the class DigesterFactory and is called by
// ContextConfig.createWebXmlDigester().
// which is in turn called by ContextConfig.createWebDigester()
// webDigester finally contains ... | protected static final Digester webDigester = init();
protected Digester init() {
Digester digester = createWebDigester();
// Does not use the context Classloader at initialization
digester.getParser();
return digester;
}
## Compliant Solution (Tomcat)
In this compliant solution, Tomcat initializes the
SAXPa... | ## Risk Assessment
Allowing untrusted code to load classes enables untrusted code to replace benign classes with Trojan classes.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC03-J
high
probable
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,883 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487883 | 2 | 15 | SEC04-J | Protect sensitive operations with security manager checks | Sensitive operations must be protected by security manager checks. | class SensitiveHash {
private Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
public void removeEntry(Object key) {
ht.remove(key);
}
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) { // Check whether file may be read
sm.checkRead("/local/schema.dtd");
}
## Noncompli... | class SensitiveHash {
private Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
public void removeEntry(Object key) {
check("removeKeyPermission");
ht.remove(key);
}
private void check(String directive) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
s... | ## Risk Assessment
Failure to enforce security checks in code that performs sensitive operations can lead to malicious tampering of sensitive data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC04-J
High
Probable
No
Yes
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,674 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487674 | 2 | 15 | SEC05-J | Do not use reflection to increase accessibility of classes, methods, or fields | Reflection enables a Java program to analyze and modify itself. In particular, a program can discover the values of field variables and change them [
Forman 2005
], [
Sun 2002
]. The Java reflection API includes a method that enables fields that are normally inaccessible to be accessed under reflection. The following c... | class FieldExample {
private int i = 3;
private int j = 4;
public String toString() {
return "FieldExample: i=" + i + ", j=" + j;
}
public void zeroI() {
this.i = 0;
}
public void zeroField(String fieldName) {
try {
Field f = this.getClass().getDeclaredField(fieldName);
// Subse... | class FieldExample {
// ...
private void zeroField(String fieldName) {
// ...
}
}
class FieldExample {
// ...
public void zeroField(String fieldName) {
// ...
}
public void zeroI() {
this.i = 0;
}
public void zeroJ() {
this.j = 0;
}
}
package Safe;
public class Trusted {
Trust... | ## Risk Assessment
Misuse of APIs that perform language access checks only against the immediate caller can break data encapsulation, leak sensitive information, or permit privilege escalation attacks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC05-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,867 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487867 | 2 | 15 | SEC06-J | Do not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar | Code should be signed only if it requires elevated privileges to perform one or more tasks (see
for more information). For example, applets are denied the privilege of making HTTP connections to any hosts except the host from which they came. When an applet requires an HTTP connection with an external host to download ... | public class JarRunner {
public static void main(String[] args)
throws IOException, ClassNotFoundException,
NoSuchMethodException, InvocationTargetException {
URL url = new URL(args[0]);
// Create the class loader for the application jar file
JarClassLoader cl = new JarClassLo... | jarsigner -verify signed-updates-jar-file.jar
public void invokeClass(String name, String[] args)
throws ClassNotFoundException, NoSuchMethodException,
InvocationTargetException, GeneralSecurityException,
IOException {
Class c = loadClass(name);
Certificate[] certs =
c.getProtecti... | ## Risk Assessment
Failure to verify a digital signature, whether manually or programmatically, can result in the execution of malicious code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC06-J
High
Probable
No
No
P6
L2
Automated Detection
Automated detection is not feasible in the fully general case... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,701 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487701 | 2 | 15 | SEC07-J | Call the superclass's getPermissions() method when writing a custom class loader | When a custom class loader must override the
getPermissions()
method, the implementation must consult the default system policy by explicitly invoking the superclass's
getPermissions()
method before assigning arbitrary permissions to the code source. A custom class loader that ignores the superclass's
getPermissions()
... | protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = new Permissions();
// Allow exit from the VM anytime
pc.add(new RuntimePermission("exitVM"));
return pc;
}
## Noncompliant Code Example
This noncompliant code example shows a fragment of a custom class loader that extends ... | protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
// Allow exit from the VM anytime
pc.add(new RuntimePermission("exitVM"));
return pc;
}
## Compliant Solution
In this compliant solution, the
getPermissions()
method calls
super.getPermissions()
.... | ## Risk Assessment
Failure to consult the default system policy while defining a custom class loader violates the tenets of defensive programming and can result in classes defined with unintended permissions.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SEC07-J
High
Probable
Yes
No
P12
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 15. Platform Security (SEC) |
java | 88,487,526 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487526 | 3 | 15 | SEC50-J | Avoid granting excess privileges | A Java security policy grants permissions to code to allow access to specific system resources. A
code source
(an object of type
CodeSource
), to which a permission is granted, consists of the code location (URL) and a reference to the certificate(s) containing the public key(s) corresponding to the private key(s) used... | private FileInputStream openFile() {
final FileInputStream f[] = { null };
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("file");
} catch(FileNotFoundException fnf) {
// Forward to handler
}
return null;
... | private FileInputStream openFile(AccessControlContext context) {
if (context == null) {
throw new SecurityException("Missing AccessControlContext");
}
final FileInputStream f[] = { null };
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
try {
f[0] =... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,896 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487896 | 3 | 15 | SEC51-J | Minimize privileged code | Programs must comply with the principle of least privilege not only by providing privileged blocks with the minimum permissions required for correct operation (see
) but also by ensuring that privileged code contains
only
those operations that require increased privileges. Superfluous code contained within a privileged... | public void changePassword(String currentPassword, String newPassword) {
final FileInputStream f[] = { null };
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
String passwordFile = System.getProperty("user.dir") + File.separator + "PasswordFileName... | public void changePassword(String currentPassword, String newPassword) {
final FileInputStream f[] = { null };
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
String passwordFile = System.getProperty("user.dir") + File.separator + "PasswordFileName";
... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,466 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487466 | 3 | 15 | SEC52-J | Do not expose methods that use reduced-security checks to untrusted code | Most methods lack security manager checks because they do not provide access to sensitive parts of the system, such as the file system. Most methods that do provide security manager checks verify that every class and method in the call stack is authorized before they proceed. This security model allows restricted progr... | public void load(String libName) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
System.loadLibrary(libName);
return null;
}
});
}
public Connection getConnection(String url, String username, String password) {
// ...
return DriverManager.getConnection(url, ... | private void load() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
System.loadLibrary("awt");
return null;
}
});
}
private String url = // Hardwired value
public Connection getConnection(String username, String password) {
// ...
return DriverManager.getCo... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,519 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487519 | 3 | 15 | SEC53-J | Define custom security permissions for fine-grained security | The default
SecurityManager
checks whether the caller of a particular method has sufficient permissions to proceed with an action. An action is defined in Java's security architecture as a level of access and requires certain permissions before it can be performed. For Example, the actions for
java.io.FilePermission
ar... | class LoadLibrary {
private void loadLibrary() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
// Privileged code
System.loadLibrary("myLib.so");
// Perform some sensitive operation like setting the default exception handler
MyExceptionReporter.... | class LoadLibrary {
private void loadLibrary() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
// Privileged code
System.loadLibrary("myLib.so");
// Perform some sensitive operation like setting the default exception handler
MyExceptionReporter... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,523 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487523 | 3 | 15 | SEC54-J | Create a secure sandbox using a security manager | According to the Java API
Class
SecurityManager
documentation [
API 2014
],
The security manager is a class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted ... | java LocalJavaApp
try {
System.setSecurityManager(null);
} catch (SecurityException se) {
// Cannot set security manager, log to file
}
## Noncompliant Code Example (Command-Line Installation)
This noncompliant code example fails to install any security manager from the command line. Consequently, the program run... | java -Djava.security.manager -Djava.security.policy=policyURL \
LocalJavaApp
java -Djava.security.manager=my.security.CustomManager ...
java -Djava.security.manager \
-Djava.security.policy==policyURL \
LocalJavaApp
appletviewer -J-Djava.security.manager \
-J-Djava.security.policy==policy... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,340 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487340 | 3 | 15 | SEC55-J | Ensure that security-sensitive methods are called with validated arguments | Application code that calls security-sensitive methods must validate the arguments being passed to the methods. In particular,
null
values may be interpreted as benign by certain security-sensitive methods but may override default settings. Although security-sensitive methods should be coded defensively, the client cod... | AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() {
// ...
}
}, accessControlContext);
## Noncompliant Code Example
This noncompliant code example shows the two-argument
doPrivileged()
method that takes an access control context as the second argument. This code restores... | if (accessControlContext == null) {
throw new SecurityException("Missing AccessControlContext");
}
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() {
// ...
}
}, accessControlContext);
## Compliant Solution
## This compliant solution prevents granting of excess privil... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,509 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487509 | 3 | 15 | SEC56-J | Do not serialize direct handles to system resources | Serialized objects can be altered outside of any Java program unless they are protected using mechanisms such as sealing and signing. (See
ENV01-J. Place all security-sensitive code in a single JAR and sign and seal it
.) If an object referring to a system resource becomes serialized, and an attacker can alter the seri... | final class Ser implements Serializable {
File f;
public Ser() throws FileNotFoundException {
f = new File("c:\\filepath\\filename");
}
}
## Noncompliant Code Example
## This noncompliant code example declares a serializableFileobject in the classSer:
#FFcccc
final class Ser implements Serializable {
Fi... | final class Ser {
File f;
public Ser() throws FileNotFoundException {
f = new File("c:\\filepath\\filename");
}
}
final class Ser implements Serializable {
transient File f;
public Ser() throws FileNotFoundException {
f = new File("c:\\filepath\\filename");
}
}
## Compliant Solution (Not... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,559 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487559 | 3 | 15 | SEC57-J | Do not let untrusted code misuse privileges of callback methods | Callbacks provide a means to register a method to be invoked (or
called
back)
when an interesting event occurs. Java uses callbacks for applet and servlet life-cycle events, AWT and Swing event notifications such as button clicks, asynchronous reads and writes to storage, and even in
Runnable.run()
wherein a new thread... | public interface CallBack {
void callMethod();
}
class UserLookupCallBack implements CallBack {
private int uid;
private String name;
public UserLookupCallBack(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void callMethod() {
try (InputStream fis = new Fil... | public interface CallBack {
void callMethod();
}
class UserLookupCallBack implements CallBack {
private int uid;
private String name;
public UserLookupCallBack(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void callMethod() {
AccessController.doPrivile... | null | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,380 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487380 | 3 | 15 | SEC58-J | Deserialization methods should not perform potentially dangerous operations | A
Serializable
class can overload the
readObject()
method, which is called when an object of that class is being deserialized. Both this method and the
readResolve()
method should refrain from performing potentially dangerous operations.
A class that performs dangerous operations in the constructor must not be
Seriali... | null | import java.io.*;
class OpenedFile implements Serializable {
String filename;
BufferedReader reader;
boolean isInitialized;
public OpenedFile(String filename) {
this.filename = filename;
isInitialized = false;
}
public void init() throws FileNotFoundException {
reader = new BufferedReader(new... | ## Risk Assessment
The severity of violations of this rule depend on the nature of the potentially dangerous operations performed. If only mildly dangerous operations are performed, the risk might be limited to denial-of-service (DoS) attacks. At the other extreme, remote code execution is possible if attacker-suppli... | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 15. Platform Security (SEC) |
java | 88,487,786 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487786 | 2 | 14 | SER00-J | Enable serialization compatibility during class evolution | Once an object of a particular class has been serialized, future refactoring of the class's code often becomes problematic. Specifically, existing serialized forms (encoded representations) become part of the object's published API and must be supported for an indefinite period. This can be troublesome from a security ... | class GameWeapon implements Serializable {
int numOfWeapons = 10;
public String toString() {
return String.valueOf(numOfWeapons);
}
}
## Noncompliant Code Example
This noncompliant code example implements a
GameWeapon
class with a serializable field called
numOfWeapons
and uses the default serialized f... | class GameWeapon implements Serializable {
private static final long serialVersionUID = 24L;
int numOfWeapons = 10;
public String toString() {
return String.valueOf(numOfWeapons);
}
}
class WeaponStore implements Serializable {
int numOfWeapons = 10; // Total number of weapons
}
public class Game... | ## Risk Assessment
Failure to provide a consistent serialization mechanism across releases can limit the extensibility of classes. If classes are extended, compatibility issues may result.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER00-J
Low
Probable
Yes
Yes
P6
L2
Automated Detection
Automated dete... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,769 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487769 | 2 | 14 | SER01-J | Do not deviate from the proper signatures of serialization methods | Classes that require special handling during object serialization and deserialization must implement special methods with exactly the following signatures [
API 2014
]:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ... | public class Ser implements Serializable {
private final long serialVersionUID = 123456789;
private Ser() {
// Initialize
}
public static void writeObject(final ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
public static void readObject(final ObjectInputStream s... | private void writeObject(final ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
private void readObject(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
class Extendable implements Serializable {
protected Object rea... | ## Risk Assessment
Deviating from the proper signatures of serialization methods can lead to unexpected behavior. Failure to limit the accessibility of the
readObject()
and
writeObject()
methods can leave code vulnerable to untrusted invocations. Declaring
readResolve()
and
writeReplace()
methods to be static or privat... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,792 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487792 | 2 | 14 | SER02-J | Sign then seal objects before sending them outside a trust boundary | Sensitive data
must be protected from eavesdropping. All data that crosses a trust boundary must be protected from malicious tampering. An obfuscated transfer object [
Steel 2005
] that is strongly encrypted can protect data. This approach is known as
sealing
the object. To guarantee object integrity, apply a digital s... | class SerializableMap<K,V> implements Serializable {
final static long serialVersionUID = -2648720192864531932L;
private Map<K,V> map;
public SerializableMap() {
map = new HashMap<K,V>();
}
public Object getData(K key) {
return map.get(key);
}
public void setData(K key, V data) {
map.pu... | public static void main(String[] args)
throws
IOException, GeneralSecurityException,
ClassNotFoundException {
// Build map
SerializableMap<String, Integer> map = buildMap();
// Generate signing public/private key pair & sign map
KeyPairGenerator kpg = K... | ## Risk Assessment
Failure to sign and then seal objects during transit can lead to loss of object integrity or confidentiality.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER02-J
Medium
Probable
No
No
P4
L3
Automated Detection
This rule is not amenable to static analysis in the general case.
Tool
Ve... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,718 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487718 | 2 | 14 | SER03-J | Do not serialize unencrypted sensitive data | Although serialization allows an object's state to be saved as a sequence of bytes and then reconstituted at a later time, it provides no mechanism to protect the serialized data. An attacker who gains access to the serialized data can use it to discover sensitive information and to determine implementation details of ... | public class Point implements Serializable {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
// No-argument constructor
}
}
public class Coordinates extends Point {
public static void main(String[] args) {
FileOutputStrea... | public class Point implements Serializable {
private transient double x; // Declared transient
private transient double y; // Declared transient
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
// No-argument constructor
}
}
public class Coordinates extends Point {
public ... | ## Risk Assessment
If sensitive data can be serialized, it may be transmitted over an insecure connection, stored in an insecure location, or disclosed inappropriately.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER03-J
Medium
Likely
No
No
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,891 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487891 | 2 | 14 | SER04-J | Do not allow serialization and deserialization to bypass the security manager | Serialization and deserialization features can be exploited to bypass security manager checks. A serializable class may contain security manager checks in its constructors for various reasons, including preventing
untrusted code
from modifying the internal state of the class. Such security manager checks must be replic... | public final class Hometown implements Serializable {
// Private internal state
private String town;
private static final String UNKNOWN = "UNKNOWN";
void performSecurityManagerCheck() throws AccessDeniedException {
// ...
}
void validateInput(String newCC) throws InvalidInputException {
// ...
... | public final class Hometown implements Serializable {
// ... All methods the same except the following:
// writeObject() correctly enforces checks during serialization
private void writeObject(ObjectOutputStream out) throws IOException {
performSecurityManagerCheck();
out.writeObject(town);
}
// rea... | ## Risk Assessment
Allowing serialization or deserialization to bypass the security manager may result in classes being constructed without required security checks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER04-J
High
Probable
Yes
Yes
P18
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,781 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487781 | 2 | 14 | SER05-J | Do not serialize instances of inner classes | "An inner class is a nested class that is not explicitly or implicitly declared static" [
JLS 2015
]. Serialization of inner classes (including local and anonymous classes) is error prone. According to the Serialization Specification [
Sun 2006
]:
Serializing an inner class declared in a non-static context that contain... | public class OuterSer implements Serializable {
private int rank;
class InnerSer implements Serializable {
protected String name;
// ...
}
}
## Noncompliant Code Example
In this noncompliant code example, the fields contained within the outer class are serialized when the inner class is serialized:
#FFcc... | public class OuterSer implements Serializable {
private int rank;
class InnerSer {
protected String name;
// ...
}
}
public class OuterSer implements Serializable {
private int rank;
static class InnerSer implements Serializable {
protected String name;
// ...
}
}
## Compliant Solution
## ... | ## Risk Assessment
Serialization of inner classes can introduce platform dependencies and can cause serialization of instances of the outer class.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER05-J
Medium
Likely
Yes
No
P12
L1
Automated Detection
Detection of inner classes that implement serialization... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,790 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487790 | 2 | 14 | SER06-J | Make defensive copies of private mutable components during deserialization | Every serializable class that has private mutable instance variables must defensively copy them in the
readObject()
method. An attacker can tamper with the serialized form of such a class, appending extra references to the byte stream. When deserialized, this byte stream could allow the creation of a class instance who... | class MutableSer implements Serializable {
private static final Date epoch = new Date(0);
private Date date = null; // Mutable component
public MutableSer(Date d){
date = new Date(d.getTime()); // Constructor performs defensive copying
}
private void readObject(ObjectInputStream ois) throws IOExceptio... | private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = ois.readFields();
Date inDate = (Date) fields.get("date", epoch);
// Defensively copy the mutable component
date = new Date(inDate.getTime());
// Perform validation if necessary
}
#... | ## Risk Assessment
Failure to defensively copy mutable components during deserialization can violate the immutability contract of an object.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER06-J
Low
Probable
Yes
Yes
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,801 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487801 | 2 | 14 | SER07-J | Do not use the default serialized form for classes with implementation-defined invariants | Serialization can be used maliciously, for example, to violate the intended
invariants
of a class. Deserialization is equivalent to object construction; consequently, all invariants enforced during object construction must also be enforced during deserialization. The default serialized form lacks any enforcement of cla... | public class NumberData extends Number {
// ... Implement abstract Number methods, like Number.doubleValue()...
private static final NumberData INSTANCE = new NumberData ();
public static NumberData getInstance() {
return INSTANCE;
}
private NumberData() {
// Perform security checks and parameter va... | public class NumberData extends Number {
// ...
protected final Object readResolve() throws NotSerializableException {
return INSTANCE;
}
}
public final class Lottery implements Serializable {
// ...
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOExcept... | ## Risk Assessment
Using the default serialized form for any class with implementation-defined
invariants
may result in the malicious tampering of class invariants.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER07-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,882 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487882 | 2 | 14 | SER08-J | Minimize privileges before deserializing from a privileged context | Unrestricted deserializing from a privileged context allows an attacker to supply crafted input that, upon deserialization, can yield objects that the attacker would otherwise lack permissions to construct. One example is the construction of a sensitive object such as a custom class loader. Consequently, avoid deserial... | class A { // Has Object as superclass
A(int x) { }
A() { }
}
class B extends A implements Serializable {
B(int x) { super(x); }
}
class C extends B {
C(int x) { super(x); }
}
try {
ZoneInfo zi = (ZoneInfo) AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throw... | private static class CalendarAccessControlContext {
private static final AccessControlContext INSTANCE;
static {
RuntimePermission perm =
new RuntimePermission("accessClassInPackage.sun.util.calendar");
PermissionCollection perms = perm.newPermissionCollection();
perms.add(perm);
... | ## Risk Assessment
Deserializing objects from an unrestricted privileged context can result in arbitrary code execution.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER08-J
High
Likely
Yes
No
P18
L1 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,910 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487910 | 2 | 14 | SER09-J | Do not invoke overridable methods from the readObject() method | The
readObject()
method must not call any overridable methods. Invoking overridable methods from the
readObject()
method can provide the overriding method with access to the object's state before it is fully initialized. This premature access is possible because, in deserialization,
readObject
plays the role of object ... | private void readObject(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
overridableMethod();
stream.defaultReadObject();
}
public void overridableMethod() {
// ...
}
## Noncompliant Code Example
## This noncompliant code example invokes an overridable method... | private void readObject(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
## Compliant Solution
This compliant solution removes the call to the overridable method. When removing such calls is infeasible, declare the method private or fi... | ## Risk Assessment
Invoking overridable methods from the
readObject()
method can lead to initialization errors.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER09-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,791 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487791 | 2 | 14 | SER10-J | Avoid memory and resource leaks during serialization | Serialization can extend the lifetime of objects, preventing their garbage collection. The
ObjectOutputStream
ensures that each object is written to the stream only once by retaining a reference (or handle) to each object written to the stream. When a previously written object is subsequently written to the stream agai... | class SensorData implements Serializable {
// 1 MB of data per instance!
...
public static SensorData readSensorData() {...}
public static boolean isAvailable() {...}
}
class SerializeSensorData {
public static void main(String[] args) throws IOException {
ObjectOutputStream out = null;
try {
... | class SerializeSensorData {
public static void main(String[] args) throws IOException {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream("ser.dat")));
while (SensorData.isAvailable()) {
// Note that each SensorData o... | ## Risk Assessment
Memory and resource leaks during serialization can result in a resource exhaustion attack or can crash the Java Virtual Machine.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER10-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,802 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487802 | 2 | 14 | SER11-J | Prevent overwriting of externalizable objects | Classes that implement the
Externalizable
interface must provide the
readExternal()
and
writeExternal()
methods. These methods have package-private or public access, and so they can be called by trusted and untrusted code alike. Consequently, programs must ensure that these methods execute only when intended and that t... | public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// Read instance fields
this.name = (String) in.readObject();
this.UID = in.readInt();
// ...
}
## Noncompliant Code Example
This noncompliant code example allows any caller to reset the value of... | private final Object lock = new Object();
private boolean initialized = false;
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
synchronized (lock) {
if (!initialized) {
// Read instance fields
this.name = (String) in.readObject();
t... | ## Risk Assessment
Failure to prevent the overwriting of an externalizable object can corrupt the state of the object.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
SER11-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,384 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487384 | 2 | 14 | SER12-J | Prevent deserialization of untrusted data | Deserializing untrusted data can cause Java to create an object of an arbitrary attacker-specified class, provided that the class is available on the classpath specified for the JVM. Some classes have triggers that execute additional code when they are created in this manner; see
for more information. If such classes... | null | import java.io.*;
import java.util.*;
class WhitelistedObjectInputStream extends ObjectInputStream {
public Set whitelist;
public WhitelistedObjectInputStream(InputStream inputStream, Set wl) throws IOException {
super(inputStream);
whitelist = wl;
}
@Override
protected Class<?> resolveClass(Objec... | ## Risk Assessment
Whether a violation of this rule is exploitable depends on what classes are on the JVM's classpath. (Note that this is a property of the execution environment, not of the code being audited.) In the worst case, it could lead to remote execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 14. Serialization (SER) |
java | 88,487,614 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487614 | 2 | 4 | STR00-J | Don't form strings containing partial characters from variable-width encodings | Character information in Java SE 8 is based on the Unicode Standard, version 6.2.0 [
Unicode 2012
]. A
Unicode transformation format
(UTF) is an algorithmic mapping from every Unicode code point (except surrogate code points) to a unique byte sequence. The Java platform uses the UTF-16 encoding in
char
arrays and in th... | public final int MAX_SIZE = 1024;
public String readBytes(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] data = new byte[MAX_SIZE+1];
int offset = 0;
int bytesRead = 0;
String str = new String();
while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {... | public final int MAX_SIZE = 1024;
public String readBytes(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] data = new byte[MAX_SIZE+1];
int offset = 0;
int bytesRead = 0;
while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
offset += bytesRead;
... | ## Risk Assessment
Forming strings from character data containing partial characters can result in data corruption.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR00-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 04. Characters and Strings (STR) |
java | 88,487,813 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487813 | 2 | 4 | STR01-J | Do not assume that a Java char fully represents a Unicode code point | The
char
data type is based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of
Unicode code point
s is now U+0000 to U+10FFFF. The set of charact... | public static String trim(String string) {
char ch;
int i;
for (i = 0; i < string.length(); i += 1) {
ch = string.charAt(i);
if (!Character.isLetter(ch)) {
break;
}
}
return string.substring(i);
}
## Noncompliant Code Example
## This noncompliant code example attempts to trim leading letter... | public static String trim(String string) {
int ch;
int i;
for (i = 0; i < string.length(); i += Character.charCount(ch)) {
ch = string.codePointAt(i);
if (!Character.isLetter(ch)) {
break;
}
}
return string.substring(i);
}
## Compliant Solution
This compliant solution corrects the problem ... | ## Risk Assessment
Forming strings consisting of partial characters can result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR01-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 04. Characters and Strings (STR) |
java | 88,487,907 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487907 | 2 | 4 | STR02-J | Specify an appropriate locale when comparing locale-dependent data | Using locale-dependent methods on locale-dependent data can produce unexpected results when the locale is unspecified. Programming language identifiers, protocol keys, and HTML tags are often specified in a particular locale, usually
Locale.ENGLISH
. Running a program in a different locale may result in unexpected prog... | public static void processTag(String tag) {
if (tag.toUpperCase().equals("SCRIPT")) {
return;
}
// Process tag
}
import java.io.*;
public class PrintMyself {
private static String inputFile = "PrintMyself.java";
private static String outputFile = "PrintMyself.txt";
public static void main(String[] a... | public static void processTag(String tag) {
if (tag.toUpperCase(Locale.ENGLISH).equals("SCRIPT")) {
return;
}
// Process tag
}
public static void processTag(String tag) {
Locale.setDefault(Locale.ENGLISH);
if (tag.toUpperCase().equals("SCRIPT")) {
return;
}
// Process tag
}
public static void p... | ## Risk Assessment
Failure to specify the appropriate locale when using locale-dependent methods on local-dependent data without specifying the appropriate locale may result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR02-J
Medium
Probable
No
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 04. Characters and Strings (STR) |
java | 88,487,609 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487609 | 2 | 4 | STR03-J | Do not encode noncharacter data as a string | Increasingly, programmers view strings as a portable means of storing and communicating arbitrary data, such as numeric values. For example, a real-world system stores the binary values of encrypted passwords as strings in a database. Noncharacter data may not be representable as a string, because not all bit patterns ... | BigInteger x = new BigInteger("530500452766");
byte[] byteArray = x.toByteArray();
String s = new String(byteArray);
byteArray = s.getBytes();
x = new BigInteger(byteArray);
## Noncompliant Code Example
This noncompliant code example attempts to convert a
BigInteger
value to a
String
and then restore it to a
BigIntege... | BigInteger x = new BigInteger("530500452766");
String s = x.toString(); // Valid character data
byte[] byteArray = s.getBytes();
String ns = new String(byteArray);
x = new BigInteger(ns);
BigInteger x = new BigInteger("530500452766");
byte[] byteArray = x.toByteArray();
String s = Base64.getEncoder().encodeToStrin... | ## Risk Assessment
Encoding noncharacter data as a string is likely to result in a loss of data integrity.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR03-J
Low
Unlikely
No
No
P1
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 04. Characters and Strings (STR) |
java | 88,487,847 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487847 | 2 | 4 | STR04-J | Use compatible character encodings when communicating string data between JVMs | A
character encoding
or
charset
specifies the binary representation of the coded character set. Every instance of the Java Virtual Machine (JVM) has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends on the loca... | FileInputStream fis = null;
try {
fis = new FileInputStream("SomeFile");
DataInputStream dis = new DataInputStream(fis);
byte[] data = new byte[1024];
dis.readFully(data);
String result = new String(data);
} catch (IOException x) {
// Handle error
} finally {
if (fis != null) {
try {
fis.close()... | FileInputStream fis = null;
try {
fis = new FileInputStream("SomeFile");
DataInputStream dis = new DataInputStream(fis);
byte[] data = new byte[1024];
dis.readFully(data);
String result = new String(data, "UTF-16LE");
} catch (IOException x) {
// Handle error
} finally {
if (fis != null) {
try {
... | ## Risk Assessment
Using incompatible encodings when communicating string data between JVMs can result in corrupted data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR04-J
Low
Unlikely
No
No
P1
L3
Automated Detection
Sound automated detection of this
vulnerability
is not feasible.
Tool
Version
Check... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 04. Characters and Strings (STR) |
java | 88,487,610 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487610 | 3 | 4 | STR50-J | Use the appropriate method for counting characters in a string | Character information in Java SE 8 is based on the Unicode Standard, version 6.2.0 [
Unicode 2012
]. However, Java programs must often work with string data represented in various character sets. Java 7 introduced the
StandardCharsets
Class that specifies character sets that are guaranteed to be available on every imp... | public final int MAX_SIZE = 1024;
public String readBytes(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] data = new byte[MAX_SIZE+1];
int offset = 0;
int bytesRead = 0;
String str = new String();
while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {... | public final int MAX_SIZE = 1024;
public String readBytes(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
byte[] data = new byte[MAX_SIZE+1];
int offset = 0;
int bytesRead = 0;
while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
offset += bytesRead;
... | ## Risk Assessment
Forming strings consisting of partial characters can result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR50-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 04. Characters and Strings (STR) |
java | 88,487,698 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487698 | 3 | 4 | STR51-J | Use the charset encoder and decoder classes when more control over the encoding process is required | String objects in Java are encoded in UTF-16. Java Platform is required to support other character encodings or charsets such as US-ASCII, ISO-8859-1, and UTF-8. Errors may occur when converting between differently coded character data. There are two general types of encoding errors. If the byte sequence is not valid... | import java.math.BigInteger;
import java.nio.CharBuffer;
public class CharsetConversion {
public static void main(String[] args) {
BigInteger x = new BigInteger("530500452766");
byte[] byteArray = x.toByteArray();
String s = new String(byteArray);
System.out.println(s);
}
}
## Noncompliant Code Ex... | import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnmappableCharacterException;
... | ## Risk Assessment
Malformed input or unmappable character errors can result in a loss of data integrity.
Rule
Severity
Likelihood
Remediation Cost
Priority
Level
STR51-J
low
unlikely
medium
P2
L3 | SEI CERT Oracle Coding Standard for Java > 3 Recommendations > Rec. 04. Characters and Strings (STR) |
java | 88,487,912 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487912 | 2 | 10 | THI00-J | Do not invoke Thread.run() | Thread startup can be misleading because the code can appear to be performing its function correctly when it is actually being executed by the wrong thread.
Invoking the
Thread.start()
method instructs the Java runtime to start executing the thread's
run()
method using the started thread. Invoking a
Thread
object's
run... | public final class Foo implements Runnable {
@Override public void run() {
// ...
}
public static void main(String[] args) {
Foo foo = new Foo();
new Thread(foo).run();
}
}
## Noncompliant Code Example
## This noncompliant code example explicitly invokesrun()in the context of the current thread:
#... | public final class Foo implements Runnable {
@Override public void run() {
// ...
}
public static void main(String[] args) {
Foo foo = new Foo();
new Thread(foo).start();
}
}
## Compliant Solution
## This compliant solution correctly uses thestart()method to tell the Java runtime to start a new th... | ## Risk Assessment
Failure to start threads correctly can cause unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI00-J
Low
Probable
Yes
Yes
P6
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,779 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487779 | 2 | 10 | THI01-J | Do not invoke ThreadGroup methods | Each thread in Java is assigned to a thread group upon the thread's creation. These groups are implemented by the
java.lang.ThreadGroup
class. When the thread group name is not specified explicitly, the
main
default group is assigned by the Java Virtual Machine (JVM) [
Java Tutorials
]. The convenience methods of the
T... | final class HandleRequest implements Runnable {
public void run() {
// Do something
}
}
public final class NetworkHandler implements Runnable {
private static ThreadGroup tg = new ThreadGroup("Chief");
@Override public void run() {
new Thread(tg, new HandleRequest(), "thread1").start();
new Thread... | public final class NetworkHandler {
private final ExecutorService executor;
NetworkHandler(int poolSize) {
this.executor = Executors.newFixedThreadPool(poolSize);
}
public void startThreads() {
for (int i = 0; i < 3; i++) {
executor.execute(new HandleRequest());
}
}
public void shutdown... | ## Risk Assessment
Use of the
ThreadGroup
APIs may result in
race conditions
, memory leaks, and inconsistent object state.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI01-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,729 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487729 | 2 | 10 | THI02-J | Notify all waiting threads rather than a single thread | Threads that invoke
Object.wait()
expect to wake up and resume execution when their
condition predicate
becomes true. To be compliant with
, waiting threads must test their condition predicates upon receiving notifications and must resume waiting if the predicates are false.
The
notify()
and
notifyAll()
methods of pack... | public final class ProcessStep implements Runnable {
private static final Object lock = new Object();
private static int time = 0;
private final int step; // Do Perform operations when field time
// reaches this value
public ProcessStep(int step) {
this.step = step;
}
@Overr... | // Declare class as final because its constructor throws an exception
public final class ProcessStep implements Runnable {
private static final Lock lock = new ReentrantLock();
private static int time = 0;
private final int step; // Perform operations when field time
// reaches this val... | ## Risk Assessment
Notifying a single thread rather than all waiting threads can violate the
liveness
property of the system.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI02-J
Low
Unlikely
No
Yes
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,699 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487699 | 2 | 10 | THI03-J | Always invoke wait() and await() methods inside a loop | The
Object.wait()
method temporarily cedes possession of a lock so that other threads that may be requesting the lock can proceed.
Object.wait()
must always be called from a
synchronized
block or method. The waiting thread resumes execution only after it has been notified, generally as the result of the invocation of t... | synchronized (object) {
if (<condition does not hold>) {
object.wait();
}
// Proceed when condition holds
}
## Noncompliant Code Example
This noncompliant code example invokes the
wait()
method inside a traditional
if
block and fails to check the postcondition after the notification is received. If the notif... | synchronized (object) {
while (<condition does not hold>) {
object.wait();
}
// Proceed when condition holds
}
## Compliant Solution
This compliant solution calls the
wait()
method from within a
while
loop to check the condition both before and after the call to
wait()
:
#ccccff
synchronized (object) {
while... | ## Risk Assessment
Failure to encase the
wait()
or
await()
methods inside a
while
loop can lead to indefinite blocking and
denial of service
(DoS).
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI03-J
Low
Unlikely
Yes
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,884 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487884 | 2 | 10 | THI04-J | Ensure that threads performing blocking operations can be terminated | Threads and tasks that block on operations involving network or file I/O must provide callers with an explicit termination mechanism to prevent
denial-of-service
(DoS)
vulnerabilities
. | // Thread-safe class
public final class SocketReader implements Runnable {
private final Socket socket;
private final BufferedReader in;
private volatile boolean done = false;
private final Object lock = new Object();
public SocketReader(String host, int port) throws IOException {
this.socket = new Soc... | public final class SocketReader implements Runnable {
// Other methods...
public void readData() throws IOException {
String string;
try {
while ((string = in.readLine()) != null) {
// Blocks until end of stream (null)
}
} finally {
shutdown();
}
}
public void shutdow... | ## Risk Assessment
Failure to provide facilities for thread termination can cause nonresponsiveness and
DoS
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI04-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,930 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487930 | 2 | 10 | THI05-J | Do not use Thread.stop() to terminate threads | Threads preserve class
invariants
when they are allowed to exit normally. Programmers often attempt to terminate threads abruptly when they believe the task is complete, the request has been canceled, or the program or Java Virtual Machine (JVM) must shut down expeditiously.
Certain thread APIs were introduced to facil... | public final class Container implements Runnable {
private final Vector<Integer> vector = new Vector<Integer>(1000);
public Vector<Integer> getVector() {
return vector;
}
@Override public synchronized void run() {
Random number = new Random(123L);
int i = vector.capacity();
while (i > 0) {
... | public final class Container implements Runnable {
private final Vector<Integer> vector = new Vector<Integer>(1000);
private volatile boolean done = false;
public Vector<Integer> getVector() {
return vector;
}
public void shutdown() {
done = true;
}
@Override public synchronized void run() {
... | ## Risk Assessment
Forcing a thread to stop can result in inconsistent object state. Critical resources could also leak if cleanup operations are not carried out as required.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
THI05-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 10. Thread APIs (THI) |
java | 88,487,862 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487862 | 2 | 11 | TPS00-J | Use thread pools to enable graceful degradation of service during traffic bursts | Many programs must address the problem of handling a series of incoming requests. One simple concurrency strategy is the Thread-Per-Message design pattern, which uses a new thread for each request [
Lea 2000a
]. This pattern is generally preferred over sequential executions of time-consuming, I/O-bound, session-based, ... | class Helper {
public void handle(Socket socket) {
// ...
}
}
final class RequestHandler {
private final Helper helper = new Helper();
private final ServerSocket server;
private RequestHandler(int port) throws IOException {
server = new ServerSocket(port);
}
public static RequestHandler newInst... | // class Helper remains unchanged
final class RequestHandler {
private final Helper helper = new Helper();
private final ServerSocket server;
private final ExecutorService exec;
private RequestHandler(int port, int poolSize) throws IOException {
server = new ServerSocket(port);
exec = Executors.newFix... | ## Risk Assessment
Using simplistic concurrency primitives to process an unbounded number of requests could result in severe performance degradation,
deadlock
, or system resource exhaustion and
DOS
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TPS00-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 11. Thread Pools (TPS) |
java | 88,487,727 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487727 | 2 | 11 | TPS01-J | Do not execute interdependent tasks in a bounded thread pool | Bounded thread pools allow the programmer to specify an upper limit on the number of threads that can concurrently execute in a thread pool. Programs must not use threads from a bounded thread pool to execute tasks that depend on the completion of other tasks in the pool.
A form of
deadlock
called
thread-starvation dea... | public final class ValidationService {
private final ExecutorService pool;
public ValidationService(int poolSize) {
pool = Executors.newFixedThreadPool(poolSize);
}
public void shutdown() {
pool.shutdown();
}
public StringBuilder fieldAggregator(String... inputs)
throws InterruptedException... | public final class ValidationService {
// ...
public StringBuilder fieldAggregator(String... inputs)
throws InterruptedException, ExecutionException {
// ...
for (int i = 0; i < inputs.length; i++) {
// Don't pass-in thread pool
results[i] = pool.submit(new ValidateInput<String>(inputs[i... | ## Risk Assessment
Executing interdependent tasks in a thread pool can lead to
denial of service
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TPS01-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 11. Thread Pools (TPS) |
java | 88,487,888 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487888 | 2 | 11 | TPS02-J | Ensure that tasks submitted to a thread pool are interruptible | Programs may submit
only
tasks that support interruption using
Thread.interrupt()
to thread pools that require the ability to shut down the thread pool or to cancel individual tasks within the pool. Programs must not submit tasks that lack interruption support to such thread pools. According to the Java API [
API 2014
... | public final class SocketReader implements Runnable { // Thread-safe class
private final Socket socket;
private final BufferedReader in;
private final Object lock = new Object();
public SocketReader(String host, int port) throws IOException {
this.socket = new Socket(host, port);
this.in = new Buffered... | public final class SocketReader implements Runnable {
private final SocketChannel sc;
private final Object lock = new Object();
public SocketReader(String host, int port) throws IOException {
sc = SocketChannel.open(new InetSocketAddress(host, port));
}
@Override public void run() {
ByteBuffer buf =... | ## Risk Assessment
Submitting tasks that are uninterruptible may prevent a thread pool from shutting down and consequently may cause
DoS
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TPS02-J
Low
Probable
No
No
P2
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 11. Thread Pools (TPS) |
java | 88,487,900 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487900 | 2 | 11 | TPS03-J | Ensure that tasks executing in a thread pool do not fail silently | All tasks in a thread pool must provide a mechanism for notifying the application if they terminate abnormally. Failure to do so cannot cause resource leaks because the threads in the pool are still recycled, but it makes failure diagnosis extremely difficult or impossible.
The best way to handle exceptions at the appl... | final class PoolService {
private final ExecutorService pool = Executors.newFixedThreadPool(10);
public void doSomething() {
pool.execute(new Task());
}
}
final class Task implements Runnable {
@Override public void run() {
// ...
throw new NullPointerException();
// ...
}
}
## Noncompliant... | final class PoolService {
// The values have been hard-coded for brevity
ExecutorService pool = new CustomThreadPoolExecutor(
10, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
// ...
}
class CustomThreadPoolExecutor extends ThreadPoolExecutor {
// ... Constructor ...
public CustomThr... | ## Risk Assessment
Failure to provide a mechanism for reporting that tasks in a thread pool failed as a result of an exceptional condition can make it difficult or impossible to diagnose the problem.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TPS03-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 11. Thread Pools (TPS) |
java | 88,487,860 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487860 | 2 | 11 | TPS04-J | Ensure ThreadLocal variables are reinitialized when using thread pools | The
java.lang.ThreadLocal<T>
class provides thread-local variables. According to the Java API [
API 2014
]:
These variables differ from their normal counterparts in that each thread that accesses one (via its
get
or
set
method) has its own, independently initialized copy of the variable.
ThreadLocal
instances are typic... | public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public final class Diary {
private static final ThreadLocal<Day> days =
new ThreadLocal<Day>() {
// Initialize to Monday
protected Day initialValue() {
return Day.MONDAY;
}
};
private static Day current... | public final class Diary {
// ...
public static void removeDay() {
days.remove();
}
}
public final class DiaryPool {
// ...
public void doSomething1() {
exec.execute(new Runnable() {
@Override public void run() {
try {
Diary.setDay(Day.FRIDAY);
diary.threa... | ## Risk Assessment
Objects using
ThreadLocal
data and executed by different tasks in a thread pool without reinitialization might be in an unexpected state when reused.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TPS04-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 11. Thread Pools (TPS) |
java | 88,487,811 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487811 | 2 | 12 | TSM00-J | Do not override thread-safe methods with methods that are not thread-safe | Overriding
thread-safe
methods with methods that are unsafe for concurrent use can result in improper
synchronization
when a client that depends on the thread-safety promised by the parent inadvertently operates on an instance of the subclass. For example, an overridden synchronized method's contract can be violated wh... | class Base {
public synchronized void doSomething() {
// ...
}
}
class Derived extends Base {
@Override public void doSomething() {
// ...
}
}
class Base {
private final Object lock = new Object();
public void doSomething() {
synchronized (lock) {
// ...
}
}
}
class Derived exten... | class Base {
public synchronized void doSomething() {
// ...
}
}
class Derived extends Base {
@Override public synchronized void doSomething() {
// ...
}
}
class Base {
public synchronized void doSomething() {
// ...
}
}
class Derived extends Base {
private final Object lock = new Object()... | ## Risk Assessment
Overriding
thread-safe
methods with methods that are unsafe for concurrent access can result in unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TSM00-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 12. Thread-Safety Miscellaneous (TSM) |
java | 88,487,816 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487816 | 2 | 12 | TSM01-J | Do not let the this reference escape during object construction | According to
The Java Language Specification
,
§15.8.3, "
this
"
[
JLS 2015
]:
When used as a primary expression, the keyword
this
denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed....
The type of
this
is the class or interface type ... | final class Publisher {
public static volatile Publisher published;
int num;
Publisher(int number) {
published = this;
// Initialization
this.num = number;
// ...
}
}
final class Publisher {
public static Publisher published;
int num;
Publisher(int number) {
// Initialization
th... | final class Publisher {
static volatile Publisher published;
int num;
Publisher(int number) {
// Initialization
this.num = number;
// ...
published = this;
}
}
final class Publisher {
final int num;
private Publisher(int number) {
// Initialization
this.num = number;
}
public... | ## Risk Assessment
Allowing the
this
reference to escape can result in improper initialization and runtime exceptions.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TSM01-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 12. Thread-Safety Miscellaneous (TSM) |
java | 88,487,700 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487700 | 2 | 12 | TSM02-J | Do not use background threads during class initialization | Starting and using background threads during class initialization can result in class initialization cycles and
deadlock
. For example, the main thread responsible for performing class initialization can block waiting for the background thread, which in turn will wait for the main thread to finish class initialization.... | public final class ConnectionFactory {
private static Connection dbConnection;
// Other fields ...
static {
Thread dbInitializerThread = new Thread(new Runnable() {
@Override public void run() {
// Initialize the database connection
try {
dbConnection = DriverManager.g... | public final class ConnectionFactory {
private static Connection dbConnection;
// Other fields ...
static {
// Initialize a database connection
try {
dbConnection = DriverManager.getConnection("connection string");
} catch (SQLException e) {
dbConnection = null;
}
// Other initial... | ## Risk Assessment
Starting and using background threads during class initialization can result in
deadlock
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TSM02-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 12. Thread-Safety Miscellaneous (TSM) |
java | 88,487,871 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487871 | 2 | 12 | TSM03-J | Do not publish partially initialized objects | During initialization of a shared object, the object must be accessible only to the thread constructing it. However, the object can be published safely (that is, made visible to other threads) once its initialization is complete. The
Java memory model (JMM)
allows multiple threads to observe the object after its initia... | class Foo {
private Helper helper;
public Helper getHelper() {
return helper;
}
public void initialize() {
helper = new Helper(42);
}
}
public class Helper {
private int n;
public Helper(int n) {
this.n = n;
}
// ...
}
## Noncompliant Code Example
This noncompliant code example constr... | class Foo {
private Helper helper;
public synchronized Helper getHelper() {
return helper;
}
public synchronized void initialize() {
helper = new Helper(42);
}
}
class Foo {
private final Helper helper;
public Helper getHelper() {
return helper;
}
public Foo() {
// Point 1
hel... | ## Risk Assessment
Failure to synchronize access to shared mutable data can cause different threads to observe different states of the object or to observe a partially initialized object.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
TSM03-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 12. Thread-Safety Miscellaneous (TSM) |
java | 88,487,745 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487745 | 2 | 8 | VNA00-J | Ensure visibility when accessing shared primitive variables | Reading a shared primitive variable in one thread may not yield the value of the most recent write to the variable from another thread. Consequently, the thread may observe a stale value of the shared variable. To ensure the visibility of the most recent update, either the variable must be declared volatile or the read... | final class ControlledStop implements Runnable {
private boolean done = false;
@Override public void run() {
while (!done) {
try {
// ...
Thread.currentThread().sleep(1000); // Do something
} catch(InterruptedException ie) {
Thread.currentThread().interrupt(); // Reset int... | final class ControlledStop implements Runnable {
private volatile boolean done = false;
@Override public void run() {
while (!done) {
try {
// ...
Thread.currentThread().sleep(1000); // Do something
} catch(InterruptedException ie) {
Thread.currentThread().interrupt(); // ... | ## Risk Assessment
Failing to ensure the visibility of a shared primitive variable may result in a thread observing a stale value of the variable.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
VNA00-J
Medium
Probable
Yes
No
P8
L2 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
java | 88,487,906 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487906 | 2 | 8 | VNA01-J | Ensure visibility of shared references to immutable objects | A common misconception is that shared references to
immutable
objects are immediately visible across multiple threads as soon as they are updated. For example, a developer can mistakenly believe that a class containing fields that refer only to immutable objects is itself immutable and consequently
thread-safe
.
Sectio... | // Immutable Helper
public final class Helper {
private final int n;
public Helper(int n) {
this.n = n;
}
// ...
}
final class Foo {
private Helper helper;
public Helper getHelper() {
return helper;
}
public void setHelper(int num) {
helper = new Helper(num);
}
}
do not replace with ... | final class Foo {
private Helper helper;
public synchronized Helper getHelper() {
return helper;
}
public synchronized void setHelper(int num) {
helper = new Helper(num);
}
}
final class Foo {
private volatile Helper helper;
public Helper getHelper() {
return helper;
}
public void set... | ## Risk Assessment
The incorrect assumption that classes that contain only references to immutable objects are themselves immutable can cause serious
thread-safety
issues.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
VNA01-J
Low
Probable
Yes
No
P4
L3
Automated Detection
Some static analysis tools are c... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
java | 88,487,754 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487754 | 2 | 8 | VNA02-J | Ensure that compound operations on shared variables are atomic | Compound operations are operations that consist of more than one discrete operation. Expressions that include postfix or prefix increment (
++
), postfix or prefix decrement (
--
), or compound assignment operators always result in compound operations. Compound assignment expressions use operators such as
*=
,
/=
,
%=
... | final class Flag {
private boolean flag = true;
public void toggle() { // Unsafe
flag = !flag;
}
public boolean getFlag() { // Unsafe
return flag;
}
}
final class Flag {
private boolean flag = true;
public void toggle() { // Unsafe
flag ^= true; // Same as flag = !flag;
}
public bo... | final class Flag {
private boolean flag = true;
public synchronized void toggle() {
flag ^= true; // Same as flag = !flag;
}
public synchronized boolean getFlag() {
return flag;
}
}
final class Flag {
private volatile boolean flag = true;
public synchronized void toggle() {
flag ^= true; /... | ## Risk Assessment
When operations on shared variables are not atomic, unexpected results can be produced. For example, information can be disclosed inadvertently because one user can receive information about other users.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
VNA02-J
Medium
Probable
Yes
No
P8
L... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
java | 88,487,922 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487922 | 2 | 8 | VNA03-J | Do not assume that a group of calls to independently atomic methods is atomic | A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. When two or more operations must be performed as a single atomic operation, a consistent locking policy must be implemented using either intrinsic synchronization or
java.util.concurrent
utilities. In the ab... | final class Adder {
private final AtomicReference<BigInteger> first;
private final AtomicReference<BigInteger> second;
public Adder(BigInteger f, BigInteger s) {
first = new AtomicReference<BigInteger>(f);
second = new AtomicReference<BigInteger>(s);
}
public void update(BigInteger f, BigInteger s)... | final class Adder {
// ...
private final AtomicReference<BigInteger> first;
private final AtomicReference<BigInteger> second;
public Adder(BigInteger f, BigInteger s) {
first = new AtomicReference<BigInteger>(f);
second = new AtomicReference<BigInteger>(s);
}
public synchronized void update(Big... | ## Risk Assessment
Failure to ensure the atomicity of two or more operations that must be performed as a single atomic operation can result in
race conditions
in multithreaded applications.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
VNA03-J
Low
Probable
No
No
P2
L3
Automated Detection
Some static ana... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
java | 88,487,766 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487766 | 2 | 8 | VNA04-J | Ensure that calls to chained methods are atomic | Method chaining is a convenient mechanism that allows multiple method invocations on the same object to occur in a single statement. A method-chaining implementation consists of a series of methods that return the
this
reference. This implementation allows a caller to invoke methods in a chain by performing the next me... | final class USCurrency {
// Change requested, denomination (optional fields)
private int quarters = 0;
private int dimes = 0;
private int nickels = 0;
private int pennies = 0;
public USCurrency() {}
// Setter methods
public USCurrency setQuarters(int quantity) {
quarters = quantity;
return thi... | What does this mean? It can be accessible to any number of threads ~DM => The method chaining is actually constrained to the {{USCurrency.Builder}} class which is only accessible from a single thread.
final class USCurrency {
private final int quarters;
private final int dimes;
private final int nickels;
priv... | ## Risk Assessment
Using method chaining in multithreaded environments without performing external locking can lead to nondeterministic behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
VNA04-J
Low
Probable
Yes
No
P4
L3 | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
java | 88,487,887 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88487887 | 2 | 8 | VNA05-J | Ensure atomicity when reading and writing 64-bit values | The Java Language Specification
(JLS) allows 64-bit
long
and
double
values to be treated as two 32-bit values. For example, a 64-bit write operation could be performed as two separate 32-bit operations.
According to the JLS, §17.7,
"Non-Atomic Treatment of
double
and
long
"
[
JLS 2015
]:
For the purposes of the Java pr... | class LongContainer {
private long i = 0;
void assignValue(long j) {
i = j;
}
void printLong() {
System.out.println("i = " + i);
}
}
## Noncompliant Code Example
In this noncompliant code example, if one thread repeatedly calls the
assignValue()
method and another thread repeatedly calls the
printL... | class LongContainer {
private volatile long i = 0;
void assignValue(long j) {
i = j;
}
void printLong() {
System.out.println("i = " + i);
}
}
## Compliant Solution (Volatile)
## This compliant solution declaresivolatile. Writes and reads oflonganddoublevolatile values are always atomic.
#ccccff
cla... | ## Risk Assessment
Failure to ensure the atomicity of operations involving 64-bit values in multithreaded applications can result in reading and writing indeterminate values. However, many Java Virtual Machines read and write 64-bit values atomically even though the specification does not require them to.
Rule
Severity... | SEI CERT Oracle Coding Standard for Java > 2 Rules > Rule 08. Visibility and Atomicity (VNA) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.