Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * fb-contrib - Auxiliary detectors for Java programs
   * Copyright (C) 2005-2013 Dave Brosius
   *
   * This library is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 package com.mebigfatguy.fbcontrib.detect;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  org.apache.bcel.classfile.Code;
 import  org.apache.bcel.generic.Type;
 
 import  edu.umd.cs.findbugs.BugInstance;
 import  edu.umd.cs.findbugs.BugReporter;
 import  edu.umd.cs.findbugs.BytecodeScanningDetector;
 import  edu.umd.cs.findbugs.OpcodeStack;
 import  edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
 import  edu.umd.cs.findbugs.ba.ClassContext;

finds methods that create and populate collections, and while knowing the end size of those collections, does not pre allocate the collection to be big enough. This just causes unneeded reallocations putting strain on the garbage collector.
 
 @CustomUserValue
 public class PresizeCollections extends BytecodeScanningDetector {
 
     private static final Set<StringPRESIZEABLE_COLLECTIONS = new HashSet<String>();
     static {
         .add("java/util/ArrayBlockingQueue");
         .add("java/util/ArrayDeque");
         .add("java/util/ArrayList");
         .add("java/util/HashMap");
         .add("java/util/HashSet");
         .add("java/util/LinkedBlockingQueue");
         .add("java/util/LinkedHashMap");
         .add("java/util/LinkedHashSet");
         .add("java/util/PriorityBlockingQueue");
         .add("java/util/PriorityQueue");
         .add("java/util/Vector");
     }
 
     private BugReporter bugReporter;
     private OpcodeStack stack;
     private int allocNumber;
     private Map<IntegerIntegerallocLocation;
     private Map<IntegerList<Integer>> allocToAddPCs;
     private List<DownBranchdownBranches;
 
     public PresizeCollections(BugReporter bugReporter) {
         this. = bugReporter;
     }

    
overrides the visitor to initialize the opcode stack

Parameters:
classContext the context object that holds the JavaClass being parsed
 
     public void visitClassContext(ClassContext classContext) {
         try {
              = new OpcodeStack();
              = new HashMap<IntegerInteger>();
              = new HashMap<IntegerList<Integer>>();
              = new ArrayList<DownBranch>();
             super.visitClassContext(classContext);
         } finally {
              = null;
              = null;
              = null;
              = null;
         }
     }

    
implements the visitor to reset the opcode stack

Parameters:
obj the context object of the currently parsed code block
 
     @Override
     public void visitCode(Code obj) {
         .resetForMethodEntry(this);
         = 0;
        .clear();
        .clear();
        .clear();
        super.visitCode(obj);
        for (List<Integerpcs : .values()) {
            if (pcs.size() > 16) {
                .reportBug(new BugInstance(this"PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY)
                .addClass(this)
                .addMethod(this)
                .addSourceLine(thispcs.get(0)));
            }
        }
    }

    
implements the visitor to look for creation of collections that are then populated with a known number of elements usually based on another collection, but the new collection is not presized.

Parameters:
seen the opcode of the currently parsed instruction
    @Override
    public void sawOpcode(int seen) {
        boolean sawAlloc = false;
        try {
            .precomputation(this);
            
            switch (seen) {
            case INVOKESPECIAL:
                String clsName = getClassConstantOperand();
                if (.contains(clsName)) {
                    String methodName = getNameConstantOperand();
                    if ("<init>".equals(methodName)) {
                        String signature = getSigConstantOperand();
                        if ("()V".equals(signature)) {
                            sawAlloc = true;
                        }
                    }
                }
            break;
            case INVOKEINTERFACE:
                String methodName = getNameConstantOperand();
                if ("add".equals(methodName) || "addAll".equals(methodName)) {
                    String signature = getSigConstantOperand();
                    Type[] argTypes = Type.getArgumentTypes(signature);
                    if ((argTypes.length == 1) && (.getStackDepth() > 1)) {
                        OpcodeStack.Item item = .getStackItem(1);
                        Integer allocNum = (Integeritem.getUserValue();
                        if (allocNum != null) {
                            if ("addAll".equals(methodName)) {
                                .remove(allocNum);
                            } else {
                                List<Integerlines = .get(allocNum);
                                if (lines == null) {
                                    lines = new ArrayList<Integer>();
                                    .put(allocNumlines);
                                }
                                lines.add(getPC());
                            }
                        }
                    }
                } else if ("put".equals(methodName) || "putAll".equals(methodName)) {
                    String signature = getSigConstantOperand();
                    Type[] argTypes = Type.getArgumentTypes(signature);
                    if ((argTypes.length == 2) && (.getStackDepth() > 2)) {
                        OpcodeStack.Item item = .getStackItem(2);
                        Integer allocNum = (Integeritem.getUserValue();
                        if (allocNum != null) {
                            if ("putAll".equals(methodName)) {
                                .remove(allocNum);
                            } else {
                                List<Integerlines = .get(allocNum);
                                if (lines == null) {
                                    lines = new ArrayList<Integer>();
                                    .put(allocNumlines);
                                }
                                lines.add(getPC());
                            }
                        }
                    }
                }
                break;
            case LOOKUPSWITCH:
            case TABLESWITCH:
                int[] offsets = getSwitchOffsets();
                if (offsets.length > 1) {
                    int secondCase = offsets[1] + getPC();
                    DownBranch db = new DownBranch(getPC(), secondCase);
                    .add(db);
                }
                break;
            case IFEQ:
            case IFNE:
            case IFLT:
            case IFLE:
            case IF_ICMPEQ:
            case IF_ICMPNE:
            case IF_ICMPLT:
            case IF_ICMPGE:
            case IF_ICMPGT:
            case IF_ICMPLE:
            case IF_ACMPEQ:
            case IF_ACMPNE:
            case GOTO:
            case GOTO_W:
                if (getBranchOffset() < 0) {
                    int target = getBranchTarget();
                    Iterator<Map.Entry<IntegerList<Integer>>> it = .entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<IntegerList<Integer>> entry = it.next();
                        Integer allocLoc = .get(entry.getKey());
                        if ((allocLoc != null) && (allocLoc.intValue() < target)) {
                            List<Integerpcs = entry.getValue();
                            for (Integer pc : pcs) {
                                if (pc > target) {
                                    int numDownBranches = countDownBranches(targetpc);
                                    if (numDownBranches == 1) {
                                        .reportBug(new BugInstance(this"PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY)
                                                    .addClass(this)
                                                    .addMethod(this)
                                                    .addSourceLine(thispc));
                                        it.remove();
                                    }
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    DownBranch db = new DownBranch(getPC(), getBranchTarget());
                    .add(db);
                }
                break;
                
            case IFNULL:
            case IFNONNULL:
            case IFGE:
            case IFGT:
                //null check and >, >= branches are hard to presize
                break;
            }
        } finally {
            .sawOpcode(thisseen);
            if (sawAlloc) {
                if (.getStackDepth() > 0) {
                    OpcodeStack.Item item = .getStackItem(0);
                    ++;
                    item.setUserValue(Integer.valueOf());
                    .put(Integer.valueOf(), Integer.valueOf(getPC()));
                }
            }
        }
    }
    private int countDownBranches(int loopTopint addPC) {
        int numDownBranches = 0;
        for (DownBranch db : ) {
            if ((db.fromPC > loopTop) && (db.fromPC < addPC) && (db.toPC > addPC)) {
                numDownBranches++;
            }
        }
        return numDownBranches;
    }
    static class DownBranch {
        public int fromPC;
        public int toPC;
        public DownBranch(int fromint to) {
             = from;
             = to;
        }
        @Override
        public String toString() {
            return "DownBranch[From: " +  + " To: " +  + "]";
        }
    }
New to GrepCode? Check out our FAQ X