001package ca.uhn.fhir.util; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2022 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 024import org.slf4j.Logger; 025import org.slf4j.LoggerFactory; 026 027import java.util.concurrent.CountDownLatch; 028import java.util.concurrent.TimeUnit; 029 030public class AsyncUtil { 031 private static final Logger ourLog = LoggerFactory.getLogger(AsyncUtil.class); 032 033 /** 034 * Non instantiable 035 */ 036 private AsyncUtil() { 037 } 038 039 /** 040 * Calls Thread.sleep and if an InterruptedException occurs, logs a warning but otherwise continues 041 * 042 * @param theMillis The number of millis to sleep 043 * @return Did we sleep the whole amount 044 */ 045 public static boolean sleep(long theMillis) { 046 try { 047 Thread.sleep(theMillis); 048 return true; 049 } catch (InterruptedException theE) { 050 Thread.currentThread().interrupt(); 051 ourLog.warn("Sleep for {}ms was interrupted", theMillis); 052 return false; 053 } 054 } 055 056 public static boolean awaitLatchAndThrowInternalErrorExceptionOnInterrupt(CountDownLatch theInitialCollectionLatch, long theTime, TimeUnit theTimeUnit) { 057 try { 058 return theInitialCollectionLatch.await(theTime, theTimeUnit); 059 } catch (InterruptedException e) { 060 Thread.currentThread().interrupt(); 061 throw new InternalErrorException(e); 062 } 063 } 064 065 public static boolean awaitLatchAndIgnoreInterrupt(CountDownLatch theInitialCollectionLatch, long theTime, TimeUnit theTimeUnit) { 066 try { 067 return theInitialCollectionLatch.await(theTime, theTimeUnit); 068 } catch (InterruptedException e) { 069 Thread.currentThread().interrupt(); 070 ourLog.warn("Interrupted while waiting for latch"); 071 return false; 072 } 073 } 074}