001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.procedure2;
019
020import static org.junit.jupiter.api.Assertions.assertSame;
021import static org.junit.jupiter.api.Assertions.assertThrows;
022import static org.mockito.ArgumentMatchers.any;
023import static org.mockito.Mockito.mock;
024import static org.mockito.Mockito.times;
025import static org.mockito.Mockito.verify;
026import static org.mockito.Mockito.when;
027
028import java.io.IOException;
029import java.util.concurrent.CompletableFuture;
030import java.util.concurrent.ExecutorService;
031import org.apache.commons.lang3.mutable.MutableObject;
032import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
033import org.apache.hadoop.hbase.testclassification.MasterTests;
034import org.apache.hadoop.hbase.testclassification.SmallTests;
035import org.junit.jupiter.api.Tag;
036import org.junit.jupiter.api.Test;
037
038@Tag(SmallTests.TAG)
039@Tag(MasterTests.TAG)
040public class TestProcedureFutureUtil {
041
042  @Test
043  public void testCompleteInSameThread() throws IOException {
044    Procedure<?> proc = mock(Procedure.class);
045    MutableObject<CompletableFuture<Void>> setFuture = new MutableObject<>();
046
047    CompletableFuture<Void> future = new CompletableFuture<>();
048
049    MasterProcedureEnv env = mock(MasterProcedureEnv.class);
050    ExecutorService exec = mock(ExecutorService.class);
051    when(env.getAsyncTaskExecutor()).thenReturn(exec);
052
053    Runnable actionAfterDone = mock(Runnable.class);
054
055    assertThrows(ProcedureSuspendedException.class, () -> ProcedureFutureUtil
056      .suspendIfNecessary(proc, setFuture::setValue, future, env, actionAfterDone));
057
058    assertSame(future, setFuture.get());
059    verify(proc, times(1)).skipPersistence();
060
061    // complete in the same thread, and make sure the callback has been scheduled correctly
062    future.complete(null);
063    verify(env, times(1)).getAsyncTaskExecutor();
064    verify(exec, times(1)).execute(any());
065  }
066}