zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.codingapi.tx.datasource.relational;
 
import com.codingapi.tx.framework.thread.HookRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.sql.SQLException;
 
/**
 * create by lorne on 2017/12/1
 */
public abstract class AbstractTransactionThread {
 
    private volatile boolean hasStartTransaction = false;
 
    private Logger logger = LoggerFactory.getLogger(AbstractTransactionThread.class);
 
    protected void startRunnable(){
        if(hasStartTransaction){
            logger.debug("start connection is wait ! ");
            return;
        }
        hasStartTransaction = true;
        Runnable runnable = new HookRunnable() {
            @Override
            public void run0() {
                try {
                    transaction();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    try {
                        rollbackConnection();
                    } catch (SQLException e1) {
                        logger.error(e1.getMessage());
                    }
                } finally {
                    try {
                        closeConnection();
                    } catch (SQLException e) {
                        logger.error(e.getMessage());
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
 
 
    protected abstract void transaction() throws SQLException;
 
    protected abstract void closeConnection() throws SQLException;
 
    protected abstract void rollbackConnection() throws SQLException;
}