SlideShare a Scribd company logo
1 of 52
1 FindBugs™ - Find Bugs in Java Programs Defective Java Code Learning from mistakes Carol McDonald
2 What is FindBugs? ,[object Object]
Looks for defects based on bug patterns
Bug patterns come from real bugs
bug patterns are grouped into categories:
correctness, bad practice, performance…
assigned a priority: high, medium or low.
High-Medium priority have low false positive rates
http://findbugs.sourceforge.net/,[object Object]
a read or write on a null pointer
typos
Methods whose return value should not be ignored
Also specific bug patterns:
Every Programming Puzzler
Eclipse documented bug fixes
Every chapter in Effective Java
Many postings to http://thedailywtf.com/3
© Availity, LLC | All rights reserved.	 4 BugPatterns: http://thedailywtf.com/ 4
© Availity, LLC | All rights reserved.	 5 Some bug Patterns:
© Availity, LLC | All rights reserved.	 6 Some bug Patterns:
7 Misconceptions about Bugs ,[object Object]
Smart people don’t make dumb mistakes
WRONG!
Smart people make dumb mistakes
Common errors:
wrong boolean operator, forgetting parentheses, etc.
Misunderstood class or method  !,[object Object]
9 Who uses FindBugs?  ,[object Object]
Google, Ebay, Sun, Wells Fargo…
Bill Pugh spent a year sabbatical at Google  working Findbugs  into their development process
Google runs FindBugs over all Java code
1800s issues identified, > 600 fixed.
Ebay found 2 developers reviewing  Findbugs  was 10 times more effective than 2 testers,[object Object]
Concurrency
Performance• Security defect
11 Can you find the Bug?  public String sendMessage (User user, String body, Date time) {     return sendMessage(user, body, null);   } public String sendMessage (User user, String body, Date time, List attachments) {    String xml = buildXML (body, attachments);    String response = sendMessage(user, xml);    return response;   }
12 Infinite recursive loopHigh priority correctness public String sendMessage (User user, String body, Date time) {     return sendMessage(user, body, null);   } public String sendMessage (User user, String body, Date time, List attachments) {    String xml = buildXML (body, attachments);    String response = sendMessage(user, xml);    return response;   }
13 Can you find the Bug?  public String foundType() {    return this.foundType(); }
14 Infinite recursive loop public String foundType() {    return this.foundType(); } // should be  public String foundType() {    return this.foundType; } • Findbugs found 5 infinite recursive loops in  JDK1.6.0-b13 • Including this one written by Joshua Bloch • Smart people make dumb mistakes • 27 across all versions of JDK, 31 in Google’s Java code • Embrace and fix your dumb mistakes
15 Can you find the Bug?  if (name != null || name.length > 0)
16 Can you find the Bug?  if (name != null || name.length > 0) if (name != null &&name.length > 0) Found in //com.sun.corba.se.impl.naming.cosnaming.NamingContextImpl
17 Can you find the Bug?  if (part == null | part.equals(""))
18 Can you find the Bug?  if (part == null | part.equals("")) if (part == null ||part.equals("")) Found in  //com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser
19 Null Pointer Bugs found in com.sun…. if (name != null || name.length > 0) if (part == null | part.equals("")) // sun.awt.x11.ScrollPanePeer if (g != null) paintScrollBars(g,colors); g.dispose();
© Availity, LLC | All rights reserved.	 20 Can you find the Bug?  //BoundedThreadPool private final String _lock = "LOCK";...synchronized(_lock){...}
© Availity, LLC | All rights reserved.	 21 found in Jetty…. //BoundedThreadPoolprivate final String _lock = "LOCK";...synchronized(_lock){...} Constant Strings are shared across all other classes loaded by the JVM. Could lead to unexpected deadlocks in conjunction with other code
22 Problem? public final WritableRaster filter( Raster src, 	WritableRasterdst) { intdstLength = dst.getNumBands();  // Create a new destination Raster,if needed  if (dst == null) dst = createCompatibleDestRaster(src);
23 Redundant Check for Null Is it a bug or a redundant check? public final WritableRaster filter( Raster src, 	WritableRasterdst) { intdstLength = dst.getNumBands();  // Create a new destination Raster,if needed  if (dst == null) dst = createCompatibleDestRaster(src); can't be null because there would have been a NPE if it were null
24 Can you find the Bug?  if (adapters == null && adapters.length == 0) 	return; Eclipse, 3.5RC3 • in Eclipse since  3.2 •in this case adapters is probably never null • Impact: ,[object Object]
Won’t return if length is 0, error harder to find,[object Object]
26 Bad Method Call // com.sun.xml.internal.txw2.output.XMLWriter try { ... } catch (IOException e) {   new SAXException("Server side Exception:" + e); } Exception created and dropped rather than thrown  try { ... } catch (IOException e) { throw new SAXException("Server side Exception:" + e); }
27 Problem? public static String getNameById(String userId) {     String str = userId;     ... str.replace(' ', '_');     return str;   }

More Related Content

What's hot

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

What's hot (20)

Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean code
Clean codeClean code
Clean code
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean code
Clean codeClean code
Clean code
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelines
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Garbage collection
Garbage collectionGarbage collection
Garbage collection
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 

Viewers also liked (8)

Preemptive Error Detection with FindBugs
Preemptive Error Detection with FindBugsPreemptive Error Detection with FindBugs
Preemptive Error Detection with FindBugs
 
Ensuring code quality
Ensuring code qualityEnsuring code quality
Ensuring code quality
 
Story behind PF 2016
Story behind PF 2016Story behind PF 2016
Story behind PF 2016
 
C language in our world 2016
C language in our world 2016C language in our world 2016
C language in our world 2016
 
Java Code Quality Tools
Java Code Quality ToolsJava Code Quality Tools
Java Code Quality Tools
 
Code Coverage
Code CoverageCode Coverage
Code Coverage
 
Development of Mobile Applications
Development of Mobile ApplicationsDevelopment of Mobile Applications
Development of Mobile Applications
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Similar to Finding bugs that matter with Findbugs

Similar to Finding bugs that matter with Findbugs (20)

Java best practices
Java best practicesJava best practices
Java best practices
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Clean code
Clean codeClean code
Clean code
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
 
Clean Code
Clean CodeClean Code
Clean Code
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

More from Carol McDonald

More from Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Finding bugs that matter with Findbugs

  • 1. 1 FindBugs™ - Find Bugs in Java Programs Defective Java Code Learning from mistakes Carol McDonald
  • 2.
  • 3. Looks for defects based on bug patterns
  • 4. Bug patterns come from real bugs
  • 5. bug patterns are grouped into categories:
  • 7. assigned a priority: high, medium or low.
  • 8. High-Medium priority have low false positive rates
  • 9.
  • 10. a read or write on a null pointer
  • 11. typos
  • 12. Methods whose return value should not be ignored
  • 13. Also specific bug patterns:
  • 16. Every chapter in Effective Java
  • 17. Many postings to http://thedailywtf.com/3
  • 18. © Availity, LLC | All rights reserved. 4 BugPatterns: http://thedailywtf.com/ 4
  • 19. © Availity, LLC | All rights reserved. 5 Some bug Patterns:
  • 20. © Availity, LLC | All rights reserved. 6 Some bug Patterns:
  • 21.
  • 22. Smart people don’t make dumb mistakes
  • 24. Smart people make dumb mistakes
  • 26. wrong boolean operator, forgetting parentheses, etc.
  • 27.
  • 28.
  • 29. Google, Ebay, Sun, Wells Fargo…
  • 30. Bill Pugh spent a year sabbatical at Google working Findbugs into their development process
  • 31. Google runs FindBugs over all Java code
  • 33.
  • 36. 11 Can you find the Bug? public String sendMessage (User user, String body, Date time) { return sendMessage(user, body, null); } public String sendMessage (User user, String body, Date time, List attachments) { String xml = buildXML (body, attachments); String response = sendMessage(user, xml); return response; }
  • 37. 12 Infinite recursive loopHigh priority correctness public String sendMessage (User user, String body, Date time) { return sendMessage(user, body, null); } public String sendMessage (User user, String body, Date time, List attachments) { String xml = buildXML (body, attachments); String response = sendMessage(user, xml); return response; }
  • 38. 13 Can you find the Bug? public String foundType() { return this.foundType(); }
  • 39. 14 Infinite recursive loop public String foundType() { return this.foundType(); } // should be public String foundType() { return this.foundType; } • Findbugs found 5 infinite recursive loops in JDK1.6.0-b13 • Including this one written by Joshua Bloch • Smart people make dumb mistakes • 27 across all versions of JDK, 31 in Google’s Java code • Embrace and fix your dumb mistakes
  • 40. 15 Can you find the Bug? if (name != null || name.length > 0)
  • 41. 16 Can you find the Bug? if (name != null || name.length > 0) if (name != null &&name.length > 0) Found in //com.sun.corba.se.impl.naming.cosnaming.NamingContextImpl
  • 42. 17 Can you find the Bug? if (part == null | part.equals(""))
  • 43. 18 Can you find the Bug? if (part == null | part.equals("")) if (part == null ||part.equals("")) Found in //com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser
  • 44. 19 Null Pointer Bugs found in com.sun…. if (name != null || name.length > 0) if (part == null | part.equals("")) // sun.awt.x11.ScrollPanePeer if (g != null) paintScrollBars(g,colors); g.dispose();
  • 45. © Availity, LLC | All rights reserved. 20 Can you find the Bug? //BoundedThreadPool private final String _lock = "LOCK";...synchronized(_lock){...}
  • 46. © Availity, LLC | All rights reserved. 21 found in Jetty…. //BoundedThreadPoolprivate final String _lock = "LOCK";...synchronized(_lock){...} Constant Strings are shared across all other classes loaded by the JVM. Could lead to unexpected deadlocks in conjunction with other code
  • 47. 22 Problem? public final WritableRaster filter( Raster src, WritableRasterdst) { intdstLength = dst.getNumBands(); // Create a new destination Raster,if needed if (dst == null) dst = createCompatibleDestRaster(src);
  • 48. 23 Redundant Check for Null Is it a bug or a redundant check? public final WritableRaster filter( Raster src, WritableRasterdst) { intdstLength = dst.getNumBands(); // Create a new destination Raster,if needed if (dst == null) dst = createCompatibleDestRaster(src); can't be null because there would have been a NPE if it were null
  • 49.
  • 50.
  • 51. 26 Bad Method Call // com.sun.xml.internal.txw2.output.XMLWriter try { ... } catch (IOException e) { new SAXException("Server side Exception:" + e); } Exception created and dropped rather than thrown try { ... } catch (IOException e) { throw new SAXException("Server side Exception:" + e); }
  • 52. 27 Problem? public static String getNameById(String userId) { String str = userId; ... str.replace(' ', '_'); return str; }
  • 53. 28 Method Ignores return valueCorrectness public static String getNameById(String userId) { String str = userId; ... str= str.replace(' ', '_'); return str; } Methods whose return value shouldn't be ignored • Strings are immutable, so functions like trim() and replace() return new String
  • 54. 29 What does it Print? Integer one = 1; Long addressTypeCode = 1L; if (addressTypeCode.equals(one)) { System.out.println("equals"); } else { System.out.println("not equals"); }
  • 55. 30 Comparing Different Types Integer one = 1; Long addressTypeCode = 1L; if (addressTypeCode.equals(one)) { System.out.println("equals"); } else { System.out.println("not equals"); } According to the contract of equals(), objects of different classes should always compare as unequal;
  • 56.
  • 57. Using .equals to compare arrays
  • 58. only checks if the same array
  • 59. Checking to see if a Set<Long> contains an Integer
  • 60. never found, even if the same integral value is contained in the map
  • 61. Calling get(String) on a Map<Integer,String>
  • 62.
  • 63. May be introduced by refactoring
  • 64. Google refactoring that changed a method to return byte[ ] rather than String© Availity, LLC | All rights reserved. 31
  • 65. 32 Best Way to use Findbugs •Want to find an effective/profitable way to use static analysis to improve software quality Mistakes That Don’t Mistakes That Matter Testing Deployment Static Analysis
  • 66.
  • 67. While code is fresh in developers heads
  • 68. Don’t be too eager to fix old issuesMistakes That Matter Mistakes That Don’t Static Analysis Testing Deployment
  • 69. Runtime exceptions can be your friend… Errors which cause a runtime exception are more easily found Throwing a runtime exception is often a reasonable way to fail safely and report a failure. runtime exceptions represent conditions that reflect errors in your program's logic and cannot be reasonably recovered from IllegalArgumentException, NullPointerException, or IllegalStateException © Availity, LLC | All rights reserved. 34
  • 70.
  • 71. silently cause the wrong answer to be computed
  • 72. Mistakes that cause loss of money when they occur
  • 73. Mistakes that are hard to fix© Availity, LLC | All rights reserved. 35
  • 74. 36 Can you find the (Google) bug ? // calculate DR amount by aggregating CR amounts BigDecimaldrAmount = new BigDecimal(0); for (JournalEntry je: journalEntries) drAmount.add(je.getCrAmount()); // persist to db getTrxnService().saveJournalEntry(id, drAmount, // aggregated amount true, // Debit "USD", "Revenue");
  • 75. 37 A Google Bug //Ignored return value of BigDecimal.add for (JournalEntry je: journalEntries) drAmount.add(je.getCrAmount()); // should be drAmount= drAmount.add(je.getCrAmount()); Fixed within 30 minutes of being reported
  • 76. 38 Bug ? int value2; Public boolean equals(Integer value1){ return value1== intValue() ; } public Integer intValue() { return value2; }
  • 77. 39 Using reference equality rather than .equals int value2; Public boolean equals(Integer value1){ return value1.equals(intValue() ); } public Integer intValue() { return value2; } For boxed primitives, == and != are computed using pointer equality, but <, <=, >, >= are computed by comparing unboxed primitive values This can bite you on other classes (e.g., String) • but boxed primitives is where people get bit
  • 78. 40 Bug ? ConcurrentMap<Long,XmitTimeStat> xmit_time_stats = ...; ..... stat = new XmitTimeStat(); xmit_time_stats.putIfAbsent(key, stat); stat.xmit_rsps_sent.addAndGet(sent);
  • 79. 41 misusing putIfAbsentorg.jgroups.protocols.pbcast.NAKACK ConcurrentMap<Long,XmitTimeStat> xmit_time_stats = ...; ..... stat = new XmitTimeStat(); XmitTimeStat stat2 = xmit_time_stats.putIfAbsent(key, stat); if (stat2 != null) stat = stat2; stat.xmit_rsps_sent.addAndGet(sent); ConcurrentMap provides putIfAbsent • atomically add key -> value mapping • but only if the key isnʼt already in the map • if non-null value is returned, put failed and value returned is the value already associated with the key
  • 80.
  • 81. They don’t cause as many problems as they should
  • 82. Problems will probably increase with bigger core systems
  • 83. Early reports from 768 core systems are that they have more severe problems© Availity, LLC | All rights reserved. 42
  • 84.
  • 85. a lock is held sometimes when field accessed
  • 87. e.g., call to wait() not in loop
  • 88. unsafe lazy initialization of static field© Availity, LLC | All rights reserved. 43
  • 89. 44 Bug ? synchronized (object) {   if (<condition does not hold>) {     object.wait();   }   // Proceed when condition holds }
  • 90. 45 call to wait() not in loop synchronized (object) {   while (<condition does not hold>) {     object.wait();   }   // Proceed when condition holds }
  • 91.
  • 92. In Joshua Blochʼs said: don’t lock on ConcurrentMaps• Bill Pugh wrote a detector for FindBugs © Availity, LLC | All rights reserved. 46
  • 93.
  • 94. 9 synchronizations on CopyOnWriteArrayList
  • 95. 3 synchronizations on AtomicBoolean© Availity, LLC | All rights reserved. 47
  • 96.
  • 97. Need:
  • 98. Risk analysis, careful design, static analysis, dynamic testing and analysis
  • 99. Findbugsdoes simple analysis for network security vulnerabilities© Availity, LLC | All rights reserved. 48
  • 100.
  • 102. Methods that don’t defensively copy mutable arguments before storing them into fields
  • 103. Methods that don’t defensively copy mutable values stored in fields before returning them
  • 106. included in HTTP response
  • 107. Forming a file path © Availity, LLC | All rights reserved. 49
  • 108.
  • 110. Run with Hudson build © Availity, LLC | All rights reserved. 50
  • 112.