A List became empty without modifying it in java - java

Currently, I'm getting stuck with what it seems to be an unexpected error.
I'm programming with the java language, using eclipse as IDE.
The List in question is declared as follows :
private final List<Integer> resList;
Using the "Watchpoint" feature of eclipse while debugging the program, I've seen the following process :
After returning the resList List two times, and before returning it for the third time, the List became suddenly empty.
If anyone have a suggestion to give me in order to fix that problem, I would be very pleased ?
Concerning the code, I posted all the methods that access the resList list and are invoked in the program :
Here is the first One :
public CloudInformationService(String name) throws Exception {
super(name);
resList = new LinkedList<Integer>();
arList = new LinkedList<Integer>();
gisList = new LinkedList<Integer>();
}
And the second one :
public void processEvent(SimEvent ev) {
int id = -1; // requester id
switch (ev.getTag()) {
...
// A resource is requesting to register.
case CloudSimTags.REGISTER_RESOURCE:
resList.add((Integer) ev.getData());
break;
...
}
}
And finally, The third one :
private static CloudInformationService cis;
public static List<Integer> getCloudResourceList() {
if (cis == null) {
return null;
}
return cis.getList();// The implementation of this method is listed below
}
public List<Integer> getList() {
return resList;
}
Thank you in advance.

Step 1: use ctrl+alt+H to look up references to resList and look for methods calling remove, clear, removeAll. If there are too many methods using resList move on to Step 2.
Step 2: Set breakpoints in the CloudInformationServices constructor, when hit, set up breakpoints in LinkedList/AbstractList (in the JDK) in all remove, clear, removeAll methods. In the breakpoints view, right click on resList and choose instance breakpoints. Pick all your remove, clear, removeAll breakpoints and continue execution. Now you'll get a breakpoint hit and can observe from where the list is being emptied.
Without any more code there isn't much help you can get I'm afraid.

Related

Identify record that is culprit - coding practices

Is method chaining good?
I am not against functional programming that uses method chaining a lot, but against a herd mentality where people mindlessly run behind something that is new.
The example, if I am processing a list of items using stream programming and need to find out the exact row that resulted into throwing NullPointerException.
private void test() {
List<User> aList = new ArrayList<>();
// fill aList with some data
aList.stream().forEach(x -> doSomethingMeaningFul(x.getAddress()));
}
private void doSomethingMeaningFul(Address x) {
// Do something
}
So in the example above if any object in list is null, it will lead to NullPointerException while calling x.getAddress() and come out, without giving us a hook to identify a User record which has this problem.
I may be missing something that offers this feature in stream programming, any help is appreciated.
Edit 1:
NPE is just an example, but there are several other RuntimeExceptions that could occur. Writing filter would essentially mean checking for every RTE condition based on the operation I am performing. And checking for every operation will become a pain.
To give a better idea about what I mean following is the snippet using older methods; I couldn't find any equivalent with streams / functional programming methods.
List<User> aList = new ArrayList<>();
// Fill list with some data
int counter = 0;
User u = null;
try {
for (;counter < aList.size(); counter++) {
u = aList.get(counter);
u.doSomething();
int result = u.getX() / u.getY();
}
} catch(Exception e) {
System.out.println("Error processing at index:" + counter + " with User record:" + u);
System.out.println("Exception:" + e);
}
This will be a boon during the maintenance phase(longest phase) pointing exact data related issues which are difficult to reproduce.
**Benefits:**
- Find exact index causing issue, pointing to data
- Any RTE is recorded and analyzed against the user record
- Smaller stacktrace to look at
Is method chaining good?
As so often, the simple answer is: it depends.
When you
know what you are doing
are be very sure that elements will never be null, thus the chance for an NPE in such a construct is (close to) 0
and the chaining of calls leads to improved readability
then sure, chain calls.
If any of the above criteria isn't clearly fulfilled, then consider not doing that.
In any case, it might be helpful to distribute your method calls on new lines. Tools like IntelliJ actually give you advanced type information for each line, when you do that (well, not always, see my own question ;)
From a different perspective: to the compiler, it doesn't matter much if you chain call. That really only matters to humans. Either for readability, or during debugging.
There are a few aspects to this.
1) Nulls
It's best to avoid the problem of checking for nulls, by never assigning null. This applies whether you're doing functional programming or not. Unfortunately a lot of library code does expose the possibility of a null return value, but try to limit exposure to this by handling it in one place.
Regardless of whether you're doing FP or not, you'll find you get a lot less frustrated if you never have to write null checks when calling your own methods, because your own methods can never return null.
An alternative to variables that might be null, is to use Java 8's Optional class.
Instead of:
public String myMethod(int i) {
if(i>0) {
return "Hello";
} else {
return null;
}
}
Do:
public Optional<String> myMethod(int i) {
if(i>0) {
return Optional.of("Hello");
} else {
return Optional.empty();
}
Look at Optional Javadoc to see how this forces the caller to think about the possibility of an Optional.empty() response.
As a bridge between the worlds of "null represents absent" and "Optional.empty() represents absent", you can use Optional.ofNullable(val) which returns Empty when val == null. But do bear in mind that Optional.empty() and Optional.of(null) are different values.
2) Exceptions
It's true that throwing an exception in a stream handler doesn't work very well. Exceptions aren't a very FP-friendly mechanism. The FP-friendly alternative is Either -- which isn't a standard part of Java but is easy to write yourself or find in third party libraries: Is there an equivalent of Scala's Either in Java 8?
public Either<Exception, Result> meaningfulMethod(Value val) {
try {
return Either.right(methodThatMightThrow(val));
} catch (Exception e) {
return Either.left(e);
}
}
... then:
List<Either<Exception, Result>> results = listOfValues.stream().map(meaningfulMethod).collect(Collectors.toList());
3) Indexes
You want to know the index of the stream element, when you're using a stream made from a List? See Is there a concise way to iterate over a stream with indices in Java 8?
In your test() function you are creating an emptylist List<User> aList = new ArrayList<>();
And doing for each on it. First add some element to
aList
If you want to handle null values you can add .filter(x-> x != null) this before foreach it will filter out all null value
Below is code
private void test() {
List<User> aList = new ArrayList<>();
aList.stream().filter(x-> x != null).forEach(x -> doSomethingMeaningFul(x.getAddress()));
}
private void doSomethingMeaningFul(Address x) {
// Do something
}
You can write a black of code in streams. And you can find out the list item which might result in NullPointerException. I hope this code might help
private void test() {
List<User> aList = new ArrayList<>();
aList.stream().forEach(x -> {
if(x.getAddress() != null)
return doSomethingMeaningFul(x.getAddress())
else
system.out.println(x+ "doesn't have address");
});
}
private void doSomethingMeaningFul(Address x) {
// Do something
}
If you want you can throw NullPointerException or custom excption like AddressNotFoundException in the else part

