This document discusses uncommon Java bugs and how free open source static analysis tools can help detect them. It provides examples of bugs like using the letter "l" instead of the number 1 in a long constant, checking for NaN equality, and null pointer exceptions. The document introduces tools like Jlint, FindBugs, PMD, and QJ-Pro that can find these kinds of bugs and describes how each tool detects bugs in code examples. It concludes that using static analysis tools can improve code quality by finding defects early.
xUnit and TDD: Why and How in Enterprise Software, August 2012Justin Gordon
“A comprehensive suite of JUnit tests is one of the most import aspects of a software project because it reduces bugs, facilitates adding new developers, and enables refactoring and performance tuning with confidence. Test-driven development (TDD) is the best way to build a suite of tests. And the Dependent Object Framework is the best way to test against database objects.” This presentation covers the benefits of TDD along with practical advice on how to implement TDD in complex projects.
IT conferences and meetings on programming languages see a growing number of speakers talking about static code analysis. Although this field is quite specific, there is still a number of interesting discussions to be found here to help programmers understand the methods, ways of use, and specifics of static code analysis. In this article, we have collected a number of videos on static analysis whose easy style of presentation makes them useful and interesting to a wide audience of both skilled and novice programmers.
Open Source tools in Continuous Integration environment (case study for agil...suwalki24.pl
Article wrote for Testing Experience magazine, publicated in December 2010.
The aim of this article is to share our experience in building and
managing Continuous Integration environments on the basis of
open-source tools like Hudson and Selenium. In this article we
will concentrate on testing purposes, suggest just few improvements
and describe our experience with using open-source tools.
The main idea is to present how to use automated tests reasonably
by minimizing the time spent on them while optimizing the
benefits that automated tests give us.
xUnit and TDD: Why and How in Enterprise Software, August 2012Justin Gordon
“A comprehensive suite of JUnit tests is one of the most import aspects of a software project because it reduces bugs, facilitates adding new developers, and enables refactoring and performance tuning with confidence. Test-driven development (TDD) is the best way to build a suite of tests. And the Dependent Object Framework is the best way to test against database objects.” This presentation covers the benefits of TDD along with practical advice on how to implement TDD in complex projects.
IT conferences and meetings on programming languages see a growing number of speakers talking about static code analysis. Although this field is quite specific, there is still a number of interesting discussions to be found here to help programmers understand the methods, ways of use, and specifics of static code analysis. In this article, we have collected a number of videos on static analysis whose easy style of presentation makes them useful and interesting to a wide audience of both skilled and novice programmers.
Open Source tools in Continuous Integration environment (case study for agil...suwalki24.pl
Article wrote for Testing Experience magazine, publicated in December 2010.
The aim of this article is to share our experience in building and
managing Continuous Integration environments on the basis of
open-source tools like Hudson and Selenium. In this article we
will concentrate on testing purposes, suggest just few improvements
and describe our experience with using open-source tools.
The main idea is to present how to use automated tests reasonably
by minimizing the time spent on them while optimizing the
benefits that automated tests give us.
Test-Driven Development is about approaching software development from a test perspective and knowing how to use the tools (e.g. JUnit, Mockito) to effectively write tests.
Source code examples @...
https://github.com/codeprimate-software/test-driven-development
JUnit is an open source Unit Testing Framework for JAVA. It is useful for Java Developers to write and run repeatable tests. Erich Gamma and Kent Beck initially develop it. It is an instance of xUnit architecture. As the name implies, it is used for Unit Testing of a small chunk of code.
Test driven development (TDD), a software development method, helps build high quality applications faster. Life-cycle, usefulness, limitations and similar techniques of TDD have been presented in this slide deck.
The article describes the testing technologies used when developing PVS-Studio static code analyzer. The developers of the tool for programmers talk about the principles of testing their own program product which can be interesting for the developers of similar packages for processing text data or source code.
In this presentation we introduce the concept quality assurance in video games along with the most important concepts, team members and testing phases.
These slides were prepared by Dr. Marc Miquel. All the materials used in them are referenced to their authors.
Oplægget blev holdt ved et seminar i InfinIT-interessegruppen Softwaretest den 28. september 2010.
Læs mere om interessegruppen på http://www.infinit.dk/dk/interessegrupper/softwaretest/softwaretest.htm
Regular use of static code analysis in team developmentAndrey Karpov
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
The article discusses different levels of using static code analysis technologies in team development and shows how to "move" the process from one level to another. The article refers to the PVS-Studio code analyzer developed by the authors as an example.
Regular use of static code analysis in team developmentPVS-Studio
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
The article discusses different levels of using static code analysis technologies in team development and shows how to "move" the process from one level to another. The article refers to the PVS-Studio code analyzer developed by the authors as an example.
Regular use of static code analysis in team developmentPVS-Studio
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
Peter Zimmerer - Evolve Design For Testability To The Next Level - EuroSTAR 2012TEST Huddle
EuroSTAR Software Testing Conference 2012 presentation on Evolve Design For Testability To The Next Level by Peter Zimmerer . See more at: http://conference.eurostarsoftwaretesting.com/past-presentations/
Konstantin Knizhnik: static analysis, a view from asidePVS-Studio
The article is an interview with Konstantin Knizhnik taken by Andrey Karpov, "Program Verification Systems" company's worker. In this interview the issues of static code analysis, relevance of solutions made in this sphere and prospects of using static analysis while developing applications are discussed.
La charla está enfocada en una herramienta de análisis de código estático, la cuál se encuentra en desarrollo actualmente, enfocada específicamente en la búsqueda de vulnerabilidades, en vez de centrarse en errores típicos de programación como las más populares herramientas de análisis de código tales como Coverity o Klockwork. Durante el transcurso de la misma se irá dando toda la base necesaria para entender el funcionamiento de estas herramientas, la diferencia entre herramientas para buscar bugs y vulnerabilidades así como la parte que el ponente considera fundamental de dar interactividad a este tipo de herramientas.
Al final de la charla se mostrará una pequeña demo de la herramienta actual y algunos fallos/vulnerabilidades encontrados gracias a la misma.
Test-Driven Development is about approaching software development from a test perspective and knowing how to use the tools (e.g. JUnit, Mockito) to effectively write tests.
Source code examples @...
https://github.com/codeprimate-software/test-driven-development
JUnit is an open source Unit Testing Framework for JAVA. It is useful for Java Developers to write and run repeatable tests. Erich Gamma and Kent Beck initially develop it. It is an instance of xUnit architecture. As the name implies, it is used for Unit Testing of a small chunk of code.
Test driven development (TDD), a software development method, helps build high quality applications faster. Life-cycle, usefulness, limitations and similar techniques of TDD have been presented in this slide deck.
The article describes the testing technologies used when developing PVS-Studio static code analyzer. The developers of the tool for programmers talk about the principles of testing their own program product which can be interesting for the developers of similar packages for processing text data or source code.
In this presentation we introduce the concept quality assurance in video games along with the most important concepts, team members and testing phases.
These slides were prepared by Dr. Marc Miquel. All the materials used in them are referenced to their authors.
Oplægget blev holdt ved et seminar i InfinIT-interessegruppen Softwaretest den 28. september 2010.
Læs mere om interessegruppen på http://www.infinit.dk/dk/interessegrupper/softwaretest/softwaretest.htm
Regular use of static code analysis in team developmentAndrey Karpov
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
The article discusses different levels of using static code analysis technologies in team development and shows how to "move" the process from one level to another. The article refers to the PVS-Studio code analyzer developed by the authors as an example.
Regular use of static code analysis in team developmentPVS-Studio
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
The article discusses different levels of using static code analysis technologies in team development and shows how to "move" the process from one level to another. The article refers to the PVS-Studio code analyzer developed by the authors as an example.
Regular use of static code analysis in team developmentPVS-Studio
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
Peter Zimmerer - Evolve Design For Testability To The Next Level - EuroSTAR 2012TEST Huddle
EuroSTAR Software Testing Conference 2012 presentation on Evolve Design For Testability To The Next Level by Peter Zimmerer . See more at: http://conference.eurostarsoftwaretesting.com/past-presentations/
Konstantin Knizhnik: static analysis, a view from asidePVS-Studio
The article is an interview with Konstantin Knizhnik taken by Andrey Karpov, "Program Verification Systems" company's worker. In this interview the issues of static code analysis, relevance of solutions made in this sphere and prospects of using static analysis while developing applications are discussed.
La charla está enfocada en una herramienta de análisis de código estático, la cuál se encuentra en desarrollo actualmente, enfocada específicamente en la búsqueda de vulnerabilidades, en vez de centrarse en errores típicos de programación como las más populares herramientas de análisis de código tales como Coverity o Klockwork. Durante el transcurso de la misma se irá dando toda la base necesaria para entender el funcionamiento de estas herramientas, la diferencia entre herramientas para buscar bugs y vulnerabilidades así como la parte que el ponente considera fundamental de dar interactividad a este tipo de herramientas.
Al final de la charla se mostrará una pequeña demo de la herramienta actual y algunos fallos/vulnerabilidades encontrados gracias a la misma.
The Namtional Assembely Pakistan proceedings of the special committee of the whole house held in Camera to consider the Qadiani Issue - Vol 5 out of 27
The ASSA ABLOY Group released its interim report for the third quarter July-September 2013 on Monday 28 October 2013 at 08.00 am (CET). The presentation from the combined investors’ and analyst meeting and web conference is available as an on-demand webcast. Welcome to visit our Investor pages on http://www.assaabloy.com/investors/.
Anger in the Light of J Krishnamurti TeachingsSaumitra Das
Anger hurts and tears us apart. Anger is such an emotion that only inflicts violence. In fact anger itself is violence. All religions and spiritual leaders have spoken about the dangers of anger. Lot of remedies have been prescribed by them to get rid of the anger but still people are in the flames of anger. Here attempt has been made to see the Anger in the light of J Krishnamurti teachings.
These are the best tips from millionaires to use in your business. These are important! How many are you actually setting aside time for?
Millionaires became millionaires because they took action. Beside each tip I created a checklist with ideas on how you can accomplish them. Enjoy!!
The ASSA ABLOY Group released its interim report January-June 2013 on Friday 19 July 2013 at 08.00 am (CET). The presentation from the combined investors’ and analyst meeting and web conference is available as an on-demand webcast. Welcome to visit our Investor pages on http://www.assaabloy.com/investors/.
Yellow Slice is a design studio in Mumbai, India. We specialise in Branding, UI (User Interface) , UX (User Experience), User Research & Usability Testing.
An ideal static analyzer, or why ideals are unachievablePVS-Studio
Being inspired by Eugene Laspersky's post about an ideal antivirus, I decided to write a similar post about an ideal static analyzer. And meanwhile think how far from being it our PVS-Studio is.
The pragmatic programmer 1999
Andy Hunt, Dave Thomas
Chapter 3 / The Basic Tools
Quick review about programmer's tools , power of plain text, debugging, source code control and so on...
A Java compiler is a compiler for the development terminology Java. The most frequent way of outcome from a Java compiler is Java category data files containing platform-neutral Java bytecode,
Testing parallel software is a more complicated task in comparison to testing a standard program. The programmer should be aware both of the traps he can face while testing parallel code and existing methodologies and toolkit.
Almost everything can be done using refactoring tools:
* How to get buy-in for refactoring? (use Technical Debt quantification tools)
* How to identify refactoring candidates? (use smell detection tools)
* How to prioritize / identify what to refactor first? (use reports from design analysis tools)
* How do I identify dependencies and evaluate impact of refactoring? (use visulization tools)
* How to I actually perform refactoring? (Use IDE support for automated refactoring and use them!)
Deriving from a rich experience in using tools for refactoring in real-world projects, this talk takes you through a whirl-wind tour of refactoring tools (of course for Java). What's more, this talk includes quick demos of some of these tools so you can see them in action.
Presented in BoJUG meetup on 19th Jan in Bangalore - https://www.meetup.com/BangaloreOpenJUG/events/257183518/
Please check out the workshop "AI meets Blockchain" at HIPC 2018, in Bangalore: http://hipc.org/ai-blockchain/
HIPC is a premier conference and hence getting a paper accepted in HIPC workshop would be quite an accomplishment for any blockchain/AI enthusiast. Check out the details in this poster on submissions.
I have been fortunate to have worked with some geeks with incredible coding skills. I felt amazed at how they can play games with compilers, perform magic with their incantations on the shell, and solve some insanely complex algorithm problems with ease. I naively assumed that they are going to achieve greatness in near future. Alas, I was wrong. Really wrong. [Read the rest of the article ... ]
Many students reach out to me asking for project ideas they can do as a summer project for learning. Here is an interesting project idea - implement your own java disassembler (and expand it to a VM later).
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
This presentation provides an overview of recently concluded Bangalore Container Conference (07-April-2017). See www.containerconf.in for more details.
Bangalore Container Conference 2017 (BCC '17) is the first conference on container technologies in India happening on 07th April. Organizations are increasingly adopting containers and related technologies in production.Hence, the main focus of this conference is “Containers in Production”. This one-day conference sets the perfect stage for container enthusiasts, developers, users and experts to meet together and learn from each others experiences.
Presented in Bangalore Open Java User Group on 21st Jan 2017
Awareness of design smells - Design comes before code. A care at design level can solve lot of problems.
Indicators of common design problems - helps developers or software engineers understand mistakes made while designing and apply design principles for creating high-quality designs. This presentation provides insights gained from performing refactoring in real-world projects to improve refactoring and reduce the time and costs of managing software projects. The talk also presents insightful anecdotes and case studies drawn from the trenches of real-world projects. By attending this talk, you will know pragmatic techniques for refactoring design smells to manage technical debt and to create and maintain high-quality software in practice. All the examples in this talk are in Java.
Bangalore Container Conference 2017 (BCC '17) is the first conference on container technologies in India. Organizations are increasingly adopting containers and related technologies in production. Hence, the main focus of this conference is “Containers in Production”. This one-day conference sets the perfect stage for container enthusiasts, developers, users and experts to meet together and learn from each others experiences.
This presentation covers quiz questions prepared for the Core Java meetup on 1st October in Accion Labs. It has questions from "Java best practices", "bytecodes", and "elastic search".
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Jdj Foss Java Tools
1. FEATURE
Uncommon Java Bugs
Detecting them with FOSS tools
by S.G. Ganesh
A
ny large Java source base can have insidious and work schedules results in code that is often substandard
subtle bugs. Every experienced Java programmer and filled with bugs. So, because of practical problems,
knows that finding and fixing these bugs can be most code developed in the real world has bugs and it’s
difficult and costly. Fortunately, there are a large worthwhile using static analysis tools to find them and fix
number of free open source Java tools available that can them.
be used to find and fix defects early in the development In this article we’ll see an uncommon defect and intro-
lifecycle. In this article, we’ll look at a few examples of duce a tool that detects it. We do this for two reasons: to
specific uncommon or unusual defects that can happen in illustrate the kind of unusual problems that can happen
code and see how different Java static analysis tools detect in the code and to introduce a FOSS tool that’s suitable for
them. detecting this kind of problem.
Testing Jlint
As software gets more complex and ubiquitous, it What does this program print?
becomes more difficult to ensure high-quality code. One
common method of finding bugs is testing. But testing class LongVal {
can’t cover all paths and possibilities or enforce good public static void main(String[] s) {
programming practices. Expert knowledge in the form of long l = 0x1l;
manual code review by peers is one of the best ways to System.out.format(“%x”, l);
ensure good code quality. Code review is often used as a }
mandatory process step for improving the code and for }
finding the problems early in the software lifecycle.
Since testing and manual code review processes are When you run it, it prints 1, not 11 – why? Let’s use a
resource-intensive, it would be helpful to use automated
tools to review code. Static analysis tools help consid- Benefits of Using FOSS Java Static Analysis Tools
NEED erably in detecting the problems early in the software
HEAD lifecycle and help enhance the quality of the code Using Java static analysis tools can significantly improve the quality
significantly. of code. Although static analysis tools can’t cover all the paths or pos-
SHOT
There are many high-quality Java tools available in the sibilities, it provides significant help in providing coverage in detecting
open source domain. While it’s true that Java programs problems early in code; such tools can also point out programming prob-
S. G. Ganesh is a research don’t suffer from traditional C/C++ problems like memory lems and warn of violations of important and well-accepted program-
engineer at Siemens (Corpo- issues and major portability issues, Java software does suf- ming rules and recommendations.
rate Technology), Bangalore. fer quality problems like reliability, efficiency, maintain- Using static analysis tools has many attractive benefits. A few of the
Prior to Siemens, he worked ability, and security. A brief discussion on benefits of using salient benefits of most of these tools are listed here. Most of the Java
at Hewlett-Packard for FOSS Java tools is given in the sidebar. FOSS tools:
around five years. His areas Before getting into the meat of the matter, let’s discuss • Can cover code that’s not covered by testing or dynamic analysis
of interest are programming why bugs happen. First, it’s important to recognize that • Find many unusual or uncommon bugs that are usually missed
languages and compilers. His everyone makes mistakes, even experts. Second, compil- during testing or manual code review
latest book is 60 Tips on Ob- ers only check for syntax and semantic violations. Errors • Work even on partial code – fully compilable source isn’t always
ject Oriented Programming in language or API use, which manifest themselves as needed
(ISBN-13 978-0-07-065670-3) bugs, aren’t detected by compilers: This is left to static • Easily integrate with popular IDEs, so it’s comfortable to use them in
published by Tata McGraw- analysis tools and it’s important to use them to detect cod- your favorite environment
Hill, New Delhi. ing problems. Third, programmers and engineers are un- • Are usually easy-to-run –with just a button click from your IDE
der constant pressure to “get-the-work-done” under tight • Are absolutely free and high-quality
sgganesh@gmail.com schedules; working under “almost-impossible-to-meet”
10 May 2008 JDJ.SYS-CON.com
2. tool to detect the problem. The antic tool (that’s part of
JLint) finds it:
$antic –java LongVal.java
LongVal.java:3:26: May be ‘l’ is used instead of ‘1’ at the end of
integer constant
The programmer, possibly by mistake, typed ‘l’ (English
letter l) instead of ‘1’ (number one)!
long l = 0x1l;
To avoid this problem, it’s best to use ‘L’ (upper case
letter L) as the suffix for long constants instead of ‘l’ (lower
case letter l).
Antic is part of the Jlint tool that’s meant to find prob- Figure 1 FindBugs detects the check-for-equality-to-NaN problem
lems related to C syntax. There are quite a few coding
problems that are common to languages that use C-like
syntax. The problem we saw now is just one such problem.
Jlint ferrets out Java inconsistencies and bugs. It’s not a
very sophisticated tool and if you don’t have experience
using static analysis tools, JLint is a good tool to start with.
Antic works on Java source files and Jlint works on Java
class file builds. It’s a command line tool and easy-to-use.
It’s available at http://jlint.sourceforge.net.
Figure 2 Test.java program results in NullPointerException
FindBugs
What does this program print?
class NaNTest {
public static void main(String[] s) {
double d = getVal();
if(d == Double.NaN)
System.out.println(“d is NaN”);
} Figure 3 The DeadLock.java program results in a “deadlock condition”
private static double getVal() {
return Double.NaN;
} PMD
} What’s wrong with the program in Listing 1? If you
try to run it (as shown in Figure 2) you’ll get a NullPointer-
You might be surprised to find that it doesn’t print any- Exception!
thing! What went wrong? The FindBugs tool detects the What could have gone wrong? PMD detects it and warns
problem and warns us about it (see Figure 1). of the problem:
The bug is that the condition (NaN == NaN) evaluates
to false! In the condition (d == Double.NaN), this code $ pmd Test.java text design
checks to see if a floating-point value is equal to the spe- Test.java:3 Overridable method ‘foo’ called during object con-
cial “Not A Number” value. The IEEE 754 floating-point struction
standard provides the special semantics of NaN: no value
is equal to NaN, including NaN itself. So, the check (d == The bug in this program is that the constructor of
Double.NaN) always evaluates to false. The correct check the Base class calls an overridden method. Construc-
to use is the condition check Double.isNaN(x). tors don’t support runtime polymorphism since derived
The FindBugs tool detects this problem and aptly objects aren’t constructed when the base class constructor
names it “Doomed test for equality to NaN”. executes. The virtual method foo is called from the base
The FindBugs tool is excellent. It detects correctness class constructor. Since foo is overridden, the overridden
problems, multithreading issues, performance problems, foo calls the toString method from I, which isn’t initial-
and bad practices. It has less false positives and warns ized yet (note that i gets initialized only after the Derived
of only critical or important problems that are likely constructor has completed executing). Because of this, the
to be actual defects in code. So, if you’re pressed for time program terminates with a NullPointerException. For this
and want to look at only important problems, this tool reason, it’s not a recommended programming practice to
will suit you. It runs on Java class/jar files, so no Java call overridable methods from constructors.
source files are needed to use it. And it runs in a nice The PMD tool checks for problems like possible bugs,
standalone GUI. You can download it at http://findbugs. design rule violations, duplicates, sub-optimal or dead
sourceforge.net/. code, suggestions for migration to newer JDK versions,
JDJ.SYS-CON.com May 2008 11
3. FEATURE
J2EE, JavaBeans, JSP, and JUnit rules. It works on Java Acquiring multiple locks is not a recommended program-
source files and can be used from command lines. Plug- ming practice. However, it’s often required in practice, so
ins for popular IDEs like Eclipse, JBuilder, and JCreator when we need to acquire multiple locks, we should ensure
are also available. You can download it from http://pmd. that we acquire them in the same order in the code.
sourceforge.net/. Alternatively, we can consider using non-blocking locks
when we attempt to acquire multiple locks. The tryLock meth-
QJ-Pro od in the java.util.concurrent.locks.Lock interface provides
What’s wrong with the program in Listing 2? this ability. It’s also recommended to release locks quickly and
It’s likely that the program will hang after running success- not hold the locks for a long time; so, it’s not recommended to
fully for few times as shown in Figure 3; in other words, this use sleep/wait methods after acquiring a lock; consider using
program can lead to a “deadlocked condition” (the program the wait/notify mechanism instead to avoid deadlocks be-
actually hint at this: the name of the class is Deadlock!). cause of holding a lock for a long time waiting for a condition
The QJ-Pro tool detects it as shown in Figure 4. to occur.
The bug in this code is that the code acquires two locks in The QJ-Pro tool checks for problems like conformance to
opposite order; and after that a sleep/wait method is called coding standards, coding best practices, misuse of features,
– this condition will usually result in a deadlock. and APIs. It gives lots of violations by default, so you’d have to
Locks are the basic Java synchronization mechanism. Using spend some time selecting the list of rules you want to run for
locks ensures exclusive ownership for a thread while executing your project. It works on Java source files and is easy-to-use in
a critical section. Incorrect use of synchronization can lead to its standalone GUI version (shown in Figure 5). You can use its
deadlocks. plug-ins with popular IDEs like Eclipse, JBuilder, JDeveloper
A big problem with deadlocks (as with most multithreading plug-ins or Ant. You can get QJ-Pro from http://qjpro.source-
problems) is that deadlocks are “non-deterministic” – they forge.net/.
need not reproduce consistently, and so it’s difficult to detect,
reproduce, and fix problems related to deadlocks. Other Tools
Acquiring multiple locks is prone to deadlock, particularly Other than the four tools covered here – Jlint, FindBugs,
if not done in the same order or if the sleep()/wait() in the PMD, and QJ-Pro – there are many other FOSS tools avail-
Thread is called after acquiring locks. In this program, foo and able. For example, CheckStyle checks for adherence to coding
bar acquire locks in opposite order and call sleep(). Hence standards such as Sun’s. You can get it from http://checkstyle.
deadlock occurs. sourceforge.net/. JCSC (Java Coding Style Checker) checks for
coding style adherence and for common bugs. You can get it at
http://jcsc.sourceforge.net/. There are many more useful tools
like Classycle, Condenser, DoctorJ, and JarAnalyzer. More in-
formation and links on Java tools is provided in the Resource
section.
Conclusion
We saw four specific static analysis tools that can be used to
detect not-so-common defects in code. They are free, easy-to-
integrate with IDEs, and easy-to-use. It’s highly recommended
to use such tools to improve the quality of the software by
detecting and fixing bugs early in the software lifecycle.
Figure 4 QJ-Pro detects deadlock because of acquiring multiple locks
Resources
• If you’re interested in a list of the Java FOSS static analysis
tools available, check http://java-source.net/open-source/
code-analyzers.
• “A Comparison of Bug Finding Tools for Java” by Nick
Rutar, Christian B. Almazan, and Jeffrey S. Foster from
the University of Maryland provides a detailed technical
comparison of Bandera, ESC/Java, FindBugs, JLint and
PMD tools. See http://www.cs.umd.edu/~jfoster/papers/
issre04.pdf.
• If you’re using Eclipse, it’s very convenient to use Java
tools as plug-ins. The list of available plug-ins for Java is at
http://www.eclipseplugincentral.com/Web_Links-index-
req-viewcatlink-cid-14-orderby-rating.html.
• The book Java Puzzlers: Traps, Pitfalls, and Corner Cases
by Joshua Bloch and Neal Gafter covers many interesting
bugs that can happen in code. Check the link http://www.
Figure 5 QJ-Pro detects deadlock because of acquiring multiple locks javapuzzlers.com/.
12 May 2008 JDJ.SYS-CON.com
4. Listing 1 synchronized(That.class) {
class Base { Thread.currentThread().sleep(10);
public Base() { }
foo(); }
} }
public void foo() { public static void bar() throws InterruptedException {
System.out.println(“In Base’s foo “); synchronized(That.class) {
} synchronized(This.class) {
} Thread.currentThread().sleep(10);
}
class Derived extends Base { }
public Derived() { }
i = new Integer(10);
} public void run() {
public void foo() { try {
System.out.println(“In Derived’s foo “ foo();
+ i.toString()); bar();
} } catch (InterruptedException e) {
private Integer i; System.out.println(“Caught interrupted
} exception”);
}
class Test { }
public static void main(String [] s) { }
new Derived().foo();
} class DeadLock {
}
public static void main(String []s) {
DoSynchronize pc = new DoSynchronize();
Thread t1 = new Thread(pc);
Listing 2
class This {} Thread t2 = new Thread(pc);
class That {}
t1.start();
t2.start();
class DoSynchronize implements Runnable {
}
public static void foo() throws InterruptedException {
synchronized(This.class) { }
JDJ.SYS-CON.com May 2008 13