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.i18n.Msg; 024import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 025import org.slf4j.Logger; 026import org.slf4j.LoggerFactory; 027 028import java.util.concurrent.CountDownLatch; 029import java.util.concurrent.TimeUnit; 030 031public class AsyncUtil { 032 private static final Logger ourLog = LoggerFactory.getLogger(AsyncUtil.class); 033 034 /** 035 * Non instantiable 036 */ 037 private AsyncUtil() { 038 } 039 040 /** 041 * Calls Thread.sleep and if an InterruptedException occurs, logs a warning but otherwise continues 042 * 043 * @param theMillis The number of millis to sleep 044 * @return Did we sleep the whole amount 045 */ 046 public static boolean sleep(long theMillis) { 047 try { 048 Thread.sleep(theMillis); 049 return true; 050 } catch (InterruptedException theE) { 051 Thread.currentThread().interrupt(); 052 ourLog.warn("Sleep for {}ms was interrupted", theMillis); 053 return false; 054 } 055 } 056 057 public static boolean awaitLatchAndThrowInternalErrorExceptionOnInterrupt(CountDownLatch theInitialCollectionLatch, long theTime, TimeUnit theTimeUnit) { 058 try { 059 return theInitialCollectionLatch.await(theTime, theTimeUnit); 060 } catch (InterruptedException e) { 061 Thread.currentThread().interrupt(); 062 throw new InternalErrorException(Msg.code(1805) + e); 063 } 064 } 065 066 public static boolean awaitLatchAndIgnoreInterrupt(CountDownLatch theInitialCollectionLatch, long theTime, TimeUnit theTimeUnit) { 067 try { 068 return theInitialCollectionLatch.await(theTime, theTimeUnit); 069 } catch (InterruptedException e) { 070 Thread.currentThread().interrupt(); 071 ourLog.warn("Interrupted while waiting for latch"); 072 return false; 073 } 074 } 075}