Non intrusive way to exit a method under a given condition?

Given this method:
public void walk( String path , ArrayList<String> files, String ext)
which collects all files into the ArrayList<> files starting at path and with given extension ext, I'm looking for a way to stop the search when a certain condition is met. For example, it should stop when files.size() becomes greater than a given number. How could I do this without modifying the method walk() ?
By not modifying the method, I mean not touching the source code in the editor. It's in a state that I like, and I don't want to touch it, because it's just for testing purpose.
Create your class extending ArrayList and override add method:
public class MyList extends ArrayList<String> {
#Override
public boolean add(String item) {
boolean added = super.add(item);
if (added && size() >= 10) {
throw MaxItemsReachedException();
}
}
}
When size is greater or equals to 10, for instance, you can throw an exception.
And call your method with an instance of MyList instead of ArrayList:
MyList list = new MyList();
walk("path", list, "extension");
DISCLAIMER: This is bad programming practice. Dont't do this. I only offer it because it solves the OP's problem.
Subclass ArrayList. Add some logic to the add methods that throw an exception if files.size is greater than some threshold.
It will look like this
public void add(E element){
if(size()<THRESHOLD){
super.add(element);
}else{
throw new RuntimeException("STOP HERE");
}
}
Try to throw an exception that walk does not catch and you should catch this exception in the method that calls walk.
Among other bad things this is using exceptions to manage flow control.

Java: Return in a for loop

