-3

I have a sorted linked list - priority queue implementation and I get a null pointer exception when I attempt to do the following: get a Job from a method, delete the node in the linked listed associated with that job, change the priority of the job I received from the method and add the job back into the linked list at its new location.

this is my loop that runs a job from the sorted linked list:

while(!sl.isEmpty()) {
        Job currentJob = sl.remove().job;
        System.out.println(currentJob.toString());
        
        if(currentJob.getCurrentJobLength() > 0) {
            currentJob.decrementJobLength();
            currentJob.incrementEndTime();
            sl.insert(currentJob);
            
            if(cycles == 30) {
                System.out.println();
                Job temp = starvedJob(sl);
                sl.delete(temp);
                temp.setFinalPriority(1);
                sl.insert(temp);
                cycles = 0;
            }
            
        }
        cycles++;
    }

the null pointer occurs on line: temp.setFinalPriority(1);

This is my delete method for the sorted linked list:

public boolean delete(Job j) {
    
    Node nodeBeforeDelete = this.head;
    if(nodeBeforeDelete == null)
        return false;
    else if(nodeBeforeDelete.job == j) {
        this.head = this.head.next;
        return true;
    }
    while(true) {
        Node after = nodeBeforeDelete.next;
        if(after == null)
            return false;
        else if(after.job == j)
            break;
        nodeBeforeDelete = after;
    }
    Node after = nodeBeforeDelete.next;
    nodeBeforeDelete.next = after.next;
    after.next = null;
    return true;
}

and if it helps, my insert:

public void insert(Job job) {
    Node newNode = new Node(job);
    Node current = head;
    Node previous = null;
    while(current != null && (job.getFinalPriority() > current.job.getFinalPriority())){
        previous = current;
        current = current.next;
    }
    
    if(previous == null) {
        head = newNode;
    }else {
        previous.next = newNode;
    }
    newNode.next = current;
}

Thank you in advance for any feedback!

1 Answers1

0

It's hard to know without seeing how you implemented "starvedJob" method, but maybe you're not creating any new object for "temp" and you're deleting the object you're referencing when returning your Job object from starved Jobs. Remember that when you assign something to a variable without creating a new object java assigns its reference but doesn't create a new object. Maybe it helps!

Guillem
  • 58
  • 5