Search code examples
javamultithreadingthread-safetythreadpool

Java multi-threading cause database deadlock (Java 7)


I want to design a multi-threading module, I set two class and design like:

ThreadConcurrentWoker.class:

public class ThreadConcurrentWoker<E, R> extends ThreadConcurrent<E, R> {

public ThreadConcurrentWoker(List<E> traget, CallableModel<E, R> callable) {
    super.targetList = traget; // a list want to doing in thread.
    super.callable = callable; // Custom callable object
    super.results = new Vector<R>(); // get result in to this list
}

// this is doing Thread method
@Override
public List<R> concurrentExcute() throws Exception {

    ExecutorService executor = Executors.newFixedThreadPool(super.targetList.size());
    CompletionService<R> completionService = new ExecutorCompletionService<R>(executor);
    for (final E elememt : super.targetList) {
        completionService.submit(new Callable<R>() {
            @Override
            public R call() throws Exception {
                callable.setElement(elememt);
                return callable.call();
            }
        });
    }

    int finishs = 0;
    boolean errors = false;

    while (finishs < super.targetList.size() && !errors) {
        Future<R> resultFuture = completionService.take();
        try {
            super.results.add(resultFuture.get());
        } catch (ExecutionException e) {
            errors = true;
        } finally {
            finishs++;
        }
    }
    return super.results;
}

}

CallableModel.class:

public abstract class CallableModel<E, V> implements Callable<V> {
    private E element;

    public E getElement() {
        return element;
    }

    public void setElement(E element) {
        this.element = element;
    }

}

and I want to use like this:

ThreadConcurrentWoker<FlowPendingCheckedBean, ResultBean> tCUtil = 
new ThreadConcurrentWoker<>(test, new CallableModel<FlowPendingCheckedBean, ResultBean>() {

    @Override
    public ResultBean call() throws Exception {
        // do something in here and return result.
    }

});
try {
    resultBeans = tCUtil.concurrentExcute();
} catch (Exception e1) {
    log.error(e1.getMessage());
}

but when I execute this class, it will get same data in different threads. Resulting in database will appear deadlocks. How can I improve it?


Solution

  • I tried the problem. Write down notes:

    Because the multi-thread use the same CallableModel element, so when first thread in call method, second thread into setEelement to change element, and this time, first thread will get second thread's element.