标签: java.util.concurrent

停放 JAVA 线程是否会导致任何获取的监视器被释放

当通过停放线程来暂停线程执行时,是否会导致线程放弃任何获取的对象监视器的所有权?

简而言之,如果一个线程 (t1) 获取“this”对象的监视器并被停放,而另一个线程 (t2) 通过首先尝试获取“this”的监视器并阻塞来尝试取消停放 t1,则以下代码是否会死锁。

// Thread t1 executes this code first.
syncronized(this) {
    LockSupport.park();
}

// Thread t2 then executes this piece of code.
synchronized(this) {
    LockSupport.unpark(t1);
}
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading deadlock java.util.concurrent

5
推荐指数
1
解决办法
340
查看次数

当 Spring @Async 线程从未完成时会发生什么?

如果你有一个 @Async 方法,它返回一个CompletableFuture.... 并且 future永远不会完成,spring 是否会泄漏线程?是的,我知道任何等待结果的人都可能超时并假设后期阶段异常完成......但这不会停止线程。即使你调用cancel,它也不会影响正在运行的线程:

来自文档:

@param mayInterruptIfRunning 该值在此实现中无效,因为中断不用于控制处理。

如果我使用 Future 而不是 CompletableFuture,cancel将会中断线程。不幸的是,Future 上没有相当于 CompletableFuture 上的“allOf”来等待所有任务,如下所示:

// wait for all the futures to finish, regardless of results
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
   // if exceptions happened in any future, swallow them
   // I don't care because I'm going to process each future in my list anyway
   // we just wanted to wait for all the futures to finish
   .exceptionally(ex -> null); 
Run Code Online (Sandbox Code Playgroud)
  1. 我们应该如何取消我们放弃的线程?
  2. 如果我没有取消它(以某种方式),我的池会永远处于线程状态吗???

multithreading java.util.concurrent spring-boot spring-async java-11

5
推荐指数
0
解决办法
888
查看次数

为什么增加newFixedThreadPool导致性能不佳?

我正在尝试更改报告的执行并将其以并发方式完成.在'serail模式'中,执行测试需要30秒,当使用并发模式时,我得到27秒(考虑到连续几步必须采取结果).

我仍然没有得到的是这一行:

ExecutorService executor = Executors.newFixedThreadPool(4);
Run Code Online (Sandbox Code Playgroud)

我的计算机装有2x2.6 Ghz四核,如果newFixedThreadPool为高(16),我希望执行时间会减少.实际上,我增加newFixedThreadPool越多,执行速度越慢.这引出了一个问题:我做错了什么或者我没理解什么?!?!

我从我的执行中嵌入了2个结果截图.

A. newSingleThreadExecuter - 在23秒内运行

B. newFixedThreadPool(4) - 在43秒内运行.

