1
package org.apache.lucene.util;
4
* Licensed to the Apache Software Foundation (ASF) under one or more
5
* contributor license agreements. See the NOTICE file distributed with
6
* this work for additional information regarding copyright ownership.
7
* The ASF licenses this file to You under the Apache License, Version 2.0
8
* (the "License"); you may not use this file except in compliance with
9
* the License. You may obtain a copy of the License at
11
* http://www.apache.org/licenses/LICENSE-2.0
13
* Unless required by applicable law or agreed to in writing, software
14
* distributed under the License is distributed on an "AS IS" BASIS,
15
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
* See the License for the specific language governing permissions and
17
* limitations under the License.
20
import java.util.Random;
22
import org.apache.lucene.util.SetOnce.AlreadySetException;
23
import org.junit.Test;
25
public class TestSetOnce extends LuceneTestCase {
27
private static final class SetOnceThread extends Thread {
29
boolean success = false;
32
public SetOnceThread(Random random) {
33
RAND = new Random(random.nextLong());
39
sleep(RAND.nextInt(10)); // sleep for a short time
40
set.set(new Integer(Integer.parseInt(getName().substring(2))));
42
} catch (InterruptedException e) {
44
} catch (RuntimeException e) {
45
// TODO: change exception type
53
public void testEmptyCtor() throws Exception {
54
SetOnce<Integer> set = new SetOnce<Integer>();
55
assertNull(set.get());
58
@Test(expected=AlreadySetException.class)
59
public void testSettingCtor() throws Exception {
60
SetOnce<Integer> set = new SetOnce<Integer>(new Integer(5));
61
assertEquals(5, set.get().intValue());
62
set.set(new Integer(7));
65
@Test(expected=AlreadySetException.class)
66
public void testSetOnce() throws Exception {
67
SetOnce<Integer> set = new SetOnce<Integer>();
68
set.set(new Integer(5));
69
assertEquals(5, set.get().intValue());
70
set.set(new Integer(7));
74
public void testSetMultiThreaded() throws Exception {
75
final SetOnce<Integer> set = new SetOnce<Integer>();
76
SetOnceThread[] threads = new SetOnceThread[10];
77
for (int i = 0; i < threads.length; i++) {
78
threads[i] = new SetOnceThread(random);
79
threads[i].setName("t-" + (i+1));
83
for (Thread t : threads) {
87
for (Thread t : threads) {
91
for (SetOnceThread t : threads) {
93
int expectedVal = Integer.parseInt(t.getName().substring(2));
94
assertEquals("thread " + t.getName(), expectedVal, t.set.get().intValue());