Concurrent modification exception while iterating through list
Hi,
I have a list of objects. I use for each loop in java to iterate through that list of objects and display them.
The problem is that while iterating other thread can add or remove some objects from that list, and I get ConcurrentModificationException.
How can I handle this problem. How can I be sure that I am iteration through the updated list.
Thank you
Synchonize on the list before iterating through it, and make sure that other code also synchronizes on the list before adding to it or removing from it. Using a list implementation that simply synchronizes all the methods (e.g. Vector) will not do that, you have to do it yourself.
Similar Messages
-
Revision: 1043
Author: [email protected]
Date: 2008-03-31 15:22:13 -0700 (Mon, 31 Mar 2008)
Log Message:
Bug: LCDS-184 - Concurrent modification exception thrown during remote subscription management
QA: Yes
Doc: No
Details:
Make the 'subscriptions' set in MessageClient/RemoteMessageClient concurrent modification safe.
Ticket Links:
http://bugs.adobe.com/jira/browse/LCDS-184
Modified Paths:
blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/services/messaging/RemoteMess ageClient.java -
Revision: 1044
Author: [email protected]
Date: 2008-03-31 15:23:07 -0700 (Mon, 31 Mar 2008)
Log Message:
Bug: LCDS-184 - Concurrent modification exception thrown during remote subscription management
QA: Yes
Doc: No
Details:
Make the 'subscriptions' set in MessageClient/RemoteMessageClient concurrent modification safe.
Ticket Links:
http://bugs.adobe.com/jira/browse/LCDS-184
Modified Paths:
blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/MessageClient.java -
Concurrent modification exception inside fully synchronized code
Hello,
We have a private list
private LinkedList<ConnectionChannel> channels = new LinkedList<ConnectionChannel>();that is accessed by multiple threads. One is traversing the items and operating on them, while another thread is adding and removing items to the list. Each such access to the list is protected with
synchronized(channels) {
} scopes so that no simultanious access to this list is possible.
We do however get Concurrent Modification excpetions on this list when we do performance tests with heavy load on the sun server + heavy load on the java server itself. I cannot understand this problem in any other way that this must be a problem with the virtual machine! I know you guys probably will object to this furiously, but I am 100% sure that there is no logical error in my code.
We're running on jre 1.5..0_03. uname -a on my solaris host gives me:
SunOS trinity 5.8 Generic_108528-27 sun4u sparc SUNW,Sun-Fire-480R.
Best regards,
Helge FredriksenI'm very sure about this, yes. Here's all blocks where the list is used:
synchronized (channels) {
logger.info("Connecting observer channel from client at " + token.getSource());
channels.add(new ConnectionChannel(token, globalObserver));
synchronized (channels) {
if (logger.isDebugEnabled()) {
logger.debug("Sending local event to processing in " + channels.size() + " parallel channel(s)");
for (ConnectionChannel connectionChanel : channels) {
connectionChanel.send(event);
synchronized (channels) {
for (Iterator<ConnectionChannel> iterator = channels.iterator(); iterator.hasNext();) {
ConnectionChannel connectionChannel = iterator.next();
if (connectionChannel.getToken().getId().equals(token.getId())) {
iterator.remove();
logger.info("Removing connection channel to " + token.getSource());
return;
}and
synchronized (channels) {
for (ConnectionChannel channel : channels) {
channel.flush(5000);
} -
List Concurrent Modification Exception
The following codes throws the java.util.ConcurrentModificationException
public static void main(String[] args) {
List<Integer> list1 = new LinkedList<Integer>();
ListIterator head = list1.listIterator();
list1.add(1);
while(head.hasNext()) {
System.out.println(head.next());
}But if I put list1.add(1) before
ListIterator head = list1.listIterator();, then it runs fine.
I've googled the exception and get the idea that it is caused by 2 threads accessing the list. Where are the 2 threads?
Edited by: pinkyDeveloper on Feb 17, 2009 3:00 PMnothing to do with threads and everything to do with changing the list after getting the iterator and then iterating with the iterator. Don't do this unless you change the list through the iterator. You might want to read the API on LinkedList which states:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
Edited by: Encephalopathic on Feb 17, 2009 3:13 PM -
While iterating through cursor,system reset, refere to exception in thread
here is the exception,thanks.
====================== EXCEPTION ======================
NIP: C0A4FB54 XER: 20000000 LR: C0A5ABD0 SP: C53C2CB0 REGS: c53c2c00 TRAP: 0300
Not tainted
MSR: 00009032 EE: 1 PR: 0 FP: 0 ME: 1 IR/DR: 11
DAR: 0000000C, DSISR: 22000000
TASK = c109a000[43] 'SCH4' Last syscall: -1
last math 00000000 last altivec 00000000
GPR00: D9A66038 C53C2CB0 C109A000 D9800510 00000000 00000001 00000001 00000000
GPR08: 00000000 D9A7F990 D9A11530 00000000 FFFFFFFF 68EAF35D EB33E86E F9EDE7DD
GPR16: ECFBB73E 00141001 C60FDFFF EF7D6FFF 003FF000 C00E590C C00E0000 C00E5910
GPR24: C00E0000 C106C3A8 00000000 C00A0000 C00E56E8 C53C2D28 C0C216F4 C53C2CB0
Cpu Type: PPC603
task:SCH4 pid:43
Call backtrace:
c0c05a08 s_kth_c_thread_wrapper +3f3fa5f8 s_v2k_c_task_wrapper( )
c0c216f4 s_v2k_c_task_wrapper +3f3de90c s_OSS_Sche_c_ScheTaskEntry( 4 )
c08c40cc s_OSS_Sche_c_ScheTaskEntry +3f4 RunProcess( d9134090 )
c08c4888 RunProcess +30 DMA_MODE_WRITE( d9134090 )
c08cb8f8 DMA_MODE_WRITE +24 UniProcEntry( d9134090 )
c08c4920 UniProcEntry +3f73b6e0 processP15Timer( )
c091f074 processP15Timer +2e4 s_tk_15min_c_getAllMcuaddr( c53c2f88 )
c092120c s_tk_15min_c_getAllMcuaddr +54 Select( a, 0, 80000000, c53c2f58, c53c2f54, 0, 0 )
c094a0cc Select +3f6b5f34 __db_c_get_pp( d9a11530, c53c2e98,c53c2eb8, 10 )
c0a6aa2c __db_c_get_pp +120 __db_c_get( d9a11530, c53c2e98, c53c2eb8, 10 )
c0a5af84 __db_c_get +570 __db_c_idup( d9a11530, c53c2d80, 16 )
c0a5ab50 __db_c_idup +7c __db_cursor_int( d9800510, 0, 1, 1, 0, 0, c53c2d28 )
Stack: (0xc53c2cb0 to 0xc53c30b0)
2ca0: c53c2d10 6b2100a8 d9800510 00000000
2cc0: 00000001 00000001 00000000 00000000 c53c2d28 d9a7f990 aaaaaaca d9800950
2ce0: 00000000 c53c2d90 00000000 c53ad600 c53c2ac7 c00e6978 00000000 00000007
2d00: fffffffe d11c0200 c53c27ef c53c2d10 c53c2d60 c0a5abd0 d9a11530 c53c2d80
2d20: 00000016 d9800510 00000000 c00a0000 c00e56e8 d333f320 c0c216f4 c53c2d60
2d40: c53c2d70 c0c0bd0c d9800950 c00c8c40 00000000 d50553fc 00000000 c53c2d60
2d60: c53c2e00 c0a5b4f8 d9a11530 c53c2e98 c53c2eb8 00000010 d9800510 c00c8c40
2d80: 00000000 00000000 d9a7fad0 00000000 d9800950 d9800dd0 c0175b90 00000000
2da0: 00000000 00000016 00000000 00000000 c53c2e00 00000000 d9a11530 c53c2e98
2dc0: c53c2eb8 00000000 d9800510 0000000a 00000000 00000000 00000000 00000000
2de0: 0000000c d50553fc c00e0000 c53c2df0 c53c2e10 c08ce3a0 00000324 c53c2e00
2e00: c53c2e40 c0a6ab50 d9a11530 c53c2e98 c53c2eb8 00000010 d9800510 d9800950
2e20: 00000000 0000000
Edited by: Edgar Liu on Oct 27, 2008 3:58 PMHi,
Can you describe your problem in more detail? And some code snippet is quite helpful to solve the problem. So far the info you provided dose not say anything
David -
Iterating through List View Items using Group By and Jquery
In my listview to my document library, I am using grouping. For each group (using month), it lists all the documents pertaining to that particular month.
Using JQuery, I need to go through each item and parse them, but I'm having trouble finding a usable selector for the for/each function. My parsing code (JQuery) works, but since it uses the class of the table cell with a child anchor, it basically
finds the first item and then all the subsequent file names are named the same (instead of different names, like it should be).
Here's my current code that doesn't work (only the iteration and naming separately for each file - the parsing I'm doing seems to work):
$(".ms-wpContentDivSpace" ).each(function( index ) {
var val=$(".ms-vb2 a").html();
var val2=val.replace(/_/g," ");
$(".ms-vb2 a").html(val2);
any ideas?That's because
$(".ms-vb2 a").
is bringing back all the pieces that have that class with an anchor on the whole page, not just the ones in the .ms-wpContentDivSpace
I don't know the exact syntax, but I think you need to iterate through all the '.ms_vb2 a' items as well - there are multiple ones, and do something like this inside your other grouping
$(".ms-vb2 a").each(function(index) {
var val=$(this).html();
var val2=val.replace(/_/g," ")
$(this).html(val2);
That's not quite right but maybe that will help.
Robin -
Is there is any way/tag to iterate through the values in the list, other than h:datatable???
Doublepost, please continue here: [http://forums.sun.com/thread.jspa?threadID=5350782].
-
Concurrent modification exception. What is causing this?
Here is my the pasrt of code causing the exception I have put a line comment ti indicate the line where it occurs. In addition I would like to know the cause of this eception as its a first for me.
Here is the full exception ....
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:3
72)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Contact.modifyExisting(Contact.java:432)
at Phonebook1.actionPerformed(Phonebook1.java:236)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
95)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
a:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(BasicR
ootPaneUI.java:191)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2849)
at javax.swing.KeyboardManager.fireBinding(KeyboardManager.java:267)
at javax.swing.KeyboardManager.fireKeyboardAction(KeyboardManager.java:2
16)
at javax.swing.JComponent.processKeyBindingsForAllComponents(JComponent.
java:2926)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2918)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2812)
at java.awt.Component.processEvent(Component.java:5815)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.ja
va:1848)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboard
FocusManager.java:697)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeybo
ardFocusManager.java:962)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeybo
ardFocusManager.java:834)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFoc
usManager.java:661)
at java.awt.Component.dispatchEventImpl(Component.java:4282)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)and the code.......
if(modifiedWork.length()>0)
try
modifiedWorkNum = Integer.parseInt(modifiedWork);
} //////// THIS IS LINE 372
catch(Exception e)
JOptionPane.showMessageDialog(null,"You may only enter numbers for a valid phone number to try again press the modify nutton again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
}Thanks in advance...Would you mind looking at my modifyExisting method I apologise as it is long. I have icluded a line comment on line 432.
public void modifyExisting()
{// Start of modifyExisting()
int count = 0;
int count1 = 0;
int count2 = 0;
int modifiedCellNum, modifiedWorkNum, modifiedHomeNum = 0;
boolean validModify = true;
boolean found = false;
String currentHome = "";
String currentWork = "";
String currentCell = "";
if(phoneList.size() > 0)
String nameOfContactToEdit = JOptionPane.showInputDialog(null,"Please enter the name of the contact you wish to edit details for or press cancel to exit");
if(nameOfContactToEdit == null)
finish();
if(nameOfContactToEdit.trim().length()<= 0)
JOptionPane.showMessageDialog(null,"You have entered an invalid name. Please try again.","Error",JOptionPane.ERROR_MESSAGE);
modifyExisting();
validModify = false;
return;
String surnameOfContactToEdit = JOptionPane.showInputDialog(null,"Please enter the the surname for "+nameOfContactToEdit+" if one exists or press cancel to exit.");
if(surnameOfContactToEdit == null)
finish();
for(Person m: phoneList)
m = phoneList.get(count);
if((m.name).equals(nameOfContactToEdit.trim().toUpperCase())&&(m.surname).equals(surnameOfContactToEdit.trim().toUpperCase()))
currentHome = m.home;
currentWork = m.work;
currentCell = m.cell;
found = true;
count ++;
if(found == true)
String modifiedName = JOptionPane.showInputDialog("Please enter the new name for contact or press cancel to keep it as "+nameOfContactToEdit+".");
if(modifiedName == null)
modifiedName = nameOfContactToEdit;
if(modifiedName.trim().length()<= 0)
JOptionPane.showMessageDialog(null,"You have entered an invalid name. Please press the modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
return;
if(modifiedName.trim().length()>10)
JOptionPane.showMessageDialog(null,"You may not enter a new name longer than 10 characters long. Please try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
modifyExisting();
return;
String modifiedSurname = JOptionPane.showInputDialog("Please enter the new surname for contact or press cancel to keep it as "+surnameOfContactToEdit+".");
if(modifiedSurname == null)
modifiedSurname = surnameOfContactToEdit;
if(modifiedSurname.trim().length()>10)
JOptionPane.showMessageDialog(null,"You may not enter a surname longer than 10 characters long. Please try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
modifyExisting();
return;
String modifiedHome = JOptionPane.showInputDialog("Please enter a new home number for "+modifiedName+" or press cancel to keep it as is.");
if(modifiedHome == null)
modifiedHome = currentHome;
if(modifiedHome.length()>0)
try
modifiedHomeNum = Integer.parseInt(modifiedHome);
catch(Exception e)
JOptionPane.showMessageDialog(null,"You may only enter numbers for a valid phone number to try again press the modify nutton again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
if(modifiedHome.length() > 10)
JOptionPane.showMessageDialog(null,"You may not enter a number longer than 10 characters long. Please press the modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
String modifiedWork = JOptionPane.showInputDialog("Please enter a new home number for "+modifiedName+" or press cancel to keep it as is.");
if(modifiedHome == null)
modifiedWork = currentWork;
if(modifiedWork.length()>0)
try
modifiedWorkNum = Integer.parseInt(modifiedWork);
catch(Exception e)
JOptionPane.showMessageDialog(null,"You may only enter numbers for a valid phone number to try again press the modify nutton again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
if(modifiedWork.length() > 10)
JOptionPane.showMessageDialog(null,"You may not enter a number longer than 10 characters long. Please press the modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
String modifiedCell = JOptionPane.showInputDialog("Please enter a new home number for "+modifiedName+" or press cancel to keep it as is.");
if(modifiedCell == null)
modifiedCell = currentCell;
if(modifiedCell.length()>0)
try
modifiedCellNum = Integer.parseInt(modifiedCell);
catch(Exception e)
JOptionPane.showMessageDialog(null,"You may only enter numbers for a valid phone number to try again press the modify nutton again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
if(modifiedCell.length() > 10)
JOptionPane.showMessageDialog(null,"You may not enter a number longer than 10 characters long. Please press the modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
if((modifiedHome.length() <= 0) && (modifiedWork.length() <= 0) && (modifiedCell.length() <= 0))
JOptionPane.showMessageDialog(null,"The contact must have at least one number to be included in the phonebook. Please press modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
return;
for(Person z: phoneList)
z = phoneList.get(count1);
if((z.name).equals(modifiedName.trim().toUpperCase()) && (z.surname).equals(modifiedSurname.trim().toUpperCase()))
JOptionPane.showMessageDialog(null,"You may not enter duplicate contacts. Please try again.","Error",JOptionPane.ERROR_MESSAGE);
validModify = false;
modifyExisting();
return;
count1 ++;
if(validModify == true)
for(Person contactToMod: phoneList)/////////////////////////////////////////////////////// line 432
contactToMod = phoneList.get(count2);
if((contactToMod.name.equals(nameOfContactToEdit.trim().toUpperCase())) && (contactToMod.surname.equals(surnameOfContactToEdit.trim().toUpperCase())))
try
contactToMod.setName(modifiedName.trim().toUpperCase());
contactToMod.setSurname(modifiedSurname.trim().toUpperCase());
contactToMod.setHome(modifiedHome);
contactToMod.setWork(modifiedWork);
contactToMod.setCell(modifiedCell);
phoneList.add(contactToMod);
JOptionPane.showMessageDialog(null,"Updated contact succesfully.","Information",JOptionPane.INFORMATION_MESSAGE);
catch(Exception e)
JOptionPane.showMessageDialog(null,"The contact was not updated. If probelm persists please contact system administrator.","Error",JOptionPane.ERROR_MESSAGE);
count2 ++;
else
JOptionPane.showMessageDialog(null,"No contact with that name and surname exists. Please press the modify button to try again.","Error",JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(null,"The phone list is empty and there are no contacts to modify.","Information Message",JOptionPane.INFORMATION_MESSAGE);
}// End of modifyExisting()Edited by: Yucca on May 6, 2008 8:12 PM -
Concurrent Modification Exception
im running 2 "for" loops on a TreeMap's keySet. But everytime I remove a mapping from the inner loop using iterators I get the CMException. Is there a way to remove a mapping in the inner loop without getting the Exception?
Try Using two references to the same iterator. At the moment, it sounds like you are getting an iterator twice, once for each loop.
-
Modify map while iterating through it
hi all,
i have some java code iam maintaining and am seeing in many places that
HashMap object's iterator is used to iterate and in the loop, the same map is modified (adding an element). is this valid coding? i didnt get any issues so far.
Thanks.
eg code:
for ( Iterator iterator = myHashMap.keySet().iterator(); iterator.hasNext(); )
//bla bla bla
myHashMap.put(key,value);
iam wondering since the map got modified, how reliable is the iterator used in for loop?
-MadhuYou should not add during iteration. If you must, you should add
into a temporary array. When you're done with the iteration,
you can then add everything from the array into the map.
Or, if you quit the iteration right after adding something, that's okay. (That is, if after you add something, you no longer
touch the iterator, then that's okay)
Furthermore:
First of all, you should not use keySet() since it is very inefficient.
You're supposed to use entrySet() instead.
Second of all, if you use entrySet(), then you CAN delete+modify during iteration (just not "add")
for(Iterator i=map.entrySet(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)(i.next());
Object key = e.getKey();
Object value = e.getValue();
// You can now remove this entry like this:
i.remove();
// Or you can alter the value of this entry, like this:
e.setValue(someNewValue);
} -
Hello,
Just a question about a piece of code.
I have an EJB3 application with a simple Job object containing Configuration objects in an ArrayList.
The job is managed by a stateful session bean used to add and remove configurations. Cascading for the configurations inside the job is set to CascadeType.ALL.
Adding configurations works fine, but removing them is a standard way results in ConcurrentModificationExceptions.
I solved this exception by using thread synchronization inside the removeConfiguration method.
The workaround code is
public void removeConfiguration(String configName)
throws InvalidParameterException, EntityDoesNotExistException,
OperationNotAllowedException, StorageException {
if(job == null){
throw new OperationNotAllowedException("No job was created or selected.");
//Since removing elements from the list on configurations resulted
//in a concurrent modification exception at runtime, we had to create
//a deep clone of the array of configurations. After creating the deep
//clone, the element to remove will be removed from the deep copy.
//Both operations require non modification guarantee to the original
//configuration list.
//After updating the deep copy, the new list of configurations will
//be stored in the job. During this operation no modification guarantee
//is required for the deep copy.
List<Configuration> configurations = new ArrayList<Configuration>();
//Prevent modifications to the original list of configurations.
synchronized(job.getConfigurations()){
//Create the deep clone while locking the original configurations.
for(Configuration config : job.getConfigurations()){
configurations.add((Configuration)config.clone());
//Remove the object to be removed from the deep copy while locking
//the original configurations.
for(Configuration config : job.getConfigurations()){
if(config.getDescription().equals(configName)){
configurations.remove(config);
//Lock the deep copy and write it to the created/selected job.
//Prevent modifications to the deep copy.
synchronized(configurations){
job.setConfigurations(configurations);
}The code above works as expected and does not cause any exceptions.
The simplified code causing exceptions to be thrown:
public void removeConfiguration(String configName)
throws InvalidParameterException, EntityDoesNotExistException,
OperationNotAllowedException, StorageException {
if(job == null){
throw new OperationNotAllowedException("No job was created or selected.");
for(Configuration config : job.getConfigurations()){
if(config.getDescription().equals(configName)){
job.getConfigurations().remove(config);
}Allthough the first snippet works fine, it seems a bit strange to me. Isn't it recommended not to use synchronization inside business method and leave this up to the container?
Or is the solution just fine and not a problem at all. Code should be neat and not prone to errors or unexpected behaviour. This is my concern for the code above.
Better solutions are always welcome and will be Duke rewarded off course!
Thanks for your opinion. Regards,
KurtHi,
I replaced the synchronized code with the one below and everything works as expected.
Thanks to both of you for the fast response and for your help.
The new snippet looks a lot more solid to me.
public void removeConfiguration(String configName)
throws InvalidParameterException, OperationNotAllowedException {
ParameterValidation.stringNotNullNotEmpty(configName, "removeConfiguration", "config name", LOG);
if(job == null){
throw new OperationNotAllowedException("No job was created or selected.");
ListIterator<Configuration> lstConfiguration = job.getConfigurations().listIterator();
while(lstConfiguration.hasNext()){
Configuration config = lstConfiguration.next();
if(config.getDescription().equals(configName)){
lstConfiguration.remove();
}Regards,
Kurt -
Concurrent Modification of HashMap
I have a data structure like below
HashMap <String, HashMap<String, Object>>
Basically its a hashmap within a hash map. Its a global data structure.
I have a timerTask which at every interval iterates the inner hashMap and Modifies an attribute in the Object (Say Decrements an Integer attribute in the Object)
This will be continuing.
While the iteration is in progress inside the TimerTask, if i try to Modify the HashMap from outside via some other method call, I receive a concurrent Modification Exception.
My Question is, How to over come this Problem of managing both the things concurrently?wizsen wrote:
HashMap <String, HashMap<String, Object>>
Basically its a hashmap within a hash map.That's a bad idea. You almost certainly will want to encapsulate it in one way or another. You probably want a custom class to hold that structure.
Its a global data structure.What does that mean?
My Question is, How to over come this Problem of managing both the things concurrently?Avoid accessing the data structure from two places at the same time. Possibly using synchronization. -
Add to list while iterating?
What's the best way to add an element to a list during an iterating a list and have the item be in the current iteration?
For example...
List<Integer> li = new LinkedList<Integer>();
li.add(1);
li.add(3);
li.add(4);
ListIterator<Integer>iter = li.listIterator();
while(iter.hasNext()){
int num = iter.next();
if(num==1){
iter.add(2);
System.out.println(num);
}the above code would only print 1,3,4...
Any help would be appreciated, thank you.Making the simple change
if(num==1){
iter.add(2);
iter.previous();
}Seems to do the trick. Looking at the previous API we see:
Returns the previous element in the list. This method may be called repeatedly to iterate through the list backwards, or intermixed with calls to next to go back and forth. ( Note that alternating calls to next and previous will return the same element repeatedly. )
add() placed the element BEFORE the next() element. Calling previous() retrieves the added element. A subsequent call to next() gets that same element as per the API doc. -
Iterating through a generic list of unknown type
Hi,
I am in the process of creating pdf reports for my project.I have to deal with a persistence api to get the data for the report.The data will be in the form of a list,like List<SomeObject>,all these lists returned by the persistence framework contains object of some type which implements a common interface.But through that interface I wont be able to get all the data for my reports.So I am looking for a generic way for iterating through the list,by providing some metadata for the data within the list. I am planning to use reflection to query through the list.Is there any feature of generic,through which I can easily iterate through this unknown type,preferrably a combination of reflection and generics,I want to reduce the LOC.Any suggestions??If the List returned by the framework isn't parameterized, Like
public List<K> getList(Class<K> classType);
then you have to cast it to the appropriate type. If you are not sure about the type of the Objects in the list, and you have a bunch of class types you could expect from the list, then you could use instanceof operator.
If it could be Class A or B, then
if (obj instanceof A){
A castObject = (A) obj;
else if(obj instanceof B){
B castObject = (B)obj;
}Even to do reflection to invoke methods, you need to know the method Names. Which tells me you have the knowledge of what could come out of the list. So cast them. Invoking methods using reflection is really slow.
Maybe you are looking for
-
I've had my Macbook pro for about 3 1/2 years now. It has worked great until recently. A few months ago I noticed that the fan would always run really fast when I was doing simple tasks. After a few weeks/months, the fan was still really fast but it
-
.pdf I opened on my Mac Air, Lion OS will not print
Sometimes a .pdf will not print on any of my reliable printers. The entire sheet remains white with no print at all. I can't figure our why. Any ideas?
-
Hello! Pardon my beginner-ness. I've converted a MS Word doc to a fillable form - it went super-smoothly - loved it. When testing it by sending to another PC, I get a message that indicates, I paraphrase, "data entered into the form won't be saved
-
Revision: 14915 Revision: 14915 Author: [email protected] Date: 2010-03-22 11:58:59 -0700 (Mon, 22 Mar 2010) Log Message: Introduce BasicVideoElement, lightweight alternative to VideoElement. The former supports progressive and basic RTMP stre
-
Erro code:500 SRVE0199E: OutputStream already obtained
Hi all Iam writing a JSP code for exporting the result in to the csv .It working perfectly but afte exporting results it is showing exeception on same csv file.Can any one help me.The exeception is shown bellow. Error page exception The server cannot