logo
down
shadow

making sure one task completes before another starts in java


making sure one task completes before another starts in java

Content Index :

making sure one task completes before another starts in java
Tag : java , By : PaulPlum
Date : November 24 2020, 05:47 AM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Java executors: how to be notified, without blocking, when a task completes?


Tag : java , By : Dré
Date : March 29 2020, 07:55 AM
This might help you Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task.
You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService. Or, see below for a mechanism built into Java 8.
class CallbackTask implements Runnable {

  private final Runnable task;

  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  public void run() {
    task.run();
    callback.complete();
  }

}
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class GetTaskNotificationWithoutBlocking {

  public static void main(String... argv) throws Exception {
    ExampleService svc = new ExampleService();
    GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking();
    CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
    f.thenAccept(listener::notify);
    System.out.println("Exiting main()");
  }

  void notify(String msg) {
    System.out.println("Received message: " + msg);
  }

}

class ExampleService {

  String work() {
    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
    char[] str = new char[5];
    ThreadLocalRandom current = ThreadLocalRandom.current();
    for (int idx = 0; idx < str.length; ++idx)
      str[idx] = (char) ('A' + current.nextInt(26));
    String msg = new String(str);
    System.out.println("Generated message: " + msg);
    return msg;
  }

  public static void sleep(long average, TimeUnit unit) {
    String name = Thread.currentThread().getName();
    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
    try {
      unit.sleep(timeout);
      System.out.println(name + " awoke.");
    } catch (InterruptedException abort) {
      Thread.currentThread().interrupt();
      System.out.println(name + " interrupted.");
    }
  }

  public static long exponential(long avg) {
    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
  }

}

Starts several tasks at once and then start another task when one completes


Tag : chash , By : KS9
Date : March 29 2020, 07:55 AM
I hope this helps you . I have a code that runs in a asp.net web api which download image files from another sites. , You can use SemaphoreSlim to throttle asynchronous work:
private readonly SemaphoreSlim _mutex = new SemaphoreSlim(10);

...

var downloads = images.Select(file => DownloadAsync(file));
await Task.WhenAll(downloads);

...

private async Task DownloadAsync(string file)
{
  await _mutex.WaitAsync();
  try
  {
    using (WebClient client = new WebClient())
    {
      await client.DownloadFileTaskAsync(file, path + Path.GetFileName(file));                    
    }
  }
  finally
  {
    _mutex.Release();
  }
}

Java Timer is waiting for Task to finish before next Task starts


Tag : java , By : Joe Sweeney
Date : March 29 2020, 07:55 AM
wish helps you Quoting the Javadoc:

Java application hungs up for long time even script on remote server completes the task


Tag : java , By : Sonal
Date : March 29 2020, 07:55 AM

With Spark Java RDDs, how can I process individual task results immediately as each one completes without waiting for co


Tag : java , By : jonagh
Date : March 29 2020, 07:55 AM
like below fixes the issue Either you push your logic to be distributed as well (e.g. using a udf) or you can create a similar process in spark streaming and work with small batches
Related Posts Related QUESTIONS :
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How do I avoid using if statements with a large amount of variables in java
  • Writing JUnit test cases for a Spring Boot Service Application with autowired components
  • Cors for GET with Postman not showing headers
  • Printing values in different column same row using APACHE POI
  • Fully decompile java6 web application
  • Passing keycloak configuration parameters in the code rather than reading from application.properties
  • setDataSource() IO exception
  • Unexpected Output while retrieving Data from mongodb and displaying in a csv file?
  • Algorithm for searching a value in two arrays
  • How to avoid casting with generic return values?
  • Java/RegEx - Negation of pattern not working
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com