I'm trying to understand occurrence of ConcurrentModificationExceptionin below program.  import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;  public class ConcurentHashMapExample {      public static void main(String[] args) {          Map&lt;String,String&gt; myMap = new ConcurrentHashMap&lt;String,String&gt;();         myMap.put("1", "1");         myMap.put("2", "1");         myMap.put("3", "1");         myMap.put("4", "1");         myMap.put("5", "1");         myMap.put("6", "1");         System.out.println("ConcurrentHashMap before iterator: "+myMap);         Iterator&lt;String&gt; it = myMap.keySet().iterator();          while(it.hasNext()){             String key = it.next();             if(key.equals("3")) myMap.put(key+"new", "new3");         }         System.out.println("ConcurrentHashMap after iterator: "+myMap);          myMap = new HashMap&lt;String,String&gt;();         myMap.put("1", "1");         myMap.put("2", "1");         myMap.put("3", "1");         myMap.put("4", "1");         myMap.put("5", "1");         myMap.put("6", "1");         System.out.println("HashMap before iterator: "+myMap);         Iterator&lt;String&gt; it1 = myMap.keySet().iterator();          while(it1.hasNext()){             String key = it1.next();             if(key.equals("3")) myMap.put(key+"new", "new3");         }         System.out.println("HashMap after iterator: "+myMap);     }  }   Exception:  ConcurrentHashMap before iterator: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1} ConcurrentHashMap after iterator: {1=1, 2=1, 3=1, 4=1, 5=1, 3new=new3, 6=1} HashMap before iterator: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1} Exception in thread "main" java.util.ConcurrentModificationException     at java.util.HashMap$HashIterator.nextNode(Unknown Source)     at java.util.HashMap$KeyIterator.next(Unknown Source)     at ConcurentHashMapExample.main(ConcurentHashMapExample.java:39)   My doubt is why ConcurrentHashMap takes care of any new entry in the map at runtime whereas HashMap throws ConcurrentModificationException ?  I'm not able to understand this reason "Iterator on Collection objects are fail-fast i.e any modification in the structure or the number of entry in the collection object will trigger this exception thrown by iterator.  My understanding says, myMap is pointing to two different objects sequentially, then how this error could happen ? Am I wrong ?  Please help to understand why its happening and reason for that. What is fail-fast as well ?  Thanks
78
We all know you can't do the following because of ConcurrentModificationException:  for (Object i : l) {     if (condition(i)) {         l.remove(i);     } }   But this apparently works sometimes, but not always. Here's some specific code:  public static void main(String[] args) {     Collection&lt;Integer&gt; l = new ArrayList&lt;&gt;();      for (int i = 0; i &lt; 10; ++i) {         l.add(4);         l.add(5);         l.add(6);     }      for (int i : l) {         if (i == 5) {             l.remove(i);         }     }      System.out.println(l); }   This, of course, results in:  Exception in thread "main" java.util.ConcurrentModificationException   Even though multiple threads aren't doing it. Anyway.  What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?  I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.
5063
I have a production server running with the following flag: -XX:+HeapDumpOnOutOfMemoryError  Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it.  Any ideas?
33779
I came across some very strange behaviour when working with a Map with Decimal keys today. It seems like the Decimal type can't handle Integer assignments properly, but allows them nonetheless. I've written some example code demonstrating the problem:  Map&lt;Decimal, String&gt; m = new Map&lt;Decimal, String&gt;(); m.put(1234, 'Integer key');  m.put(1234.0, 'Decimal key'); m.put(1234.5, 'Decimal Unique key');  System.debug(m.get(1234));      // =&gt; Integer key, why was this not overwritten if 1234 == 1234.0? System.debug(m.get(1234.0));    // =&gt; Decimal key System.debug(m.get(1234.5));    // =&gt; Decimal Unique key  System.debug(m);        //Order of insertion matters, newest value does not override existing one but is not shown on map printout... for(Decimal d : m.keySet()){     System.debug(d);    //...unless you print it out yourself, because this loop shows all the keys }  //Sanity check System.debug(1234 == 1234.0); //True  //Digging deeper Decimal fake_d = 1234; Decimal real_d = 1234.0; Integer real_i = 1234; //Integer fake_i = 1234.0; //Illegal assignment, typechecking only works one way, it seems  //More sanity checks System.debug(fake_d == real_d); //True (Except when used in a Map, apparently) System.debug(fake_d == real_i); //True  System.debug(m.get(real_i)); // =&gt; Integer key System.debug(m.get(fake_d)); // =&gt; Integer key, even with fake_d explicitely declared as a Decimal type, it still pretends to be an Integer. System.debug(m.get(real_d)); // =&gt; Decimal key   I found this behaviour when I tried to fetch a value from a map using a Decimal sObject field, only to find that the keys I used to populate the Map (coming from a different Decimal field) were interpreted as Integers since they had no real decimal digits.  Maybe using Decimals as Map keys is not supported for some reason? Is it expected behaviour for 1234 and 1234.0 being distinct values in this case or is this an oversight in the Map implementation?
115421
In this simplified example I have a generic class, and a method that returns a Map regardless of the type parameter.  Why does the compiler wipe out the types on the map when I don't specify a type on the containing class?  import java.util.Map;  public class MyClass&lt;T&gt; {     public Map&lt;String, String&gt; getMap()     {            return null;     }      public void test()     {            MyClass&lt;Object&gt; success = new MyClass&lt;Object&gt;();         String s = success.getMap().get("");          MyClass unchecked = new MyClass();         Map&lt;String, String&gt; map = unchecked.getMap();  // Unchecked warning, why?         String s2 = map.get("");          MyClass fail = new MyClass();         String s3 = fail.getMap().get("");  // Compiler error, why?     } }   I get this compiler error.  MyClass.java:20: incompatible types found   : java.lang.Object required: java.lang.String                 String s3 = fail.getMap().get("");  // Compiler error
3650
This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.    Can somebody clarify what is meant by immutable?  Why is a String immutable? What are the advantages/disadvantages of the immutable objects? Why should a mutable object such as StringBuilder be preferred over String and vice-verse?   A nice example (in Java) will be really appreciated.
84853
Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate?  I also believe the question, detail, and response is much better than the referenced question.  I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse.  I want to use the  to visualize some data I'm working with.  This code is organized like this:  ./com ./com/touchgraph ./com/touchgraph/graphlayout ./com/touchgraph/graphlayout/Edge.java ./com/touchgraph/graphlayout/GLPanel.java ./com/touchgraph/graphlayout/graphelements ./com/touchgraph/graphlayout/graphelements/GESUtils.java ./com/touchgraph/graphlayout/graphelements/GraphEltSet.java ./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java ./com/touchgraph/graphlayout/graphelements/Locality.java ./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java ./com/touchgraph/graphlayout/graphelements/TGForEachNode.java ./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java ./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java ./com/touchgraph/graphlayout/graphelements/VisibleLocality.java ./com/touchgraph/graphlayout/GraphLayoutApplet.java ./com/touchgraph/graphlayout/GraphListener.java ./com/touchgraph/graphlayout/interaction ./com/touchgraph/graphlayout/interaction/DragAddUI.java ./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java ./com/touchgraph/graphlayout/interaction/DragNodeUI.java ./com/touchgraph/graphlayout/interaction/GLEditUI.java ./com/touchgraph/graphlayout/interaction/GLNavigateUI.java ./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java ./com/touchgraph/graphlayout/interaction/HVScroll.java ./com/touchgraph/graphlayout/interaction/HyperScroll.java ./com/touchgraph/graphlayout/interaction/LocalityScroll.java ./com/touchgraph/graphlayout/interaction/RotateScroll.java ./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java ./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java ./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java ./com/touchgraph/graphlayout/interaction/TGUIManager.java ./com/touchgraph/graphlayout/interaction/TGUserInterface.java ./com/touchgraph/graphlayout/interaction/ZoomScroll.java ./com/touchgraph/graphlayout/LocalityUtils.java ./com/touchgraph/graphlayout/Node.java ./com/touchgraph/graphlayout/TGAbstractLens.java ./com/touchgraph/graphlayout/TGException.java ./com/touchgraph/graphlayout/TGLayout.java ./com/touchgraph/graphlayout/TGLensSet.java ./com/touchgraph/graphlayout/TGPaintListener.java ./com/touchgraph/graphlayout/TGPanel.java ./com/touchgraph/graphlayout/TGPoint2D.java ./com/touchgraph/graphlayout/TGScrollPane.java ./TG-APACHE-LICENSE.txt ./TGGL ReleaseNotes.txt ./TGGraphLayout.html ./TGGraphLayout.jar   How do I add this project in Eclipse and get it compiling and running quickly?
73349
When I use an Iterator of Object I use a while loop (as written in every book learning Java, as Thinking in Java of Bruce Eckel):  Iterator it=...  while(it.hasNext()){     //... }   but sometime i saw than instead somebody use the for loop:  Iterator it=... for (Iterator it=...; it.hasNext();){     //... }   I don't' understand this choice:    I use the for loop when I have a collection with ordinal sequence (as array) or with a special rule for the step (declared generally as a simple increment counter++).  I use the while loop when the loop finishes with I have'nt this constraints but only a logic condition for exit.   It's a question of style-coding without other cause or it exists some other logic (performance, for example) that I don't' know?  Thanks for every feedback
81002
When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts?  Edit: there is a native component, this is an SWT application on win32.
68536
In several modern programming languages (including C++, Java, and C#), the language allows  to occur at runtime without raising any kind of error condition.  For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow.  (For brevity, the method also doesn't handle the case where the specified list is a null reference.)    //Returns the sum of the values in the specified list. private static int sumList(List&lt;int&gt; list) {     int sum = 0;     foreach (int listItem in list)     {         sum += listItem;     }     return sum; }   If this method is called as follows:  List&lt;int&gt; list = new List&lt;int&gt;(); list.Add(2000000000); list.Add(2000000000); int sum = sumList(list);   An overflow will occur in the sumList() method (because the int type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.  Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's , or the  keyword and  compiler switch in C#.  However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow.  It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow.  (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually .)  Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?  Are there other reasons for this language design decision as well, other than performance considerations?
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
54815
I'm looking for a class in java that has key-value association, but without using hashes.  Here is what I'm currently doing:   Add values to a Hashtable. Get an iterator for the Hashtable.entrySet(). Iterate through all values and:   Get a Map.Entry for the iterator. Create an object of type Module (a custom class) based on the value. Add the class to a JPanel.  Show the panel.   The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).  I would use an ArrayList or Vector for this, but later in the code I need to grab the Module object for a given Key, which I can't do with an ArrayList or Vector.  Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable based on when they were added?  Thanks!
98177
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.  Is there a more elegant way of doing this? Perhaps an API call that will reveal this?  Here's some rough code of what I'm talking about:  Throwable t = null;  try {       stream.write(buffer);  } catch(IOException e) {     t = e;   //Need to save this exception for finally     throw e; } finally {        try {        stream.close();   //may throw exception    } catch(IOException e) {       //Is there something better than saving the exception from the exception block?       if(t!=null) {          //propagate the read exception as the "cause"--not great, but you see what I mean.          throw new IOException("Could not close in finally block: " + e.getMessage(),t);       } else {          throw e;  //just pass it up       }        }//end close }   Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.  Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?  This question actually spawned from comments in  that raised an interesting question.
7194
I read about Java's type erasure .  When does type erasure occur? At compile time or runtime? When the class is loaded? When the class is instantiated?  A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?  Consider the following example: Say class A has a method, empty(Box&lt;?&nbsp;extends&nbsp;Number&gt;&nbsp;b). We compile A.java and get the class file A.class.  public class A {     public static void empty(Box&lt;? extends Number&gt; b) {} }     public class Box&lt;T&gt; {}   Now we create another class B which invokes the method empty with a non-parameterized argument (raw type): empty(new Box()). If we compile B.java with A.class in the classpath, javac is smart enough to raise a warning. So A.class has some type information stored in it.  public class B {     public static void invoke() {         // java: unchecked method invocation:         //  method empty in class A is applied to given types         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         // java: unchecked conversion         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         A.empty(new Box());     } }   My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen?
87341
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.   if the input array is {} , isMaxMinEqual should return false (array must have at least two different elements) status = false; if the input array is {2}, isMaxMinEqual should return false (array must have at least two different elements). if the input array is {1,1,1,1,1,1}, isMaxMinEqual should return false (array must have at least two different elements).  if the input array is {2,4,6,8,11}, isMaxMinEqual should return true (Both max value(11) and min value 2 appear exactly one time). if the input array is {-2,-4,-6,-8,-11}, isMaxMinEqual should return true(Both max value(-2) and min value -11 appear exaclty one time).   I wrote the class MaxMin which satisfied the above condition.  public class MaxMin {  public static void main(String args[]) {     System.out.println("The result is: " + isMaxMinEqual(new int[]{2, 2})); }  public static boolean isMaxMinEqual(int[] a) {     boolean status = false;     int count = 0;     if (a.length &lt; 2) {         status = false;         return status;     }     for (int i = 1; i &lt; a.length; i++) {         if (a[i - 1] != a[i]) {             count++;         }     }      int max = a[0];     int min = a[0];     for (int i = 0; i &lt; a.length; i++) {         if (a[i] &gt; max) {             max = a[i];         } else if (a[i] &lt; min) {             min = a[i];         }     }      int maxCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == max) {             maxCount++;         }     }      int minCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == min) {             minCount++;         }     }     System.out.println(count);     System.out.println("max is: " + max);     System.out.println("min is: " + min);     System.out.println("Max Count is: " + maxCount);     System.out.println("Min Count is: " + minCount);      if (maxCount == minCount &amp;&amp; count &gt;= 1) {         status = true;     }      return status; } }
56415
I have four foreach loops that iterate through the collections and based on a condition do something.   Here is the code that I am writing now:  boolean breakFlag = false; String valueFromObj2 = null; String valueFromObj4 = null; for(Object1 object1: objects){   for(Object2 object2: object1){     // I get some value from object2     valueFromObj2 = object2.getSomeValue();     for(Object3 object3 : object2){       for(Object4 object4: object3){        // Finally I get some value from Object4.        valueFromObj4 = object4.getSomeValue();        // Compare with valueFromObj2 to decide either to break all the foreach loop        breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );        if(breakFlag){break;}       } // fourth loop ends here       if(breakFlag){break;}     } // third loop ends here     if(breakFlag){break;}   } // second loop ends here   if(breakFlag){break;} } // first loop ends here   The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack&nbsp;Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.
81862
Does string immutability work by statement, or by strings within a statement?   For example, I understand that the following code will allocate two strings on the heap.  string s = "hello "; s += "world!";   "hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?  string s = "goodbye " + "cruel world!";
22087
This is a poll of sorts about common concurrency problems in Java.  An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing.  I'm interested both in a breadth of possible issues but also in what issues are most common.  So, please leave one specific answer of a Java concurrency bug per comment and vote up if you see one you've encountered.