Video about Java 21 LTS

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,300
Some sample Java 21 codes that test on large number of virtual threads
Java:
import java.util.*;
import java.util.concurrent.locks.*;

void main() throws Throwable {
  final int MAX = 10_000_000;
  final List<Thread> t = new ArrayList<>();
  ReentrantLock lock = new ReentrantLock();
  lock.lock();

  long start = System.currentTimeMillis();
  for (int i = 0; i < MAX; i++) {
    final int ii = i;
    t.add(Thread.ofVirtual().unstarted(() -> {
      lock.lock();
    }));
  }
  for (int i = 0; i < t.size(); i++) {
    t.get(i).start();
  }
  long stop = System.currentTimeMillis();
  System.out.printf("took %d ms\n", stop - start);
  for (int i = 0; i < t.size(); i++) {
    t.get(i).join();
  }
}
Code:
$ java -Xmx32g --enable-preview --source 21 Multi.java
Note: Multi.java uses preview features of Java SE 21.
Note: Recompile with -Xlint:preview for details.
took 11448 ms

OgDc5do.png

B7Hxm33.png


Nice. I have 10 million threads started that took 11s from creation to started, and occupy only 12GBs
:)
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,300
Here is another set of codes that test on using semaphore to constraint concurrency with 1M virtual threads
Java:
import java.util.concurrent.*;

void main() throws Throwable {
  final int MAX         = 100_000;
  final int CONCURRENCY = 1;

  final Semaphore avail      = new Semaphore(CONCURRENCY, true);
  final CountDownLatch latch = new CountDownLatch(MAX);

  for (int i = 0; i < MAX; i++) {
    final int ii = i;
    Thread.startVirtualThread(() -> {
      try {
        avail.acquire();
        System.out.printf("THREAD %d WORKING. %d IN QUEUE\n", ii, avail.getQueueLength());
        avail.release();
        latch.countDown();
      }
      catch (Throwable t) {}
    });
  }

  latch.await();
}

You don't need to use any thread pooling since virtual threads are super lightweight.
You just need to use semaphore to control concurrency and/or reentrantlock for critical sections.

kZB5Zza.png


You should also test out on Generational ZGC.

With virtual threads, it means you get to write synchronous codes which are easier to reason and let the JVM does the context switching for you.
Since it is a LTS release, that means you get a longer support term, depending on which distributor you are using.
:)
 
Last edited:
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top