每次我提交一个'Worker'我得到system.out currentTimeMillis和'fatched tkt'结果是从db获取数据所需的毫秒数.(在策略A中 - 它需要约3毫秒,而在B中最多需要7毫秒).

    Stopper stopper = new Stopper();
    for (Long iNum : multimap.asMap().keySet())
    {
        List<Long> tickets = (List<Long>) multimap.get(iNum);
        for (Long ticketNumber : tickets)
        {
                pojoPks = getPkData(iNum);
                Callable<PojoTicket> worker = new MaxCommThread(ticketNumber, pojoPks);
                Future<PojoTicket> submit = executor.submit(worker);
                futures.add(submit);
        }
    }

    System.out.println("futurues: " +futures.size());
    for (Future<PojoTicket> future : futures)
    {
        try
        {
            PojoTicket pojoTicket = future.get();
            //do the rest here

        } …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading callable java.util.concurrent

4
推荐指数
1
解决办法
616
查看次数

是否适合使用AtomicReference.compareAndSet来设置对数据库调用结果的引用?

我正在实现一个简单的缓存,缓存存储为AtomicReference.

private AtomicReference<Map<String, String>> cacheData;
Run Code Online (Sandbox Code Playgroud)

应该从数据库表中填充(延迟)缓存对象.

我提供了一种方法来将缓存数据返回给调用者,但如果数据为空(即未加载),则代码需要从数据库加载数据.为避免同步我想到使用compareAndSet()方法:

public Object getCacheData() {
  cacheData.compareAndSet(null, getDataFromDatabase()); // atomic reload only if data not set!
  return Collections.unmodifiableMap(cacheData.get());
}
Run Code Online (Sandbox Code Playgroud)

以这种方式使用compareAndSet是否可以.将数据库调用作为原子动作的一部分?是否比同步方法更好/更差?

非常感谢任何建议..

java java.util.concurrent compare-and-swap

4
推荐指数
1
解决办法
4340
查看次数

AtomicBoolean.set(flag)和AtomicBoolean.compareAndSet(!flag,flag)有什么区别?

我想知道在调用之间是否存在任何差异(或可能的副作用):

AtomicBoolean.set(true)
Run Code Online (Sandbox Code Playgroud)

AtomicBoolean.compareAndset(false, true)
Run Code Online (Sandbox Code Playgroud)

JavaDoc AtomicBoolean#set状态:

无条件地设置为给定值.

虽然AtomicBoolean#compareAndSet状态:

如果当前值==期望值,则以原子方式将值设置为给定的更新值.

在这两种情况下,该值都将设置为true.那么区别是什么呢?

java java.util.concurrent compare-and-swap

4
推荐指数
2
解决办法
4323
查看次数

使用内在锁进入块

我没有看到以下代码如何产生看似违反对象锁定义的输出.当然只允许一个线程打印"获取锁定"消息,但他们都这样做?

class InterruptThreadGroup {
    public static void main(String[] args) {
        Object lock = new Object();
        MyThread mt1 = new MyThread(lock);
        MyThread mt2 = new MyThread(lock);
        mt1.setName("A");
        mt1.start();
        mt2.setName("B");
        mt2.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        // Thread.currentThread().getThreadGroup().interrupt();
    }
}

class MyThread extends Thread {
    private Object lock;

    public MyThread(Object l) {
        this.lock = l;

    }

    public void run() {
        synchronized (lock) {
            System.out.println(getName() + " acquired lock");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                System.out.println(getName() + …
Run Code Online (Sandbox Code Playgroud)

java locking java.util.concurrent

4
推荐指数
1
解决办法
104
查看次数

ForkJoinPool重置线程中断状态

我刚刚在取消ForkJoinPool返回的Future时注意到以下现象.给出以下示例代码:

ForkJoinPool pool = new ForkJoinPool();
Future<?> fut = pool.submit(new Callable<Void>() {

  @Override
  public Void call() throws Exception {
    while (true) {
      if (Thread.currentThread().isInterrupted()) { // <-- never true
        System.out.println("interrupted");
        throw new InterruptedException();
      }
    }
  }
});

Thread.sleep(1000);
System.out.println("cancel");
fut.cancel(true);
Run Code Online (Sandbox Code Playgroud)

该程序永远不会打印interrupted.ForkJoinTask#cancel(boolean)的文档说:

mayInterruptIfRunning - 此值在默认实现中无效,因为中断不用于控制取消.

如果ForkJoinTasks忽略了中断,你应该如何检查提交给ForkJoinPool的Callables中的取消?

java multithreading java.util.concurrent forkjoinpool

4
推荐指数
1
解决办法
884
查看次数

Java中有多少种类型的内存屏障?

例如,在标准C11C++ 11中,有6种类型的内存屏障:http://en.cppreference.com/w/cpp/atomic/memory_order

  • memory_order_relaxed
  • memory_order_consume
  • memory_order_acquire
  • memory_order_release
  • memory_order_acq_rel
  • memory_order_seq_cst

哪些是确定编译器可以重新排序指令的方向,以及哪些处理器指令需要插入以限制处理器的流水线中的重新排序.例如,前五个障碍仅影响编译器,但不生成任何CPU指令(否S/L/ MFENCE),因为在x86中 - 自动提供acquire-release-semantics.

Java中有多少种类型的内存屏障?或者只有两种类型?

  • 允许所有重新排序
  • 禁止所有重新排序

java concurrency multithreading java.util.concurrent

4
推荐指数
1
解决办法
338
查看次数

CompletableFuture没有得到执行。如果我使用ExecutorService池,则其工作正常,但不使用默认的forkJoin公共池

我试图运行以下类,使其终止而不执行CompletableFuture。

public class ThenApplyExample {

public static void main(String[] args) throws Exception {
    //ExecutorService es = Executors.newCachedThreadPool();
    CompletableFuture<Student> studentCompletableFuture = CompletableFuture.supplyAsync(() -> {

        try {

            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 3;
    })// If I put executorservice created n commented above, programme work as expected.
            .thenApply(i -> {

                for (int j = 0; j <= i; j++) {
                    System.out.println("Inside first then apply");
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("First then apply is …
Run Code Online (Sandbox Code Playgroud)

java multithreading java.util.concurrent concurrent.futures completable-future

4
推荐指数
1
解决办法
783
查看次数

多次在CompletableFuture中运行Runnable

我想执行多个线程,它们会尝试同时添加到我的自定义列表中MyList,但是当我尝试计数时,我看不到任何输出

    public static void main(String[] args) {

        MyList<String> list = new list<String>();

        MyRunner<String> myRunner = new MyRunner<String>(list);

        ExecutorService threadPool = Executors.newFixedThreadPool(4);

        for(int i = 0; i < 20; i++) {
            CompletableFuture.runAsync(new MyRunner<String>(list));
        }

        try {
            threadPool.awaitTermination(100l, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.getCount());
}
Run Code Online (Sandbox Code Playgroud)

跑步者班:

class MyRunner<String> implements Runnable {

    MyList<String> list;

    public MyRunner(MyList <String> t) {
        this.list = t;
    }

    @Override
    public void run() {
        for(int i = 0; i < 200; i++) {
            list((String) …
Run Code Online (Sandbox Code Playgroud)

java concurrency java.util.concurrent java-8

4
推荐指数
1
解决办法
234
查看次数