PMD rule DataflowAnomalyAnalysis oddness
Question
I have the following JUnit test:
@Test
public void testRunLocalhost() throws IOException, InterruptedException {
// Start an AnnouncerThread
final AnnouncerThread announcer = new AnnouncerThread();
announcer.start();
// Create the socket and listen on the right port.
final DatagramSocket socket = new DatagramSocket();
assert(socket != null);
// Create a packet to send.
final DatagramPacket packet = new DatagramPacket(new byte[0], 0, InetAddress.getByName(AnnouncerThread.GROUP), AnnouncerThread.PORT);
assert(packet != null);
// Send the packet.
socket.send(packet);
// Listen for the IP from the server.
final DatagramPacket receivedPacket = new DatagramPacket(new byte[256], 256);
socket.setSoTimeout(2000); // Only wait 2 seconds.
socket.receive(receivedPacket);
socket.close();
// Get localhost's address.
final InetAddress localhost = InetAddress.getLocalHost();
assert(localhost != null);
// Compare the receive IP to the localhost IP.
final String receivedIP = new String(receivedPacket.getData());
if (!receivedIP.startsWith(localhost.getHostAddress())) {
fail("Received IP: '" + receivedIP + "' not the same as localhost: '" + localhost.getHostAddress() + "'");
}
announcer.shutdown();
announcer.join();
}
And PMD gives the following violations:
Found 'UR'-anomaly for variable 'socket' (lines '36'-'36').
Found 'UR'-anomaly for variable 'localhost' (lines '36'-'36').
Found 'UR'-anomaly for variable 'packet' (lines '36'-'36').
Line 36 in my file is the line the method is defined:
public void testRunLocalhost() throws IOException, InterruptedException {
I don't understand what the violations are saying. Where should I defining those three variables? Why wasn't the AnnouncerThread in the violations? It's declared the same way I've tried re-ordering the declarations to no avail.
Solution
It does appear to have something to do with the assert
calls you're making right after allocating those three final variables.
The PMD docs (http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis) say:
UR - Anomaly: There is a reference to a variable that was not defined before
OTHER TIPS
That looks rather strange. Interestingly, it occurs for all three variables that are defined for objects allocated via 'new', which you then check for nullness. I would expect the result of 'new' to always be valid/not-null - otherwise an OutOfMemoryException
should be thrown. Is that the issue, I wonder ?