A context which inherits cancellation from its parent but which can also be independently cancelled and which will propagate cancellation to its descendants. To avoid leaking memory, every CancellableContext must have a defined lifetime, after which it is guaranteed to be cancelled. This class m
| 655 | * and cancel the context at the appropriate time. |
| 656 | */ |
| 657 | public static final class CancellableContext extends Context implements Closeable { |
| 658 | |
| 659 | private final Deadline deadline; |
| 660 | private final Context uncancellableSurrogate; |
| 661 | |
| 662 | private ArrayList<ExecutableListener> listeners; |
| 663 | // parentListener is initialized when listeners is initialized (only if there is a |
| 664 | // cancellable ancestor), and uninitialized when listeners is uninitialized. |
| 665 | private CancellationListener parentListener; |
| 666 | private Throwable cancellationCause; |
| 667 | private ScheduledFuture<?> pendingDeadline; |
| 668 | private boolean cancelled; |
| 669 | |
| 670 | /** |
| 671 | * Create a cancellable context that does not have a deadline. |
| 672 | */ |
| 673 | private CancellableContext(Context parent) { |
| 674 | super(parent, parent.keyValueEntries); |
| 675 | deadline = parent.getDeadline(); |
| 676 | // Create a surrogate that inherits from this to attach so that you cannot retrieve a |
| 677 | // cancellable context from Context.current() |
| 678 | uncancellableSurrogate = new Context(this, keyValueEntries); |
| 679 | } |
| 680 | |
| 681 | /** |
| 682 | * Create a cancellable context that has a deadline. |
| 683 | */ |
| 684 | private CancellableContext(Context parent, Deadline deadline) { |
| 685 | super(parent, parent.keyValueEntries); |
| 686 | this.deadline = deadline; |
| 687 | this.uncancellableSurrogate = new Context(this, keyValueEntries); |
| 688 | } |
| 689 | |
| 690 | private void setUpDeadlineCancellation(Deadline deadline, ScheduledExecutorService scheduler) { |
| 691 | if (!deadline.isExpired()) { |
| 692 | final class CancelOnExpiration implements Runnable { |
| 693 | @Override |
| 694 | public void run() { |
| 695 | try { |
| 696 | cancel(new TimeoutException("context timed out")); |
| 697 | } catch (Throwable t) { |
| 698 | log.log(Level.SEVERE, "Cancel threw an exception, which should not happen", t); |
| 699 | } |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | synchronized (this) { |
| 704 | pendingDeadline = deadline.runOnExpiration(new CancelOnExpiration(), scheduler); |
| 705 | } |
| 706 | } else { |
| 707 | // Cancel immediately if the deadline is already expired. |
| 708 | cancel(new TimeoutException("context timed out")); |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | @Override |
| 713 | public Context attach() { |
| 714 | return uncancellableSurrogate.attach(); |
nothing calls this directly
no outgoing calls
no test coverage detected