Reputation: 559
I have a school assignment where Iam going to use threads in Java to sort a long name list. There is no focus on the speed of the sorting algorithm, but a assignment for understanding threads and how threads affect the speed of the sort.
I feel I'm on the right path, but the code/threads messes up the monitor, I have tried for a while to locate the problem, for me the problem seems to be in class SortThreads
run()
method. Can folks please give me some tips or hints?
public void run() {
while (monitor.getSize() > 1) {
System.out.println("Number of array in list to be sorted: "
+ monitor.getSize());
String[] f = monitor.getRandom();
String[] g = monitor.getRandom();
monitor.add(descSort(f, g));
}
System.out.println("*** THREAD DEAD ***");
}
Output:
After delete: 1
Number of array in list to be sorted: 3
Befor delete: 1
After delete: 0
Number of array in list to be sorted: 0
Exception in thread "Thread-101" java.lang.NullPointerException
at SortThread.append(Sort.java:222)
at SortThread.descSort(Sort.java:201)
at SortThread.run(Sort.java:178)
Exception in thread "Thread-96" java.lang.NullPointerException
at SortThread.append(Sort.java:222)
at SortThread.descSort(Sort.java:201)
at SortThread.run(Sort.java:178)
Number of array in list to be sorted: 0
Number of array in list to be sorted: 0
Upvotes: 1
Views: 2682
Reputation: 328618
One of your (possible) problems is that this section is not atomic:
while (monitor.getSize() > 1) {
System.out.println("Number of array in list to be sorted: "
+ monitor.getSize());
String[] f = monitor.getRandom();
String[] g = monitor.getRandom();
monitor.add(descSort(f, g));
}
Typically, if you use any threads, it is very likely that between the call to monitor.getSize()
and monitor.getRandom()
the size has actually changed. So I guess that one of the getRandom
calls (or both) returns null which triggers the NullPointerException
.
You could add a check for null
before calling descSort()
. If only one of f
and g
is null
, you probably need to put it back into the monitor (just guessing here).
Upvotes: 1