Commit | Line | Data |
---|---|---|
951d134a FC |
1 | /******************************************************************************* |
2 | * Copyright (c) 2009, 2010 Ericsson | |
3 | * | |
4 | * All rights reserved. This program and the accompanying materials are | |
5 | * made available under the terms of the Eclipse Public License v1.0 which | |
6 | * accompanies this distribution, and is available at | |
7 | * http://www.eclipse.org/legal/epl-v10.html | |
8 | * | |
9 | * Contributors: | |
10 | * Francois Chouinard - Initial API and implementation | |
11 | *******************************************************************************/ | |
12 | ||
8c8bf09f ASL |
13 | package org.eclipse.linuxtools.tmf.request; |
14 | ||
15 | import java.util.Queue; | |
16 | import java.util.concurrent.Executor; | |
54d55ced | 17 | import java.util.concurrent.ExecutorService; |
8c8bf09f ASL |
18 | import java.util.concurrent.Executors; |
19 | import java.util.concurrent.LinkedBlockingQueue; | |
20 | ||
951d134a FC |
21 | /** |
22 | * <b><u>TmfRequestExecutor</u></b> | |
23 | * | |
24 | * Implement me. Please. | |
25 | */ | |
8c8bf09f ASL |
26 | public class TmfRequestExecutor implements Executor { |
27 | ||
54d55ced | 28 | private final ExecutorService fExecutor; |
fc6ccf6f FC |
29 | private final Queue<Runnable> fRequests = new LinkedBlockingQueue<Runnable>(); |
30 | private Runnable fRequest; | |
8c8bf09f | 31 | |
54d55ced | 32 | public TmfRequestExecutor(ExecutorService executor) { |
8c8bf09f | 33 | fExecutor = executor; |
8c8bf09f ASL |
34 | } |
35 | ||
fc6ccf6f FC |
36 | public TmfRequestExecutor() { |
37 | this(Executors.newSingleThreadExecutor()); | |
8c8bf09f | 38 | } |
fc6ccf6f | 39 | |
54d55ced FC |
40 | public void start() { |
41 | // Nothing to do | |
42 | } | |
43 | ||
44 | public void stop() { | |
45 | fExecutor.shutdown(); | |
46 | } | |
47 | ||
fc6ccf6f FC |
48 | public void execute(final Runnable request) { |
49 | fRequests.offer(new Runnable() { | |
8c8bf09f ASL |
50 | public void run() { |
51 | try { | |
8c8bf09f | 52 | request.run(); |
8c8bf09f ASL |
53 | } finally { |
54 | scheduleNext(); | |
55 | } | |
56 | } | |
57 | }); | |
fc6ccf6f | 58 | if (fRequest == null) { |
8c8bf09f ASL |
59 | scheduleNext(); |
60 | } | |
61 | } | |
62 | ||
8c8bf09f | 63 | protected synchronized void scheduleNext() { |
fc6ccf6f FC |
64 | if ((fRequest = fRequests.poll()) != null) { |
65 | fExecutor.execute(fRequest); | |
8c8bf09f ASL |
66 | } |
67 | } | |
68 | ||
fc6ccf6f FC |
69 | public synchronized void queueRequest(Runnable request) { |
70 | fRequests.add(request); | |
71 | scheduleNext(); | |
8c8bf09f ASL |
72 | } |
73 | ||
74 | } |