1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.util.concurrent;
20
21 import java.util.Objects;
22
23 import org.apache.logging.log4j.LogManager;
24 import org.apache.logging.log4j.Logger;
25 import org.mycore.common.MCRSession;
26 import org.mycore.common.MCRSessionMgr;
27 import org.mycore.common.MCRTransactionHelper;
28
29
30
31
32
33
34 public class MCRTransactionableRunnable implements Runnable, MCRDecorator<Runnable> {
35
36 private static final Logger LOGGER = LogManager.getLogger();
37
38 protected Runnable runnable;
39
40 private MCRSession session;
41
42
43
44
45
46
47
48
49
50
51
52
53 public MCRTransactionableRunnable(Runnable runnable) {
54 this.runnable = Objects.requireNonNull(runnable, "runnable must not be null");
55 }
56
57
58
59
60
61
62
63
64
65
66 public MCRTransactionableRunnable(Runnable runnable, MCRSession session) {
67 this.runnable = Objects.requireNonNull(runnable, "runnable must not be null");
68 this.session = Objects.requireNonNull(session, "session must not be null");
69 }
70
71 @Override
72 public void run() {
73 boolean newSession = this.session == null;
74 MCRSessionMgr.unlock();
75 boolean closeSession = newSession && !MCRSessionMgr.hasCurrentSession();
76 if (newSession) {
77 this.session = MCRSessionMgr.getCurrentSession();
78 }
79 MCRSessionMgr.setCurrentSession(this.session);
80 MCRTransactionHelper.beginTransaction();
81 try {
82 this.runnable.run();
83 } finally {
84 try {
85 MCRTransactionHelper.commitTransaction();
86 } catch (Exception commitExc) {
87 LOGGER.error("Error while commiting transaction.", commitExc);
88 try {
89 MCRTransactionHelper.rollbackTransaction();
90 } catch (Exception rollbackExc) {
91 LOGGER.error("Error while rollbacking transaction.", commitExc);
92 }
93 } finally {
94 MCRSessionMgr.releaseCurrentSession();
95 if (closeSession && session != null) {
96 session.close();
97 }
98 }
99 }
100 }
101
102 @Override
103 public Runnable get() {
104 return this.runnable;
105 }
106
107 }