NETVIRT-1637 CSIT failure
[netvirt.git] / sfc / classifier / impl / src / main / java / org / opendaylight / netvirt / sfc / classifier / utils / LastTaskExecutor.java
1 /*
2  * Copyright (c) 2017 Ericsson Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netvirt.sfc.classifier.utils;
10
11 import java.util.concurrent.Executor;
12 import java.util.concurrent.atomic.AtomicReference;
13
14 /**
15  * An executor that only executes the last submitted task. Ongoing tasks wont
16  * be cancelled.
17  */
18 public class LastTaskExecutor implements Executor {
19
20     private final Executor executor;
21     private final AtomicReference<Runnable> lastTask = new AtomicReference<>();
22
23     public LastTaskExecutor(Executor executor) {
24         this.executor = executor;
25     }
26
27     @Override
28     public void execute(final Runnable newTask) {
29         if (newTask == null) {
30             throw new NullPointerException();
31         }
32
33         lastTask.set(newTask);
34         executor.execute(() -> {
35             final Runnable runTask = lastTask.getAndSet(null);
36             if (runTask != null) {
37                 runTask.run();
38             }
39         });
40     }
41 }