blob: efcea7aa2175c4711f7a1d9b2f0c8e950b487bf2 [file] [log] [blame]
Pierre De Ropafe12952013-10-25 18:38:24 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19package org.apache.felix.dm.impl;
20
21import java.util.LinkedList;
22
23/**
24 * This class allows to serialize the execution of tasks on one single/unique thread.
25 * Other threads are blocked until they are elected for execution.
26 *
27 * <p>note I: when one leader thread executes a task, it does not hold any locks
28 * while executing the task, and does not execute tasks scheduled by other threads.
29 *
30 * <p>note II: this executor is reentrant: when one task executed by a leader thread
31 * reschedule another task, then the task is run immediately.
32 *
33 * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
34 */
35public class BlockingSerialExecutor {
36 private final LinkedList m_tasksQueue = new LinkedList();
37 private Thread m_executingThread = null;
38
39 /**
40 * Executes a task exclusively without holding any locks (other concurrent tasks are blocked until the current task is executed).
41 * @param task a task to be executed serially, without holding any locks.
42 */
43 public void execute(Runnable task) {
44 boolean releaseLock = false;
45 synchronized (this) {
46 if (m_executingThread != Thread.currentThread()) {
47 m_tasksQueue.addLast(task);
48 while (m_tasksQueue.size() > 0 && m_tasksQueue.get(0) != task) {
49 try {
50 // TODO it might make sense to use a maxwait time and throw an exception on timeouts.
51 wait();
52 } catch (InterruptedException e) {
53 }
54 }
55 m_executingThread = Thread.currentThread();
56 releaseLock = true;
57 }
58 }
59 try {
60 task.run();
61 } finally {
62 if (releaseLock) {
63 synchronized (this) {
64 m_tasksQueue.remove(task);
65 notifyAll();
66 m_executingThread = null;
67 }
68 }
69 }
70 }
71}