code
stringlengths
25
201k
docstring
stringlengths
19
96.2k
func_name
stringlengths
0
235
language
stringclasses
1 value
repo
stringlengths
8
51
path
stringlengths
11
314
url
stringlengths
62
377
license
stringclasses
7 values
public T get() throws FlinkException { if (value != null) { return value; } checkNotNull(failureCause); throw new FlinkException(failureCause); }
@return stored value or throw a {@link FlinkException} with {@code failureCause}.
get
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/OptionalFailure.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/OptionalFailure.java
Apache-2.0
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static <T> Stream<T> stream(Optional<T> opt) { return opt.map(Stream::of).orElseGet(Stream::empty); }
Converts the given {@link Optional} into a {@link Stream}. <p>This is akin to {@code Optional#stream} available in JDK9+.
stream
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/OptionalUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/OptionalUtils.java
Apache-2.0
@SafeVarargs public static <T> Optional<T> firstPresent(Optional<T>... opts) { for (Optional<T> opt : opts) { if (opt.isPresent()) { return opt; } } return Optional.empty(); }
Returns the first {@link Optional} which is present.
firstPresent
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/OptionalUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/OptionalUtils.java
Apache-2.0
public static ParameterTool fromArgs(String[] args) { final Map<String, String> map = CollectionUtil.newHashMapWithExpectedSize(args.length / 2); int i = 0; while (i < args.length) { final String key = Utils.getKeyFromArgs(args, i); if (key.isEmpty()) { throw new IllegalArgumentException( "The input " + Arrays.toString(args) + " contains an empty argument"); } i += 1; // try to find the value if (i >= args.length) { map.put(key, AbstractParameterTool.NO_VALUE_KEY); } else if (NumberUtils.isNumber(args[i])) { map.put(key, args[i]); i += 1; } else if (args[i].startsWith("--") || args[i].startsWith("-")) { // the argument cannot be a negative number because we checked earlier // -> the next argument is a parameter name map.put(key, AbstractParameterTool.NO_VALUE_KEY); } else { map.put(key, args[i]); i += 1; } } return fromMap(map); }
Returns {@link ParameterTool} for the given arguments. The arguments are keys followed by values. Keys have to start with '-' or '--' <p><strong>Example arguments:</strong> --key1 value1 --key2 value2 -key3 value3 @param args Input array arguments @return A {@link ParameterTool}
fromArgs
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public static ParameterTool fromPropertiesFile(String path) throws IOException { File propertiesFile = new File(path); return fromPropertiesFile(propertiesFile); }
Returns {@link ParameterTool} for the given {@link Properties} file. @param path Path to the properties file @return A {@link ParameterTool} @throws IOException If the file does not exist @see Properties
fromPropertiesFile
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public static ParameterTool fromPropertiesFile(File file) throws IOException { if (!file.exists()) { throw new FileNotFoundException( "Properties file " + file.getAbsolutePath() + " does not exist"); } try (FileInputStream fis = new FileInputStream(file)) { return fromPropertiesFile(fis); } }
Returns {@link ParameterTool} for the given {@link Properties} file. @param file File object to the properties file @return A {@link ParameterTool} @throws IOException If the file does not exist @see Properties
fromPropertiesFile
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public static ParameterTool fromPropertiesFile(InputStream inputStream) throws IOException { Properties props = new Properties(); props.load(inputStream); return fromMap((Map) props); }
Returns {@link ParameterTool} for the given InputStream from {@link Properties} file. @param inputStream InputStream from the properties file @return A {@link ParameterTool} @throws IOException If the file does not exist @see Properties
fromPropertiesFile
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public static ParameterTool fromMap(Map<String, String> map) { Preconditions.checkNotNull(map, "Unable to initialize from empty map"); return new ParameterTool(map); }
Returns {@link ParameterTool} for the given map. @param map A map of arguments. Both Key and Value have to be Strings @return A {@link ParameterTool}
fromMap
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
@Override public String get(String key) { addToDefaults(key, null); unrequestedParameters.remove(key); return data.get(key); }
Returns the String value for the given key. If the key does not exist it will return null.
get
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public Configuration getConfiguration() { final Configuration conf = new Configuration(); for (Map.Entry<String, String> entry : data.entrySet()) { conf.setString(entry.getKey(), entry.getValue()); } return conf; }
Returns a {@link Configuration} object from this {@link ParameterTool}. @return A {@link Configuration}
getConfiguration
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public Properties getProperties() { Properties props = new Properties(); props.putAll(this.data); return props; }
Returns a {@link Properties} object from this {@link ParameterTool}. @return A {@link Properties}
getProperties
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public void createPropertiesFile(String pathToFile) throws IOException { createPropertiesFile(pathToFile, true); }
Create a properties file with all the known parameters (call after the last get*() call). Set the default value, if available. <p>Use this method to create a properties file skeleton. @param pathToFile Location of the default properties file.
createPropertiesFile
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ParameterTool.java
Apache-2.0
public static <T> T checkNotNull(@Nullable T reference) { if (reference == null) { throw new NullPointerException(); } return reference; }
Ensures that the given object reference is not null. Upon violation, a {@code NullPointerException} with no message is thrown. @param reference The object reference @return The object reference itself (generically typed). @throws NullPointerException Thrown, if the passed reference was null.
checkNotNull
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static <T> T checkNotNull( T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (reference == null) { throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } return reference; }
Ensures that the given object reference is not null. Upon violation, a {@code NullPointerException} with the given message is thrown. <p>The error message is constructed from a template and an arguments array, after a similar fashion as {@link String#format(String, Object...)}, but supporting only {@code %s} as a placeholder. @param reference The object reference @param errorMessageTemplate The message template for the {@code NullPointerException} that is thrown if the check fails. The template substitutes its {@code %s} placeholders with the error message arguments. @param errorMessageArgs The arguments for the error message, to be inserted into the message template for the {@code %s} placeholders. @return The object reference itself (generically typed). @throws NullPointerException Thrown, if the passed reference was null.
checkNotNull
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkArgument(boolean condition) { if (!condition) { throw new IllegalArgumentException(); } }
Checks the given boolean condition, and throws an {@code IllegalArgumentException} if the condition is not met (evaluates to {@code false}). @param condition The condition to check @throws IllegalArgumentException Thrown, if the condition is violated.
checkArgument
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkArgument( boolean condition, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!condition) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } }
Checks the given boolean condition, and throws an {@code IllegalArgumentException} if the condition is not met (evaluates to {@code false}). @param condition The condition to check @param errorMessageTemplate The message template for the {@code IllegalArgumentException} that is thrown if the check fails. The template substitutes its {@code %s} placeholders with the error message arguments. @param errorMessageArgs The arguments for the error message, to be inserted into the message template for the {@code %s} placeholders. @throws IllegalArgumentException Thrown, if the condition is violated.
checkArgument
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkState(boolean condition) { if (!condition) { throw new IllegalStateException(); } }
Checks the given boolean condition, and throws an {@code IllegalStateException} if the condition is not met (evaluates to {@code false}). @param condition The condition to check @throws IllegalStateException Thrown, if the condition is violated.
checkState
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkState(boolean condition, @Nullable Object errorMessage) { if (!condition) { throw new IllegalStateException(String.valueOf(errorMessage)); } }
Checks the given boolean condition, and throws an {@code IllegalStateException} if the condition is not met (evaluates to {@code false}). The exception will have the given error message. @param condition The condition to check @param errorMessage The message for the {@code IllegalStateException} that is thrown if the check fails. @throws IllegalStateException Thrown, if the condition is violated.
checkState
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkState( boolean condition, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!condition) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } }
Checks the given boolean condition, and throws an {@code IllegalStateException} if the condition is not met (evaluates to {@code false}). @param condition The condition to check @param errorMessageTemplate The message template for the {@code IllegalStateException} that is thrown if the check fails. The template substitutes its {@code %s} placeholders with the error message arguments. @param errorMessageArgs The arguments for the error message, to be inserted into the message template for the {@code %s} placeholders. @throws IllegalStateException Thrown, if the condition is violated.
checkState
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkElementIndex(int index, int size) { checkArgument(size >= 0, "Size was negative."); if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } }
Ensures that the given index is valid for an array, list or string of the given size. @param index index to check @param size size of the array, list or string @throws IllegalArgumentException Thrown, if size is negative. @throws IndexOutOfBoundsException Thrown, if the index negative or greater than or equal to size
checkElementIndex
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkElementIndex(int index, int size, @Nullable String errorMessage) { checkArgument(size >= 0, "Size was negative."); if (index < 0 || index >= size) { throw new IndexOutOfBoundsException( String.valueOf(errorMessage) + " Index: " + index + ", Size: " + size); } }
Ensures that the given index is valid for an array, list or string of the given size. @param index index to check @param size size of the array, list or string @param errorMessage The message for the {@code IndexOutOfBoundsException} that is thrown if the check fails. @throws IllegalArgumentException Thrown, if size is negative. @throws IndexOutOfBoundsException Thrown, if the index negative or greater than or equal to size
checkElementIndex
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public static void checkCompletedNormally(CompletableFuture<?> future) { checkState(future.isDone()); if (future.isCompletedExceptionally()) { try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }
Ensures that future has completed normally. @throws IllegalStateException Thrown, if future has not completed or it has completed exceptionally.
checkCompletedNormally
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
private static String format(@Nullable String template, @Nullable Object... args) { final int numArgs = args == null ? 0 : args.length; template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * numArgs); int templateStart = 0; int i = 0; while (i < numArgs) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < numArgs) { builder.append(" ["); builder.append(args[i++]); while (i < numArgs) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); }
A simplified formatting method. Similar to {@link String#format(String, Object...)}, but with lower overhead (only String parameters, no locale, no format validation). <p>This method is taken quasi verbatim from the Guava Preconditions class.
format
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Preconditions.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Preconditions.java
Apache-2.0
public MemoryAddressSize getAddressSize() { return addressSize; }
Gets the address size of the memory (32 bit, 64 bit).
getAddressSize
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
Apache-2.0
public String getArchitectureName() { return name; }
Gets the primary name of the processor architecture. The primary name would for example be "x86" or "amd64".
getArchitectureName
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
Apache-2.0
public List<String> getAlternativeNames() { return alternativeNames; }
Gets the alternative names for the processor architecture. Alternative names are for example "i586" for "x86", or "x86_64" for "amd64".
getAlternativeNames
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
Apache-2.0
public static ProcessorArchitecture getProcessorArchitecture() { return CURRENT; }
Gets the ProcessorArchitecture of the system running this process.
getProcessorArchitecture
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
Apache-2.0
public static int getInt(Properties config, String key, int defaultValue) { String val = config.getProperty(key); if (val == null) { return defaultValue; } else { try { return Integer.parseInt(val); } catch (NumberFormatException nfe) { throw new IllegalArgumentException( "Value for configuration key='" + key + "' is not set correctly. " + "Entered value='" + val + "'. Default value='" + defaultValue + "'"); } } }
Get integer from properties. This method throws an exception if the integer is not valid. @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key
getInt
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
Apache-2.0
public static long getLong(Properties config, String key, long defaultValue) { String val = config.getProperty(key); if (val == null) { return defaultValue; } else { try { return Long.parseLong(val); } catch (NumberFormatException nfe) { throw new IllegalArgumentException( "Value for configuration key='" + key + "' is not set correctly. " + "Entered value='" + val + "'. Default value='" + defaultValue + "'"); } } }
Get long from properties. This method throws an exception if the long is not valid. @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key
getLong
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
Apache-2.0
public static long getLong(Properties config, String key, long defaultValue, Logger logger) { try { return getLong(config, key, defaultValue); } catch (IllegalArgumentException iae) { logger.warn(iae.getMessage()); return defaultValue; } }
Get long from properties. This method only logs if the long is not valid. @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key
getLong
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
Apache-2.0
public static boolean getBoolean(Properties config, String key, boolean defaultValue) { String val = config.getProperty(key); if (val == null) { return defaultValue; } else { return Boolean.parseBoolean(val); } }
Get boolean from properties. This method returns {@code true} iff the parsed value is "true". @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key
getBoolean
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
Apache-2.0
public static Properties flatten(Properties config) { final Properties flattenProperties = new Properties(); Collections.list(config.propertyNames()).stream() .forEach( name -> { Preconditions.checkArgument(name instanceof String); flattenProperties.setProperty( (String) name, config.getProperty((String) name)); }); return flattenProperties; }
Flatten a recursive {@link Properties} to a first level property map. <p>In some cases, {@code KafkaProducer#propsToMap} for example, Properties is used purely as a HashTable without considering its default properties. @param config Properties to be flattened @return Properties without defaults; all properties are put in the first-level
flatten
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
Apache-2.0
public T deref() { return value; }
Wrapper class that allows to express whether the value is borrowed or owned. @param <T> type of the value
deref
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Reference.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Reference.java
Apache-2.0
public static FullTypeInfo getFullTemplateType(Type type, int templatePosition) { if (type instanceof ParameterizedType) { return getFullTemplateType( ((ParameterizedType) type).getActualTypeArguments()[templatePosition]); } else { throw new IllegalArgumentException(); } }
Extract the full template type information from the given type's template parameter at the given position. @param type type to extract the full template parameter information from @param templatePosition describing at which position the template type parameter is @return Full type information describing the template parameter's type
getFullTemplateType
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ReflectionUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ReflectionUtil.java
Apache-2.0
public static FullTypeInfo getFullTemplateType(Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; FullTypeInfo[] templateTypeInfos = new FullTypeInfo[parameterizedType.getActualTypeArguments().length]; for (int i = 0; i < parameterizedType.getActualTypeArguments().length; i++) { templateTypeInfos[i] = getFullTemplateType(parameterizedType.getActualTypeArguments()[i]); } return new FullTypeInfo((Class<?>) parameterizedType.getRawType(), templateTypeInfos); } else { return new FullTypeInfo((Class<?>) type, null); } }
Extract the full type information from the given type. @param type to be analyzed @return Full type information describing the given type
getFullTemplateType
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ReflectionUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ReflectionUtil.java
Apache-2.0
public Lease acquireResource() throws IOException { synchronized (lock) { if (closed) { throw new IOException("Resource guard was already closed."); } ++leaseCount; } return new Lease(); }
Acquired access from one new client for the guarded resource. @throws IOException when the resource guard is already closed.
acquireResource
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
@SuppressWarnings("WeakerAccess") public void closeUninterruptibly() { boolean interrupted = false; synchronized (lock) { closed = true; while (leaseCount > 0) { try { lock.wait(); } catch (InterruptedException e) { interrupted = true; } } } if (interrupted) { Thread.currentThread().interrupt(); } }
If the current thread is {@linkplain Thread#interrupt interrupted} while waiting for the close method to complete, then it will continue to wait. When the thread does return from this method its interrupt status will be set.
closeUninterruptibly
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
@Override public void close() { closeUninterruptibly(); }
Closed the resource guard. This method will block until all calls to {@link #acquireResource()} have seen their matching call to {@link #releaseResource()}.
close
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
public boolean isClosed() { return closed; }
Returns true if the resource guard is closed, i.e. after {@link #close()} was called.
isClosed
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
public int getLeaseCount() { return leaseCount; }
Returns the current count of open leases.
getLeaseCount
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
@Override public void close() { if (closed.compareAndSet(false, true)) { releaseResource(); } }
A lease is issued by the {@link ResourceGuard} as result of calls to {@link #acquireResource()}. The owner of the lease can release it via the {@link #close()} call.
close
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ResourceGuard.java
Apache-2.0
public T deserializeValue(ClassLoader loader) throws IOException, ClassNotFoundException { Preconditions.checkNotNull(loader, "No classloader has been passed"); return InstantiationUtil.deserializeObject(serializedData, loader); }
Constructs a serialized value. @param value value to serialize @throws NullPointerException if value is null @throws IOException exception during serialization
deserializeValue
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/SerializedValue.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/SerializedValue.java
Apache-2.0
public byte[] getByteArray() { return serializedData; }
Returns byte array for serialized data. @return Serialized data.
getByteArray
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/SerializedValue.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/SerializedValue.java
Apache-2.0
public static Thread addShutdownHook( final AutoCloseable service, final String serviceName, final Logger logger) { checkNotNull(service); checkNotNull(logger); final Thread shutdownHook = new Thread( () -> { try { service.close(); } catch (Throwable t) { logger.error( "Error during shutdown of {} via JVM shutdown hook.", serviceName, t); } }, serviceName + " shutdown hook"); return addShutdownHookThread(shutdownHook, serviceName, logger) ? shutdownHook : null; }
Adds a shutdown hook to the JVM and returns the Thread, which has been registered.
addShutdownHook
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
Apache-2.0
public static boolean addShutdownHookThread( final Thread shutdownHook, final String serviceName, final Logger logger) { checkNotNull(shutdownHook); checkNotNull(logger); try { // Add JVM shutdown hook to call shutdown of service Runtime.getRuntime().addShutdownHook(shutdownHook); return true; } catch (IllegalStateException e) { // JVM is already shutting down. no need to do our work } catch (Throwable t) { logger.error( "Cannot register shutdown hook that cleanly terminates {}.", serviceName, t); } return false; }
Adds a shutdown hook to the JVM. @param shutdownHook Shutdown hook to be registered. @param serviceName The name of service. @param logger The logger to log. @return Whether the hook has been successfully registered.
addShutdownHookThread
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
Apache-2.0
public static void removeShutdownHook( final Thread shutdownHook, final String serviceName, final Logger logger) { // Do not run if this is invoked by the shutdown hook itself if (shutdownHook == null || shutdownHook == Thread.currentThread()) { return; } checkNotNull(logger); try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException e) { // race, JVM is in shutdown already, we can safely ignore this logger.debug( "Unable to remove shutdown hook for {}, shutdown already in progress", serviceName, e); } catch (Throwable t) { logger.warn("Exception while un-registering {}'s shutdown hook.", serviceName, t); } }
Removes a shutdown hook from the JVM.
removeShutdownHook
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/ShutdownHookUtil.java
Apache-2.0
public Iterator<T> getSplit(int num, int numPartitions) { if (numPartitions < 1 || num < 0 || num >= numPartitions) { throw new IllegalArgumentException(); } return split(numPartitions)[num]; }
Splits this iterator into <i>n</i> partitions and returns the <i>i-th</i> partition out of those. @param num The partition to return (<i>i</i>). @param numPartitions The number of partitions to split into (<i>n</i>). @return The iterator for the partition.
getSplit
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/SplittableIterator.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/SplittableIterator.java
Apache-2.0
public static StateMigrationException notSupported() { return new StateMigrationException(MIGRATION_NOT_SUPPORTED_MSG); }
Base class for state migration related exceptions.
notSupported
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StateMigrationException.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StateMigrationException.java
Apache-2.0
public static String byteToHexString(final byte[] bytes, final int start, final int end) { if (bytes == null) { throw new IllegalArgumentException("bytes == null"); } int length = end - start; char[] out = new char[length * 2]; for (int i = start, j = 0; i < end; i++) { out[j++] = HEX_CHARS[(0xF0 & bytes[i]) >>> 4]; out[j++] = HEX_CHARS[0x0F & bytes[i]]; } return new String(out); }
Given an array of bytes it will convert the bytes to a hex string representation of the bytes. @param bytes the bytes to convert in a hex string @param start start index, inclusively @param end end index, exclusively @return hex string representation of the byte array
byteToHexString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String byteToHexString(final byte[] bytes) { return byteToHexString(bytes, 0, bytes.length); }
Given an array of bytes it will convert the bytes to a hex string representation of the bytes. @param bytes the bytes to convert in a hex string @return hex string representation of the byte array
byteToHexString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static byte[] hexStringToByte(final String hex) { final byte[] bts = new byte[hex.length() / 2]; for (int i = 0; i < bts.length; i++) { bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return bts; }
Given a hex string this will return the byte array corresponding to the string . @param hex the hex String array @return a byte array that is a hex string representation of the given string. The size of the byte array is therefore hex.length/2
hexStringToByte
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String showControlCharacters(String str) { int len = str.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i += 1) { char c = str.charAt(i); switch (c) { case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: sb.append(c); } } return sb.toString(); }
Replaces control characters by their escape-coded version. For example, if the string contains a line break character ('\n'), this character will be replaced by the two characters backslash '\' and 'n'. As a consequence, the resulting string will not contain any more control characters. @param str The string in which to replace the control characters. @return The string with the replaced characters.
showControlCharacters
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String getRandomString(Random rnd, int minLength, int maxLength) { int len = rnd.nextInt(maxLength - minLength + 1) + minLength; char[] data = new char[len]; for (int i = 0; i < data.length; i++) { data[i] = (char) (rnd.nextInt(0x7fff) + 1); } return new String(data); }
Creates a random string with a length within the given interval. The string contains only characters that can be represented as a single code point. @param rnd The random used to create the strings. @param minLength The minimum string length. @param maxLength The maximum string length (inclusive). @return A random String.
getRandomString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String getRandomString( Random rnd, int minLength, int maxLength, char minValue, char maxValue) { int len = rnd.nextInt(maxLength - minLength + 1) + minLength; char[] data = new char[len]; int diff = maxValue - minValue + 1; for (int i = 0; i < data.length; i++) { data[i] = (char) (rnd.nextInt(diff) + minValue); } return new String(data); }
Creates a random string with a length within the given interval. The string contains only characters that can be represented as a single code point. @param rnd The random used to create the strings. @param minLength The minimum string length. @param maxLength The maximum string length (inclusive). @param minValue The minimum character value to occur. @param maxValue The maximum character value to occur. @return A random String.
getRandomString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static void writeString(@Nonnull String str, DataOutputView out) throws IOException { checkNotNull(str); StringValue.writeString(str, out); }
Writes a String to the given output. The written string can be read with {@link #readString(DataInputView)}. @param str The string to write @param out The output to write to @throws IOException Thrown, if the writing or the serialization fails.
writeString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String readString(DataInputView in) throws IOException { return StringValue.readString(in); }
Reads a non-null String from the given input. @param in The input to read from @return The deserialized String @throws IOException Thrown, if the reading or the deserialization fails.
readString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static void writeNullableString(@Nullable String str, DataOutputView out) throws IOException { if (str != null) { out.writeBoolean(true); writeString(str, out); } else { out.writeBoolean(false); } }
Writes a String to the given output. The string may be null. The written string can be read with {@link #readNullableString(DataInputView)}- @param str The string to write, or null. @param out The output to write to. @throws IOException Thrown, if the writing or the serialization fails.
writeNullableString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static @Nullable String readNullableString(DataInputView in) throws IOException { if (in.readBoolean()) { return readString(in); } else { return null; } }
Reads a String from the given input. The string may be null and must have been written with {@link #writeNullableString(String, DataOutputView)}. @param in The input to read from. @return The deserialized string, or null. @throws IOException Thrown, if the reading or the deserialization fails.
readNullableString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
@Nullable public static String concatenateWithAnd(@Nullable String s1, @Nullable String s2) { if (s1 != null) { return s2 == null ? s1 : s1 + " and " + s2; } else { return s2; } }
If both string arguments are non-null, this method concatenates them with ' and '. If only one of the arguments is non-null, this method returns the non-null argument. If both arguments are null, this method returns null. @param s1 The first string argument @param s2 The second string argument @return The concatenated string, or non-null argument, or null
concatenateWithAnd
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static String toQuotedListString(Object[] values) { return Arrays.stream(values) .filter(Objects::nonNull) .map(v -> v.toString().toLowerCase()) .collect(Collectors.joining(", ", "\"", "\"")); }
Generates a string containing a comma-separated list of values in double-quotes. Uses lower-cased values returned from {@link Object#toString()} method for each element in the given array. Null values are skipped. @param values array of elements for the list @return The string with quoted list of elements
toQuotedListString
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringUtils.java
Apache-2.0
public static void toLowerCase(StringValue string) { final char[] chars = string.getCharArray(); final int len = string.length(); for (int i = 0; i < len; i++) { chars[i] = Character.toLowerCase(chars[i]); } }
Converts the given <code>StringValue</code> into a lower case variant. @param string The string to convert to lower case.
toLowerCase
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
Apache-2.0
public static void replaceNonWordChars(StringValue string, char replacement) { final char[] chars = string.getCharArray(); final int len = string.length(); for (int i = 0; i < len; i++) { final char c = chars[i]; if (!(Character.isLetter(c) || Character.isDigit(c) || c == '_')) { chars[i] = replacement; } } }
Replaces all non-word characters in a string by a given character. The only characters not replaced are the characters that qualify as word characters or digit characters with respect to {@link Character#isLetter(char)} or {@link Character#isDigit(char)}, as well as the underscore character. <p>This operation is intended to simplify strings for counting distinct words. @param string The string value to have the non-word characters replaced. @param replacement The character to use as the replacement.
replaceNonWordChars
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
Apache-2.0
public void setStringToTokenize(StringValue string) { this.toTokenize = string; this.pos = 0; this.limit = string.length(); }
Sets the string to be tokenized and resets the state of the tokenizer. @param string The string value to be tokenized.
setStringToTokenize
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
Apache-2.0
public boolean next(StringValue target) { final char[] data = this.toTokenize.getCharArray(); final int limit = this.limit; int pos = this.pos; // skip the delimiter for (; pos < limit && Character.isWhitespace(data[pos]); pos++) {} if (pos >= limit) { this.pos = pos; return false; } final int start = pos; for (; pos < limit && !Character.isWhitespace(data[pos]); pos++) {} this.pos = pos; target.setValue(this.toTokenize, start, pos - start); return true; }
Gets the next token from the string. If another token is available, the token is stored in the given target StringValue object. @param target The StringValue object to store the next token in. @return True, if there was another token, false if not.
next
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/StringValueUtils.java
Apache-2.0
public boolean getOrDefault(boolean defaultValue) { return this == UNDEFINED ? defaultValue : (this == TRUE); }
Gets the boolean value corresponding to this value. If this is the 'undefined' value, the method returns the given default. @param defaultValue The value to be returned in case this ternary value is 'undefined'.
getOrDefault
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
public TernaryBoolean resolveUndefined(boolean valueForUndefined) { return this != UNDEFINED ? this : fromBoolean(valueForUndefined); }
Gets the boolean value corresponding to this value. If this is the 'UNDEFINED' value, the method returns the given valueForUndefined. @param valueForUndefined The value to be returned in case this ternary value is 'undefined'.
resolveUndefined
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
@Nullable public Boolean getAsBoolean() { return this == UNDEFINED ? null : (this == TRUE ? Boolean.TRUE : Boolean.FALSE); }
Gets this ternary boolean as a boxed boolean. The value 'undefined' results in 'null.
getAsBoolean
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
public static TernaryBoolean mergeTernaryBooleanWithConfig( TernaryBoolean original, ConfigOption<Boolean> configOption, ReadableConfig config) { if (original != TernaryBoolean.UNDEFINED) { return original; } return TernaryBoolean.fromBoxedBoolean(config.getOptional(configOption).orElse(null)); }
Merges an existing value with a config, accepting the config's value only if the existing value is undefined. @param original the value to merge with the config. @param configOption the config option to merge with from the config. @param config the config to merge with.
mergeTernaryBooleanWithConfig
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
public static TernaryBoolean fromBoolean(boolean bool) { return bool ? TRUE : FALSE; }
Converts the given boolean to a TernaryBoolean, {@link #TRUE} or {@link #FALSE} respectively.
fromBoolean
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
public static TernaryBoolean fromBoxedBoolean(@Nullable Boolean bool) { return bool == null ? UNDEFINED : fromBoolean(bool); }
Converts the given boxed Boolean to a TernaryBoolean. A null value results in {@link #UNDEFINED}, while a non-null value results in {@link #TRUE} or {@link #FALSE} respectively.
fromBoxedBoolean
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TernaryBoolean.java
Apache-2.0
public static String getStringInMillis(final Duration duration) { return duration.toMillis() + TimeUnit.MILLISECONDS.labels.get(0); }
@param duration to convert to string @return duration string in millis
getStringInMillis
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
Apache-2.0
public static String formatWithHighestUnit(Duration duration) { BigInteger nanos = toNanos(duration); TimeUnit highestIntegerUnit = getHighestIntegerUnit(nanos); return String.format( "%s %s", nanos.divide(highestIntegerUnit.getUnitAsNanos()), highestIntegerUnit.getLabels().get(0)); }
Pretty prints the duration as a lowest granularity unit that does not lose precision. <p>Examples: <pre>{@code Duration.ofMilliseconds(60000) will be printed as 1 min Duration.ofHours(1).plusSeconds(1) will be printed as 3601 s }</pre> <b>NOTE:</b> It supports only durations that fit into long.
formatWithHighestUnit
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
Apache-2.0
private static String[] singular(String label) { return new String[] {label}; }
@param label the original label @return the singular format of the original label
singular
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/TimeUtils.java
Apache-2.0
public static <T> Optional<T> resolveFactory( ThreadLocal<T> threadLocalFactory, @Nullable T staticFactory) { final T localFactory = threadLocalFactory.get(); final T factory = localFactory == null ? staticFactory : localFactory; return Optional.ofNullable(factory); }
Resolves the given factories. The thread local factory has preference over the static factory. If none is set, the method returns {@link Optional#empty()}. @param threadLocalFactory containing the thread local factory @param staticFactory containing the global factory @param <T> type of factory @return Optional containing the resolved factory if it exists, otherwise it's empty
resolveFactory
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Utils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Utils.java
Apache-2.0
public static String getKeyFromArgs(String[] args, int index) { String key; if (args[index].startsWith("--")) { key = args[index].substring(2); } else if (args[index].startsWith("-")) { key = args[index].substring(1); } else { throw new IllegalArgumentException( String.format( "Error parsing arguments '%s' on '%s'. Please prefix keys with -- or -.", Arrays.toString(args), args[index])); } if (key.isEmpty()) { throw new IllegalArgumentException( "The input " + Arrays.toString(args) + " contains an empty argument"); } return key; }
Get the key from the given args. Keys have to start with '-' or '--'. For example, --key1 value1 -key2 value2. @param args all given args. @param index the index of args to be parsed. @return the key of the given arg.
getKeyFromArgs
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/Utils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/Utils.java
Apache-2.0
public Throwable unwrap() { Throwable cause = getCause(); return (cause instanceof WrappingRuntimeException) ? ((WrappingRuntimeException) cause).unwrap() : cause; }
Recursively unwraps this WrappingRuntimeException and its causes, getting the first non wrapping exception. @return The first cause that is not a wrapping exception.
unwrap
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/WrappingRuntimeException.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/WrappingRuntimeException.java
Apache-2.0
public static RuntimeException wrapIfNecessary(Throwable throwable) { if (throwable instanceof RuntimeException) { return (RuntimeException) throwable; } return new WrappingRuntimeException(throwable); }
Ensures that any throwable can be thrown as a checked exception by potentially wrapping it. @return a runtime exception wrapping the throwable if checked or by returning the throwable if it's a runtime exception.
wrapIfNecessary
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/WrappingRuntimeException.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/WrappingRuntimeException.java
Apache-2.0
@Override public int next(int bits) { long nextSeed = seed ^ (seed << 21); nextSeed ^= (nextSeed >>> 35); nextSeed ^= (nextSeed << 4); seed = nextSeed; return (int) (nextSeed & ((1L << bits) - 1)); }
All other methods like nextInt()/nextDouble()... depends on this, so we just need to overwrite this. @param bits Random bits @return The next pseudorandom value from this random number generator's sequence
next
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/XORShiftRandom.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/XORShiftRandom.java
Apache-2.0
public static Executor directExecutor() { return DirectExecutor.INSTANCE; }
Return a direct executor. The direct executor directly executes the runnable in the calling thread. @return Direct executor
directExecutor
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/Executors.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/Executors.java
Apache-2.0
public static ExecutorService newDirectExecutorService() { return new DirectExecutorService(true); }
Creates a more {@link ExecutorService} that runs the passed task in the calling thread.
newDirectExecutorService
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/Executors.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/Executors.java
Apache-2.0
@Override public Thread newThread(Runnable runnable) { Thread t = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement()); t.setDaemon(true); t.setPriority(threadPriority); // optional handler for uncaught exceptions if (exceptionHandler != null) { t.setUncaughtExceptionHandler(exceptionHandler); } return t; }
Creates a new thread factory using the given thread pool name and the given uncaught exception handler. @param poolName The pool name, used as the threads' name prefix @param exceptionHandler The uncaught exception handler for the threads
newThread
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/ExecutorThreadFactory.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/ExecutorThreadFactory.java
Apache-2.0
@Override default void accept(T value) { try { acceptWithException(value); } catch (Throwable t) { throw new CompletionException(t); } }
A checked extension of the {@link Consumer} interface which rethrows exceptions wrapped in a {@link CompletionException}. @param <T> type of the first argument @param <E> type of the thrown exception
accept
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureConsumerWithException.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureConsumerWithException.java
Apache-2.0
public static CompletableFuture<Void> completedVoidFuture() { return COMPLETED_VOID_FUTURE; }
Returns a completed future of type {@link Void}. @return a completed future of type {@link Void}
completedVoidFuture
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> unsupportedOperationFuture() { return (CompletableFuture<T>) UNSUPPORTED_OPERATION_FUTURE; }
Returns an exceptionally completed future with an {@link UnsupportedOperationException}. @param <T> type of the future @return exceptionally completed future
unsupportedOperationFuture
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> void completeFromCallable( CompletableFuture<T> future, Callable<T> operation) { try { future.complete(operation.call()); } catch (Exception e) { future.completeExceptionally(e); } }
Fakes asynchronous execution by immediately executing the operation and completing the supplied future either normally or exceptionally. @param operation to executed @param <T> type of the result
completeFromCallable
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor) { return retry(operation, retries, ignore -> true, executor); }
Retry the given operation the given number of times in case of a failure. @param operation to executed @param retries if the operation failed @param executor to use to run the futures @param <T> type of the result @return Future containing either the result of the operation or a {@link RetryException}
retry
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Predicate<Throwable> retryPredicate, final Executor executor) { final CompletableFuture<T> resultFuture = new CompletableFuture<>(); retryOperation(resultFuture, operation, retries, retryPredicate, executor); return resultFuture; }
Retry the given operation the given number of times in case of a failure only when an exception is retryable. @param operation to executed @param retries if the operation failed @param retryPredicate Predicate to test whether an exception is retryable @param executor to use to run the futures @param <T> type of the result @return Future containing either the result of the operation or a {@link RetryException}
retry
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
private static <T> void retryOperation( final CompletableFuture<T> resultFuture, final Supplier<CompletableFuture<T>> operation, final int retries, final Predicate<Throwable> retryPredicate, final Executor executor) { if (!resultFuture.isDone()) { final CompletableFuture<T> operationFuture = operation.get(); operationFuture.whenCompleteAsync( (t, throwable) -> { if (throwable != null) { if (throwable instanceof CancellationException) { resultFuture.completeExceptionally( new RetryException( "Operation future was cancelled.", throwable)); } else { throwable = ExceptionUtils.stripExecutionException(throwable); if (!retryPredicate.test(throwable)) { resultFuture.completeExceptionally( new RetryException( "Stopped retrying the operation because the error is not " + "retryable.", throwable)); } else { if (retries > 0) { retryOperation( resultFuture, operation, retries - 1, retryPredicate, executor); } else { resultFuture.completeExceptionally( new RetryException( "Could not complete the operation. Number of retries " + "has been exhausted.", throwable)); } } } } else { resultFuture.complete(t); } }, executor); resultFuture.whenComplete((t, throwable) -> operationFuture.cancel(false)); } }
Helper method which retries the provided operation in case of a failure. @param resultFuture to complete @param operation to retry @param retries until giving up @param retryPredicate Predicate to test whether an exception is retryable @param executor to run the futures @param <T> type of the future's result
retryOperation
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final RetryStrategy retryStrategy, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor) { final CompletableFuture<T> resultFuture = new CompletableFuture<>(); retryOperationWithDelay( resultFuture, operation, retryStrategy, retryPredicate, scheduledExecutor); return resultFuture; }
Retry the given operation with the given delay in between failures. @param operation to retry @param retryStrategy the RetryStrategy @param retryPredicate Predicate to test whether an exception is retryable @param scheduledExecutor executor to be used for the retry operation @param <T> type of the result @return Future which retries the given operation a given amount of times and delays the retry in case of failures
retryWithDelay
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> orTimeout( CompletableFuture<T> future, long timeout, TimeUnit timeUnit, @Nullable String timeoutMsg) { return orTimeout(future, timeout, timeUnit, Executors.directExecutor(), timeoutMsg); }
Times the given future out after the timeout. @param future to time out @param timeout after which the given future is timed out @param timeUnit time unit of the timeout @param timeoutMsg timeout message for exception @param <T> type of the given future @return The timeout enriched future
orTimeout
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> orTimeout( CompletableFuture<T> future, long timeout, TimeUnit timeUnit, Executor timeoutFailExecutor, @Nullable String timeoutMsg) { if (!future.isDone()) { final ScheduledFuture<?> timeoutFuture = Delayer.delay( () -> timeoutFailExecutor.execute(new Timeout(future, timeoutMsg)), timeout, timeUnit); future.whenComplete( (T value, Throwable throwable) -> { if (!timeoutFuture.isDone()) { timeoutFuture.cancel(false); } }); } return future; }
Times the given future out after the timeout. @param future to time out @param timeout after which the given future is timed out @param timeUnit time unit of the timeout @param timeoutFailExecutor executor that will complete the future exceptionally after the timeout is reached @param timeoutMsg timeout message for exception @param <T> type of the given future @return The timeout enriched future
orTimeout
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> void completeDelayed(CompletableFuture<T> future, T success, Duration delay) { Delayer.delay(() -> future.complete(success), delay.toMillis(), TimeUnit.MILLISECONDS); }
Asynchronously completes the future after a certain delay. @param future The future to complete. @param success The element to complete the future with. @param delay The delay after which the future should be completed.
completeDelayed
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> T runIfNotDoneAndGet(RunnableFuture<T> future) throws ExecutionException, InterruptedException { if (null == future) { return null; } if (!future.isDone()) { future.run(); } return future.get(); }
Run the given {@code RunnableFuture} if it is not done, and then retrieves its result. @param future to run if not done and get @param <T> type of the result @return the result after running the future @throws ExecutionException if a problem occurred @throws InterruptedException if the current thread has been interrupted
runIfNotDoneAndGet
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor) { final CompletableFuture<Void> resultFuture = new CompletableFuture<>(); future.whenCompleteAsync( (Object ignored, Throwable throwable) -> { try { runnable.run(); } catch (Throwable e) { throwable = ExceptionUtils.firstOrSuppressed(e, throwable); } if (throwable != null) { resultFuture.completeExceptionally(throwable); } else { resultFuture.complete(null); } }, executor); return resultFuture; }
Run the given action after the completion of the given future. The given future can be completed normally or exceptionally. In case of an exceptional completion the action's exception will be added to the initial exception. @param future to wait for its completion @param runnable action which is triggered after the future's completion @param executor to run the given action @return Future which is completed after the action has completed. This future can contain an exception, if an error occurred in the given future or action.
runAfterwardsAsync
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction) { return composeAfterwardsInternal(future, composedAction, CompletableFuture::whenComplete); }
Run the given asynchronous action after the completion of the given future. The given future can be completed normally or exceptionally. In case of an exceptional completion, the asynchronous action's exception will be added to the initial exception. @param future to wait for its completion @param composedAction asynchronous action which is triggered after the future's completion @return Future which is completed after the asynchronous action has completed. This future can contain an exception if an error occurred in the given future or asynchronous action.
composeAfterwards
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> ConjunctFuture<Collection<T>> combineAll( Collection<? extends CompletableFuture<? extends T>> futures) { checkNotNull(futures, "futures"); return new ResultConjunctFuture<>(futures); }
Creates a future that is complete once multiple other futures completed. The future fails (completes exceptionally) once one of the futures in the conjunction fails. Upon successful completion, the future returns the collection of the futures' results. <p>The ConjunctFuture gives access to how many Futures in the conjunction have already completed successfully, via {@link ConjunctFuture#getNumFuturesCompleted()}. @param futures The futures that make up the conjunction. No null entries are allowed. @return The ConjunctFuture that completes once all given futures are complete (or one fails).
combineAll
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static ConjunctFuture<Void> waitForAll( Collection<? extends CompletableFuture<?>> futures) { checkNotNull(futures, "futures"); return new WaitingConjunctFuture(futures); }
Creates a future that is complete once all of the given futures have completed. The future fails (completes exceptionally) once one of the given futures fails. <p>The ConjunctFuture gives access to how many Futures have already completed successfully, via {@link ConjunctFuture#getNumFuturesCompleted()}. @param futures The futures to wait on. No null entries are allowed. @return The WaitingFuture that completes once all given futures are complete (or one fails).
waitForAll
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
private void handleCompletedFuture(int index, T value, Throwable throwable) { if (throwable != null) { completeExceptionally(throwable); } else { /** * This {@link #results} update itself is not synchronised in any way and it's fine * because: * * <ul> * <li>There is a happens-before relationship for each thread (that is completing * the future) between setting {@link #results} and incrementing {@link * #numCompleted}. * <li>Each thread is updating uniquely different field of the {@link #results} * array. * <li>There is a happens-before relationship between all of the writing threads * and the last one thread (thanks to the {@code * numCompleted.incrementAndGet() == numTotal} check. * <li>The last thread will be completing the future, so it has transitively * happens-before relationship with all of preceding updated/writes to {@link * #results}. * <li>{@link AtomicInteger#incrementAndGet} is an equivalent of both volatile * read & write * </ul> */ results[index] = value; if (numCompleted.incrementAndGet() == numTotal) { complete(Arrays.asList(results)); } } }
The function that is attached to all futures in the conjunction. Once a future is complete, this function tracks the completion or fails the conjunct.
handleCompletedFuture
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static ConjunctFuture<Void> completeAll( Collection<? extends CompletableFuture<?>> futuresToComplete) { return new CompletionConjunctFuture(futuresToComplete); }
Creates a {@link ConjunctFuture} which is only completed after all given futures have completed. Unlike {@link FutureUtils#waitForAll(Collection)}, the resulting future won't be completed directly if one of the given futures is completed exceptionally. Instead, all occurring exception will be collected and combined to a single exception. If at least on exception occurs, then the resulting future will be completed exceptionally. @param futuresToComplete futures to complete @return Future which is completed after all given futures have been completed.
completeAll
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0
public static <T> CompletableFuture<T> completedExceptionally(Throwable cause) { CompletableFuture<T> result = new CompletableFuture<>(); result.completeExceptionally(cause); return result; }
Returns an exceptionally completed {@link CompletableFuture}. @param cause to complete the future with @param <T> type of the future @return An exceptionally completed CompletableFuture
completedExceptionally
java
apache/flink
flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
https://github.com/apache/flink/blob/master/flink-core/src/main/java/org/apache/flink/util/concurrent/FutureUtils.java
Apache-2.0