Is there a way to return some value from within a for loop without jumping out of the loop?
I am implementing a static analysis tool where I have to analyze a list of methods (CFGs) in a for loop. The size of CFG list is not known in advance. Each method in the for loop has to return some value. As asked above, is there a way to do it in a loop without breaking the loop? One possible alternative comes in mind is that I can unroll the loop, assuming the maximum list size could be some fixed value. But this does not solve the problem completely. Any help would be appreciated.
code looks like below.
for(CFG cfg: cfgList)
{
val = analyze(cfg);
return val; //I want for loop not to stop here.
}
P.S. I cannot store the values in a list to return values later.
Edit1:
For example, consider following statements.
call method1();
st2;
st3;
...
This method1() can be any of five different methods. For all five possible options, I want to analyze each of them, return their values and analyze rest of the statements accordingly. So, I would analyze these 5 methods as below.
call method1-option1();
st2;
st3;
...
call method1-option2();
st2;
st3;
...
call method1-option3();
st2;
st3;
...
Hope, it helps in understanding the question.
No you can not return value from loop without jumping out of it. According to your need you have to save value in other list and you can return that list after finishing the loop.
In Java 8, you can do:
Iterator<AnalysisResult> lazyAnalysisResults = cfgList.stream()
.map(cfg -> analyze(cfg))
.iterator();
And then the Iterator will supply new analyzed results one at a time, without you needing to collect them all into a list first.
Prior to Java 8, if you want your transformation to be lazy, the best you can do is to implement an Iterator yourself:
public final class AnalyzingIterator extends Iterator<AnalysisResult> {
private final Iterator<CFG> iter;
public AnalyzingIterator(Iterator<CFG> iter) {
this.iter = iter;
}
#Override public boolean hasNext() {
return iter.hasNext();
}
#Override public AnalysisResult next() {
return analyze(iter.next());
}
#Override public boolean remove() {
throw new UnsupportedOperationException();
}
}
If you don't want to store results in a List and return it all together you can use callback mechanism.
Use analyze() to start a new thread passing cfg as well as reference to this. When processing is over make that processing thread call a callback method on your current instance / thread passing the analyzed value. Continue to do whatever you intend to do with this returned value in the callback method. And you don't have to alter your for loop.

Should enhanced for loops include a function returning a list

I was just concerned about enhanced for loops calling a method directly.
Nested inside the code is my question in capital letters:
public class ExtendedForLoop {
public static List<Integer> returnList() {
System.out.println("Hurray ----> ");
List<Integer> abc = new ArrayList<Integer>();
abc.add(5);
abc.add(10);
abc.add(20);
return abc;
}
public static void main(String args[]) {
for (Integer i : returnList()) { // <----- OPTION 1. Include function call in extended loop.
System.out.println(i);
}
List<Integer> list = returnList()
for (Integer i : list) { // <----- OPTION 2. Provide list to function call.
System.out.println(i);
}
}
}
I prefer option 2, as some exception can be dealt with.
However if no exceptions are expected then option 1 can reduce unnecessary declaration of a new variable, hence reducing clutter.
But,
In general.
Which option is preferred ?
If it is option2 and the only reason for chosing option2 is handling exceptions, then should we use option1 if no exceptions are expected ?
I prefer using option 1 if I'm the owner of the code that returns the list and can guarantee that null will never be returned.
If I'm not the owner, I prefer to use a different construct though
for(Integer i : guaranteeCollection(resultList())
{
// dostuff
}
public static &ltT> Collection&ltT> guaranteeCollection(Collection&ltT> c)
{
return c != null ? c : Collections.EMPTY_LIST;
}
This avoids creating unnecessary variable declarations in your code and prevent NPEs.
I think second approach with null check is safer.
enhanced for loop will through NullPointerException if method returns null.
It depends on your system design:
Many project targets avoiding null objects.
If you are sure that returnList() will never return null (It should return an empty list instead (or Collections.emptyList), then go for solution 1, other wise for 2.
Well if you are dealing with NullpointerException in case then i prefer going with Option 1 as we are making an extra variable "list" on the stack which will occupy some memory also will reduce the performance by some bit.

Java Programming Error: java.util.ConcurrentModificationException

I'm writing a program as part of tutorial for a beginner Java student. I have the following method and whenever I run it, it gives me the following exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Warehouse.receive(Warehouse.java:48)
at MainClass.main(MainClass.java:13)
Here's the method itself, within the class Warehouse:
public void receive(MusicMedia product, int quantity) {
if ( myCatalog.size() != 0) { // Checks if the catalog is empty
// if the catalog is NOT empty, it will run through looking to find
// similar products and add the new product if there are none
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
} else { // if the catalog is empty, just add the product
myCatalog.add(product);
}
}
The problem seems to be with the if else statement. If I don't include the if else, then the program will run, although it won't work properly because the loop won't iterate through an empty ArrayList.
I've tried adding a product just to keep it from being empty in other parts of the code, but it still gives me the same error. Any ideas?
You can't be iterating through the same list you're going to add things to. Keep a separate list of the things you're going to add, then add them all at the end.
You must not modify mCatalog while you're iterating over it. You're adding an element to it in this loop:
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
See ConcurrentModificationException and modCount in AbstractList.

Categories