this post was submitted on 16 Jun 2023
16 points (100.0% liked)

Java

1416 readers
1 users here now

For discussing Java, the JVM, languages that run on the JVM, and other related technologies.

founded 2 years ago
MODERATORS
 

I'm curious if there are things in the standard class library that you find useful but not widely used.

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 6 points 2 years ago (2 children)

Sometimes people who build low-level code with mutable state that's shared across threads don't know about some of the synchronization tools Java has. A lot of people know about synchronized, a lot of people know about semaphores, but fewer people seem to know about CountDownLatch and fewer still seem to have heard about Phaser. Those last two have saved me from having to implement my own synchronization code on a number of occasions.

[–] JackbyDev 3 points 2 years ago

Those sound useful. I haven't had to do much cross-thread synchronization thankfully, but I have had to use a BlockingDeque to check that some events came and in the right order. The CountDownLatch and Phaser may have been better.

[–] austin 1 points 1 year ago (1 children)

I had never heard of Phaser, but it looks pretty cool. I just read Baeldung's Guide to Phaser and correct me if I'm wrong, but doesn't it kind of seem like a race condition (it could just be how they use it in the examples)?

class LongRunningAction implements Runnable {
    private String threadName;
    private Phaser ph;

    LongRunningAction(String threadName, Phaser ph) {
        this.threadName = threadName;
        this.ph = ph;
        ph.register();
    }

    @Override
    public void run() {
        ph.arriveAndAwaitAdvance();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ph.arriveAndDeregister();
    }
}

then

executorService.submit(new LongRunningAction("thread-1", ph));
executorService.submit(new LongRunningAction("thread-2", ph));
executorService.submit(new LongRunningAction("thread-3", ph));

if ph.arriveAndAwaitAdvance(); is called before all of the LongRunningActions are initialized, won't it proceed before it is supposed to?

[–] [email protected] 2 points 1 year ago

Your analysis looks right to me. If this were mine I'd initialize all three before submitting any.