001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.concurrent;
018
019import static org.junit.Assert.assertEquals;
020
021import java.util.concurrent.atomic.AtomicInteger;
022
023import org.junit.Before;
024import org.junit.Test;
025
026/**
027 * Test class for {@code AtomicSafeInitializer}.
028 *
029 * @version $Id: AtomicSafeInitializerTest.java 1088899 2011-04-05 05:31:27Z bayard $
030 */
031public class AtomicSafeInitializerTest extends
032        AbstractConcurrentInitializerTest {
033    /** The instance to be tested. */
034    private AtomicSafeInitializerTestImpl initializer;
035
036    @Before
037    public void setUp() throws Exception {
038        initializer = new AtomicSafeInitializerTestImpl();
039    }
040
041    /**
042     * Returns the initializer to be tested.
043     *
044     * @return the {@code AtomicSafeInitializer} under test
045     */
046    @Override
047    protected ConcurrentInitializer<Object> createInitializer() {
048        return initializer;
049    }
050
051    /**
052     * Tests that initialize() is called only once.
053     */
054    @Test
055    public void testNumberOfInitializeInvocations() throws ConcurrentException,
056            InterruptedException {
057        testGetConcurrent();
058        assertEquals("Wrong number of invocations", 1,
059                initializer.initCounter.get());
060    }
061
062    /**
063     * A concrete test implementation of {@code AtomicSafeInitializer}. This
064     * implementation also counts the number of invocations of the initialize()
065     * method.
066     */
067    private static class AtomicSafeInitializerTestImpl extends
068            AtomicSafeInitializer<Object> {
069        /** A counter for initialize() invocations. */
070        final AtomicInteger initCounter = new AtomicInteger();
071
072        @Override
073        protected Object initialize() throws ConcurrentException {
074            initCounter.incrementAndGet();
075            return new Object();
076        }
077    }
078}