Noninterruptible Code

Some sequences of operations cannot tolerate an asynchronous exception. Consider this code for adding a node at the front of a singly linked list:

temp = List.head;
List.head = this;
this.next = temp

If the code were interrupted by an AIE between the second and third lines, it would leave the list containing only the new entry. Any contents before the update would be unreachable.

There are three ways to fix this problem.

this.next = List.head
List.head = this

is probably the best fix. The algorithm is simpler and the intermediate state is safe, but

private void listPush(){
  Object temp = List.head;
  List.head = this;
  this.next = temp;
}

works too. The first fix works by making the problem go away. The second works by ...

Get Real-Time Java™ Platform Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.