1 package com.samsung.commons.utils.sync;
3 import org.apache.log4j.Logger;
5 import java.util.Optional;
7 import static java.util.Optional.empty;
8 import static java.util.Optional.ofNullable;
11 * Makes synchronous call
13 * @param <T> return type
15 public class Synchronous<T> {
17 private final Logger log = Logger.getLogger(Synchronous.class);
19 // Default timeout (ms)
20 private static final int DEFAULT_TIMEOUT = 1000;
22 // Default maximum rounds
23 private static final int DEFAULT_MAX_ROUNDS = 10;
25 private final Object lock = new Object();
27 private boolean firstTime = true;
29 // How long to wait before the next try
30 private int timeout = DEFAULT_TIMEOUT;
32 // Max tries before exit
33 private int maxRounds = DEFAULT_MAX_ROUNDS;
39 private boolean finished = false;
44 * @param maxRounds max rounds
45 * @param timeout timeout
47 public Synchronous(int maxRounds, int timeout) {
48 this.maxRounds = maxRounds;
49 this.timeout = timeout;
53 * Create with parameters
55 * @param maxRounds max rounds
56 * @param timeout timeout
60 public static <T> Synchronous<T> withParams(int maxRounds, int timeout) {
61 return new Synchronous<>(maxRounds, timeout);
67 * @param result result
69 void success(T result) {
70 log.trace("Result getting succeeded");
80 log.trace("Result getting failed");
88 * @param asyncCode async code
91 public Optional<T> execute(AsyncCode<T> asyncCode) {
94 log.error("Already executed. Create new Synchronous and execute again.");
102 synchronized (lock) {
107 ResultCallback<T> resultCallback = new ResultCallback<>(this);
109 asyncCode.async(resultCallback);
111 } catch (Exception e) {
112 log.error("Error on running asynchronous code. Return empty.", e);
123 if (this.maxRounds == rounds) {
124 log.debug("Max rounds exceeded. " +
125 "Check finished() method invocation after async code has been finished.");
130 return ofNullable(this.result);
133 } catch (InterruptedException e) {
134 log.error("Interrupted. Return empty.");