Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1a43d2817946f8315d3cc4814926260881b8237f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Andre Dietisheim - initial API and implementation
 *    Eike Stepper - maintenance
 */
package org.eclipse.net4j.util.tests;

import org.eclipse.net4j.util.concurrent.QueueWorkerWorkSerializer;
import org.eclipse.net4j.util.io.IOUtil;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A test for {@link QueueWorkerWorkSerializer}.
 * 
 * @author Andre Dietisheim
 */
public class QueueWorkerWorkSerializerTest extends AbstractOMTest
{
  /** timeout to wait for execution of all work units. */
  private static final int WORK_COMPLETION_TIMEOUT = 10000;

  /** number of work producer threads. */
  private static final int NUM_WORKPRODUCER_THREADS = 10;

  /** number of working units to execute. */
  private static final int NUM_WORK = 40;

  /** the latch to wait on for the execution of all working units. */
  private CountDownLatch workConsumedLatch;

  /** The number of working units created. */
  private AtomicInteger workProduced;

  /** The thread pool to execute the work unit producers in. */
  private ExecutorService threadPool;

  /** The queue worker to submit the work units to. */
  private QueueWorkerWorkSerializer queueWorker;

  public QueueWorkerWorkSerializerTest()
  {
  }

  /**
   * Test that asserts that all submitted workers are executed
   */
  public void testAllWorkSubmittedIsConsumed() throws Throwable
  {
    createWorkProducerThreads(new WorkProducerFactory()
    {
      public WorkProducer createWorkProducer()
      {
        return new WorkProducer()
        {
          @Override
          protected Runnable createWork(int id)
          {
            return new Work(id);
          }
        };
      }
    });

    waitForAllWorkExecuted();
    assertEquals(workProduced.get(), NUM_WORK - workConsumedLatch.getCount());
  }

  /**
   * If the workers throw Exceptions, the QueueWorker stops executing work (deactivates its working thread). Therefore
   * the first work unit gets consumed, the rest is not executed any more.
   */
  public void testGivenWorkExceptionInWorkAllWorkSubmittedOnlyTheFirstWorkerIsConsumed() throws Throwable
  {
    createWorkProducerThreads(new WorkProducerFactory()
    {
      public WorkProducer createWorkProducer()
      {
        return new WorkProducer()
        {
          @Override
          protected Runnable createWork(int id)
          {
            return new Work(id)
            {
              @Override
              public void run()
              {
                super.run();
                throw new RuntimeException("dummy exception to simulate an error in executed workers");
              }
            };
          }
        };
      }
    });

    waitForAllWorkExecuted();
    assertEquals(NUM_WORK, workProduced.get());
    assertEquals(1, NUM_WORK - workConsumedLatch.getCount());
  }

  private void waitForAllWorkExecuted() throws InterruptedException
  {
    if (!workConsumedLatch.await(WORK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS))
    {
      IOUtil.OUT().println("timeout occured before all workers were executed");
    }
  }

  private void createWorkProducerThreads(WorkProducerFactory factory)
  {
    for (int i = 0; i < NUM_WORKPRODUCER_THREADS; i++)
    {
      threadPool.submit(factory.createWorkProducer());
    }
  }

  /**
   * A factory that creates work units.
   */
  private static interface WorkProducerFactory
  {
    public WorkProducer createWorkProducer();
  }

  /**
   * A Runnable that creates work units
   */
  private abstract class WorkProducer implements Runnable
  {
    private Random random = new Random();

    /**
     * Produce work: add work units to the queue worker
     */
    public void run()
    {
      try
      {
        int currentWorkProduced;
        while ((currentWorkProduced = workProduced.getAndIncrement()) < NUM_WORK)
        {
          queueWorker.addWork(createWork(currentWorkProduced));
          Thread.sleep(random.nextInt(1000));
        }

        // correct last increment
        workProduced.decrementAndGet();
        IOUtil.OUT().println("work producer " + this + " stopped its production");
      }
      catch (InterruptedException ex)
      {
        return;
      }
    }

    /**
     * Creates a working unit (runnable).
     * 
     * @param id
     *          the id
     * @return the runnable
     */
    protected abstract Runnable createWork(int id);
  }

  /**
   * A simple work unit to be executed in the queueWorker.
   * 
   * @author Andre Dietisheim
   */
  class Work implements Runnable
  {
    private final int id;

    private Work(int id)
    {
      this.id = id;
      IOUtil.OUT().println("work unit " + id + " created");
    }

    public void run()
    {
      workConsumedLatch.countDown();
      IOUtil.OUT().println("work unit " + id + " consumed");
    }
  }

  @Override
  public void setUp()
  {
    threadPool = Executors.newFixedThreadPool(NUM_WORKPRODUCER_THREADS);
    workConsumedLatch = new CountDownLatch(NUM_WORK);
    queueWorker = new QueueWorkerWorkSerializer();
    workProduced = new AtomicInteger(0);
  }

  @Override
  public void tearDown()
  {
    threadPool.shutdown();
    queueWorker.dispose();
  }
}

Back to the top