You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by sb...@apache.org on 2017/09/20 07:59:45 UTC

[1/2] ignite git commit: ignite-6181

Repository: ignite
Updated Branches:
  refs/heads/ignite-6181-2 [created] 685f051ce


http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutTest.java
new file mode 100644
index 0000000..5dcd4b5
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutTest.java
@@ -0,0 +1,626 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.transactions;
+
+import java.util.concurrent.CountDownLatch;
+import javax.cache.CacheException;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.NearCacheConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInternalFuture;
+import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal;
+import org.apache.ignite.internal.util.GridConcurrentSkipListSet;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.X;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteInClosure;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.apache.ignite.transactions.TransactionConcurrency;
+import org.apache.ignite.transactions.TransactionDeadlockException;
+import org.apache.ignite.transactions.TransactionIsolation;
+import org.apache.ignite.transactions.TransactionTimeoutException;
+import org.jsr166.ThreadLocalRandom8;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
+import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
+
+/**
+ * Tests an ability to eagerly rollback timed out transactions.
+ */
+public class TxRollbackOnTimeoutTest extends GridCommonAbstractTest {
+    /** */
+    private static final long TX_MIN_TIMEOUT = 1;
+
+    /** */
+    private static final String CACHE_NAME = "test";
+
+    /** IP finder. */
+    private static final TcpDiscoveryVmIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int GRID_CNT = 3;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        boolean client = "client".equals(igniteInstanceName);
+
+        cfg.setClientMode(client);
+
+        if (!client) {
+            CacheConfiguration ccfg = new CacheConfiguration(CACHE_NAME);
+
+            if (nearCacheEnabled())
+                ccfg.setNearConfiguration(new NearCacheConfiguration());
+
+            ccfg.setAtomicityMode(TRANSACTIONAL);
+            ccfg.setBackups(2);
+            ccfg.setWriteSynchronizationMode(FULL_SYNC);
+
+            cfg.setCacheConfiguration(ccfg);
+        }
+
+        return cfg;
+    }
+
+    /**
+     * @return Near cache flag.
+     */
+    protected boolean nearCacheEnabled() {
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        startGridsMultiThreaded(GRID_CNT);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        stopAllGrids();
+    }
+
+    /**
+     * @throws Exception If f nodeailed.
+     * @return Started client.
+     */
+    private Ignite startClient() throws Exception {
+        Ignite client = startGrid("client");
+
+        assertTrue(client.configuration().isClientMode());
+
+        if (nearCacheEnabled())
+            client.createNearCache(CACHE_NAME, new NearCacheConfiguration<>());
+        else
+            assertNotNull(client.cache(CACHE_NAME));
+
+        return client;
+    }
+
+    /**
+     * @param e Exception.
+     */
+    protected void validateDeadlockException(Exception e) {
+        assertEquals("Deadlock report is expected",
+            TransactionDeadlockException.class, e.getCause().getCause().getClass());
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testLockAndConcurrentTimeout() throws Exception {
+        startClient();
+
+        for (Ignite node : G.allGrids()) {
+            log.info("Test with node: " + node.name());
+
+            lock(node, false);
+
+            lock(node, false);
+
+            lock(node, true);
+        }
+    }
+
+    /**
+     * @param node Node.
+     * @param retry {@code True}
+     * @throws Exception If failed.
+     */
+    private void lock(final Ignite node, final boolean retry) throws Exception {
+        final IgniteCache<Object, Object> cache = node.cache(CACHE_NAME);
+
+        final int KEYS_PER_THREAD = 10_000;
+
+        GridTestUtils.runMultiThreaded(new IgniteInClosure<Integer>() {
+            @Override public void apply(Integer idx) {
+                int start = idx * KEYS_PER_THREAD;
+                int end = start + KEYS_PER_THREAD;
+
+                int locked = 0;
+
+                try {
+                    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 500, 0)) {
+                        for (int i = start; i < end; i++) {
+                            cache.get(i);
+
+                            locked++;
+                        }
+
+                        tx.commit();
+                    }
+                }
+                catch (Exception e) {
+                    info("Expected error: " + e);
+                }
+
+                info("Done, locked: " + locked);
+
+                if (retry) {
+                    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 10 * 60_000, 0)) {
+                        for (int i = start; i < end; i++) {
+                            cache.get(i);
+
+                            locked++;
+                        }
+
+                        cache.put(start, 0);
+
+                        tx.commit();
+                    }
+                }
+            }
+        }, Runtime.getRuntime().availableProcessors(), "tx-thread");
+    }
+
+    /**
+     * Tests if timeout on first tx unblocks second tx waiting for the locked key.
+     *
+     * @throws Exception If failed.
+     */
+    public void testWaitingTxUnblockedOnTimeout() throws Exception {
+        waitingTxUnblockedOnTimeout(grid(0), grid(0));
+
+        waitingTxUnblockedOnTimeout(grid(0), grid(1));
+
+        Ignite client = startClient();
+
+        waitingTxUnblockedOnTimeout(grid(0), client);
+
+        waitingTxUnblockedOnTimeout(grid(1), client);
+
+        waitingTxUnblockedOnTimeout(client, grid(0));
+
+        waitingTxUnblockedOnTimeout(client, grid(1));
+
+        waitingTxUnblockedOnTimeout(client, client);
+    }
+
+    /**
+     * Tests if timeout on first tx unblocks second tx waiting for the locked key.
+     *
+     * @throws Exception If failed.
+     */
+    public void testWaitingTxUnblockedOnThreadDeath() throws Exception {
+        waitingTxUnblockedOnThreadDeath(grid(0), grid(0));
+
+        waitingTxUnblockedOnThreadDeath(grid(0), grid(1));
+
+        Ignite client = startClient();
+
+        waitingTxUnblockedOnThreadDeath(grid(0), client);
+
+        waitingTxUnblockedOnThreadDeath(grid(1), client);
+
+        waitingTxUnblockedOnThreadDeath(client, grid(0));
+
+        waitingTxUnblockedOnThreadDeath(client, grid(1));
+
+        waitingTxUnblockedOnThreadDeath(client, client);
+    }
+
+    /**
+     * Tests if deadlock is resolved on timeout with correct message.
+     *
+     * @throws Exception If failed.
+     */
+    public void testDeadlockUnblockedOnTimeout() throws Exception {
+        deadlockUnblockedOnTimeout(ignite(0), ignite(1));
+
+        deadlockUnblockedOnTimeout(ignite(0), ignite(0));
+
+        Ignite client = startClient();
+
+        deadlockUnblockedOnTimeout(ignite(0), client);
+
+        deadlockUnblockedOnTimeout(client, ignite(0));
+    }
+
+    /**
+     * Tests if deadlock is resolved on timeout with correct message.
+     *
+     * @param node1 First node.
+     * @param node2 Second node.
+     * @throws Exception If failed.
+     */
+    private void deadlockUnblockedOnTimeout(final Ignite node1, final Ignite node2) throws Exception {
+        info("Start test [node1=" + node1.name() + ", node2=" + node2.name() + ']');
+
+        final CountDownLatch l = new CountDownLatch(2);
+
+        IgniteInternalFuture<?> fut1 = GridTestUtils.runAsync(new Runnable() {
+            @Override public void run() {
+                try {
+                    try (Transaction tx = node1.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 5000, 2)) {
+                        node1.cache(CACHE_NAME).put(1, 10);
+
+                        l.countDown();
+
+                        U.awaitQuiet(l);
+
+                        node1.cache(CACHE_NAME).put(2, 20);
+
+                        tx.commit();
+
+                        fail();
+                    }
+                }
+                catch (CacheException e) {
+                    // No-op.
+                    validateDeadlockException(e);
+                }
+            }
+        }, "First");
+
+        IgniteInternalFuture<?> fut2 = GridTestUtils.runAsync(new Runnable() {
+            @Override public void run() {
+                try (Transaction tx = node2.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 0, 2)) {
+                    node2.cache(CACHE_NAME).put(2, 2);
+
+                    l.countDown();
+
+                    U.awaitQuiet(l);
+
+                    node2.cache(CACHE_NAME).put(1, 1);
+
+                    tx.commit();
+                }
+            }
+        }, "Second");
+
+        fut1.get();
+        fut2.get();
+
+        assertTrue("Expecting committed key 2", node1.cache(CACHE_NAME).get(2) != null);
+        assertTrue("Expecting committed key 1", node1.cache(CACHE_NAME).get(1) != null);
+
+        node1.cache(CACHE_NAME).removeAll(F.asSet(1, 2));
+    }
+
+    /**
+     * Tests timeout object cleanup on tx commit.
+     *
+     * @throws Exception If failed.
+     */
+    public void testTimeoutRemoval() throws Exception {
+        IgniteEx client = (IgniteEx)startClient();
+
+        final long TX_TIMEOUT = 250;
+
+        int modesCnt = 5;
+
+        for (int i = 0; i < modesCnt; i++)
+            testTimeoutRemoval0(grid(0), i, TX_TIMEOUT);
+
+        for (int i = 0; i < modesCnt; i++)
+            testTimeoutRemoval0(client, i, TX_TIMEOUT);
+
+        for (int i = 0; i < modesCnt; i++)
+            testTimeoutRemoval0(grid(0), i, TX_MIN_TIMEOUT);
+
+        for (int i = 0; i < modesCnt; i++)
+            testTimeoutRemoval0(client, i, TX_MIN_TIMEOUT);
+
+        // Repeat with more iterations to make sure everything is cleared.
+        for (int i = 0; i < 500; i++)
+            testTimeoutRemoval0(client, ThreadLocalRandom8.current().nextInt(modesCnt), TX_MIN_TIMEOUT);
+    }
+
+    /**
+     * Tests timeouts in all tx configurations.
+     *
+     * @throws Exception If failed.
+     */
+    public void testSimple() throws Exception {
+        for (TransactionConcurrency concurrency : TransactionConcurrency.values())
+            for (TransactionIsolation isolation : TransactionIsolation.values())
+                testSimple0(concurrency, isolation);
+    }
+
+    /**
+     * @param concurrency Concurrency.
+     * @param isolation Isolation.
+     *
+     * @throws Exception If failed.
+     */
+    private void testSimple0(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception {
+        Ignite near = grid(0);
+
+        final int key = 1, val = 1;
+
+        final long TX_TIMEOUT = 250;
+
+        try (Transaction tx = near.transactions().txStart(concurrency, isolation, TX_TIMEOUT, 1)) {
+            near.cache(CACHE_NAME).put(key, val);
+
+            U.sleep(TX_TIMEOUT * 2);
+
+            try {
+                tx.commit();
+
+                fail("Tx must timeout");
+            }
+            catch (IgniteException e) {
+                assertTrue("Expected timeout exception", X.hasCause(e, TransactionTimeoutException.class));
+            }
+        }
+
+        assertFalse("Must be removed by rollback on timeout", near.cache(CACHE_NAME).containsKey(key));
+    }
+
+    /**
+     * @param near Node.
+     * @param mode Test mode.
+     *
+     * @param timeout Tx timeout.
+     * @throws Exception If failed.
+     */
+    private void testTimeoutRemoval0(IgniteEx near, int mode, long timeout) throws Exception {
+        Throwable saved = null;
+
+        try (Transaction tx = near.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, timeout, 1)) {
+            near.cache(CACHE_NAME).put(1, 1);
+
+            switch (mode) {
+                case 0:
+                    tx.commit();
+                    break;
+
+                case 1:
+                    tx.commitAsync().get();
+                    break;
+
+                case 2:
+                    tx.rollback();
+                    break;
+
+                case 3:
+                    tx.rollbackAsync().get();
+                    break;
+
+                case 4:
+                    break;
+
+                default:
+                    fail();
+            }
+        }
+        catch (Throwable t) {
+            saved = t;
+        }
+
+        GridConcurrentSkipListSet set = U.field(near.context().cache().context().time(), "timeoutObjs");
+
+        for (Object obj : set) {
+            if (obj.getClass().isAssignableFrom(GridNearTxLocal.class)) {
+                log.error("Last saved exception: " + saved, saved);
+
+                fail("Not remove for mode=" + mode + " and timeout=" + timeout);
+            }
+        }
+    }
+
+    /**
+     * @param near Node starting tx which is timed out.
+     * @param other Node starting second tx.
+     * @throws Exception If failed.
+     */
+    private void waitingTxUnblockedOnTimeout(final Ignite near, final Ignite other) throws Exception {
+        waitingTxUnblockedOnTimeout(near, other, 1000);
+
+        waitingTxUnblockedOnTimeout(near, other, 50);
+    }
+
+    /**
+     * @param near Node starting tx which is timed out.
+     * @param other Node starting second tx.
+     * @param timeout Timeout.
+     * @throws Exception If failed.
+     */
+    private void waitingTxUnblockedOnTimeout(final Ignite near, final Ignite other, final long timeout) throws Exception {
+        info("Start test [node1=" + near.name() + ", node2=" + other.name() + ']');
+
+        final CountDownLatch blocked = new CountDownLatch(1);
+
+        final CountDownLatch unblocked = new CountDownLatch(1);
+
+        final int recordsCnt = 5;
+
+        IgniteInternalFuture<?> fut1 = GridTestUtils.runAsync(new Runnable() {
+            @Override public void run() {
+                try (Transaction tx = near.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, timeout, 0)) {
+                    try {
+                        for (int i = 0; i < recordsCnt; i++)
+                            near.cache(CACHE_NAME).put(i, i);
+
+                        info("Locked all keys.");
+                    }
+                    catch (CacheException e) {
+                        info("Failed to lock keys: " + e);
+                    }
+                    finally {
+                        blocked.countDown();
+                    }
+
+                    // Will be unblocked after tx timeout occurs.
+                    U.awaitQuiet(unblocked);
+
+                    try {
+                        near.cache(CACHE_NAME).put(0, 0);
+
+                        fail();
+                    }
+                    catch (CacheException e) {
+                        log.info("Expecting error: " + e.getMessage());
+                    }
+
+                    try {
+                        tx.commit();
+
+                        fail();
+                    }
+                    catch (IgniteException e) {
+                        log.info("Expecting error: " + e.getMessage());
+                    }
+                }
+
+                // Check thread is able to start new tx.
+                try (Transaction tx = near.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 60_000, 0)) {
+                    for (int i = 0; i < recordsCnt; i++)
+                        near.cache(CACHE_NAME).put(i, i);
+
+                    tx.commit();
+                }
+            }
+        }, "First");
+
+        IgniteInternalFuture<?> fut2 = GridTestUtils.runAsync(new Runnable() {
+            @Override public void run() {
+                U.awaitQuiet(blocked);
+
+                try (Transaction tx = other.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 0, 1)) {
+                    for (int i = 0; i < recordsCnt; i++)
+                        other.cache(CACHE_NAME).put(i, i);
+
+                    // Will wait until timeout on first tx will unblock put.
+                    tx.commit();
+                }
+            }
+        }, "Second");
+
+        fut2.get();
+
+        unblocked.countDown();
+
+        fut1.get();
+    }
+
+    /**
+     * @param near Node starting tx which is timed out.
+     * @param other Node starting second tx.
+     * @throws Exception If failed.
+     */
+    private void waitingTxUnblockedOnThreadDeath(final Ignite near, final Ignite other) throws Exception {
+        waitingTxUnblockedOnThreadDeath0(near, other, 10, 1000); // Try provoke timeout after all keys are locked.
+
+        waitingTxUnblockedOnThreadDeath0(near, other, 1000, 100);  // Try provoke timeout while trying to lock keys.
+    }
+
+    /**
+     * @param near Node starting tx which is timed out.
+     * @param other Node starting second tx.
+     * @param recordsCnt Number of records to locks.
+     * @param timeout Transaction timeout.
+     * @throws Exception If failed.
+     */
+    private void waitingTxUnblockedOnThreadDeath0(final Ignite near,
+        final Ignite other,
+        final int recordsCnt,
+        final long timeout)
+        throws Exception
+    {
+        info("Start test [node1=" + near.name() + ", node2=" + other.name() + ']');
+
+        final CountDownLatch blocked = new CountDownLatch(1);
+
+        IgniteInternalFuture<?> fut1 = multithreadedAsync(new Runnable() {
+            @Override public void run() {
+                near.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, timeout, recordsCnt);
+
+                try {
+                    for (int i = 0; i < recordsCnt; i++)
+                        near.cache(CACHE_NAME).put(i, i);
+
+                    log.info("Locked all records.");
+                }
+                catch (Exception e) {
+                    log.info("Failed to locked all records: " + e);
+                }
+                finally {
+                    blocked.countDown();
+                }
+
+                throw new IgniteException("Failure");
+            }
+        }, 1, "First");
+
+        IgniteInternalFuture<?> fut2 = multithreadedAsync(new Runnable() {
+            @Override public void run() {
+                U.awaitQuiet(blocked);
+
+                try (Transaction tx = other.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 0, recordsCnt)) {
+                    for (int i = 0; i < recordsCnt; i++)
+                        other.cache(CACHE_NAME).put(i, i);
+
+                    // Will wait until timeout on first tx will unblock put.
+                    tx.commit();
+                }
+            }
+        }, 1, "Second");
+
+        try {
+            fut1.get();
+
+            fail();
+        }
+        catch (IgniteCheckedException e) {
+            // No-op.
+        }
+
+        fut2.get();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
index e8810bb..0df600c 100755
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
@@ -124,6 +124,7 @@ import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheConnec
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheMessageRecoveryIdleConnectionTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheMessageWriteTimeoutTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheSystemTransactionsSelfTest;
+import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheThreadLocalTxTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheTxMessageRecoveryTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCrossCacheTxStoreSelfTest;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridCacheAtomicNearCacheSelfTest;
@@ -135,6 +136,9 @@ import org.apache.ignite.internal.processors.cache.distributed.replicated.GridCa
 import org.apache.ignite.internal.processors.cache.local.GridCacheLocalTxExceptionSelfTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.CacheEntryProcessorExternalizableFailedTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.CacheEntryProcessorNonSerializableTest;
+import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutNearCacheTest;
+import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutNoDeadlockDetectionTest;
+import org.apache.ignite.internal.processors.cache.transactions.TxRollbackOnTimeoutTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessorSelfTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerImplSelfTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerMultiThreadedSelfTest;
@@ -317,6 +321,11 @@ public class IgniteCacheTestSuite extends TestSuite {
 
         suite.addTestSuite(GridStoreLoadCacheTest.class);
 
+        suite.addTestSuite(TxRollbackOnTimeoutTest.class);
+        suite.addTestSuite(TxRollbackOnTimeoutNearCacheTest.class);
+        suite.addTestSuite(TxRollbackOnTimeoutNoDeadlockDetectionTest.class);
+        suite.addTestSuite(IgniteCacheThreadLocalTxTest.class);
+
         return suite;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/HadoopTxConfigCacheTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/HadoopTxConfigCacheTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/HadoopTxConfigCacheTest.java
index e85baed..f404732 100644
--- a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/HadoopTxConfigCacheTest.java
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/HadoopTxConfigCacheTest.java
@@ -25,11 +25,11 @@ import org.apache.ignite.internal.util.typedef.internal.CU;
 /**
  * Test checks whether hadoop system cache doesn't use user defined TX config.
  */
-public class HadoopTxConfigCacheTest  extends IgniteTxConfigCacheSelfTest {
+public class HadoopTxConfigCacheTest extends IgniteTxConfigCacheSelfTest {
     /**
      * Success if system caches weren't timed out.
      *
-     * @throws Exception
+     * @throws Exception If failed.
      */
     public void testSystemCacheTx() throws Exception {
         final Ignite ignite = grid(0);


[2/2] ignite git commit: ignite-6181

Posted by sb...@apache.org.
ignite-6181


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/685f051c
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/685f051c
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/685f051c

Branch: refs/heads/ignite-6181-2
Commit: 685f051cee48c4e875e2ec8fef211da4da251423
Parents: 2299589
Author: sboikov <sb...@gridgain.com>
Authored: Wed Sep 20 10:58:24 2017 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Sep 20 10:59:02 2017 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/cache/CacheMetrics.java   |   2 +
 .../IgniteDiagnosticPrepareContext.java         |   4 +-
 .../processors/cache/CacheMetricsImpl.java      |   4 +-
 .../processors/cache/GridCacheAdapter.java      |  18 +-
 .../processors/cache/GridCacheMapEntry.java     |   9 +-
 .../cache/GridCacheSharedContext.java           |  11 +-
 .../dht/colocated/GridDhtColocatedCache.java    |   4 +-
 .../colocated/GridDhtColocatedLockFuture.java   |  58 +-
 .../distributed/near/GridNearLockFuture.java    |  58 +-
 .../near/GridNearOptimisticTxPrepareFuture.java |   3 +-
 ...ridNearOptimisticTxPrepareFutureAdapter.java |   2 +-
 .../near/GridNearTransactionalCache.java        |   2 +-
 .../cache/distributed/near/GridNearTxLocal.java | 105 +++-
 .../cache/transactions/IgniteInternalTx.java    |   2 +-
 .../cache/transactions/IgniteTxAdapter.java     |   8 +-
 .../cache/transactions/IgniteTxHandler.java     |   4 +-
 .../cache/transactions/IgniteTxManager.java     | 232 +++----
 .../timeout/GridTimeoutProcessor.java           |  17 +-
 .../cache/IgniteTxConfigCacheSelfTest.java      |  14 +
 .../IgniteCacheSystemTransactionsSelfTest.java  |   4 +-
 .../IgniteCacheThreadLocalTxTest.java           | 225 +++++++
 .../IgniteOptimisticTxSuspendResumeTest.java    |   6 +-
 .../TxRollbackOnTimeoutNearCacheTest.java       |  28 +
 ...ollbackOnTimeoutNoDeadlockDetectionTest.java |  47 ++
 .../transactions/TxRollbackOnTimeoutTest.java   | 626 +++++++++++++++++++
 .../ignite/testsuites/IgniteCacheTestSuite.java |   9 +
 .../hadoop/impl/HadoopTxConfigCacheTest.java    |   4 +-
 27 files changed, 1249 insertions(+), 257 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/cache/CacheMetrics.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/cache/CacheMetrics.java b/modules/core/src/main/java/org/apache/ignite/cache/CacheMetrics.java
index 20ea692..470645b 100644
--- a/modules/core/src/main/java/org/apache/ignite/cache/CacheMetrics.java
+++ b/modules/core/src/main/java/org/apache/ignite/cache/CacheMetrics.java
@@ -269,6 +269,7 @@ public interface CacheMetrics {
      *
      * @return Thread map size.
      */
+    @Deprecated
     public int getTxThreadMapSize();
 
     /**
@@ -318,6 +319,7 @@ public interface CacheMetrics {
      *
      * @return DHT thread map size.
      */
+    @Deprecated
     public int getTxDhtThreadMapSize();
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/IgniteDiagnosticPrepareContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteDiagnosticPrepareContext.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteDiagnosticPrepareContext.java
index 378dc74..ed8d35e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteDiagnosticPrepareContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteDiagnosticPrepareContext.java
@@ -75,7 +75,7 @@ public class IgniteDiagnosticPrepareContext {
      * @param keys Entry keys.
      * @param msg Initial message.
      */
-    public void  txKeyInfo(UUID nodeId, int cacheId, Collection<KeyCacheObject> keys, String msg) {
+    public void txKeyInfo(UUID nodeId, int cacheId, Collection<KeyCacheObject> keys, String msg) {
         closure(nodeId).add(msg, new TxEntriesInfoClosure(cacheId, keys));
     }
 
@@ -280,4 +280,4 @@ public class IgniteDiagnosticPrepareContext {
             }
         }
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheMetricsImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheMetricsImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheMetricsImpl.java
index d03a6f8..d608435 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheMetricsImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheMetricsImpl.java
@@ -298,7 +298,7 @@ public class CacheMetricsImpl implements CacheMetrics {
 
     /** {@inheritDoc} */
     @Override public int getTxThreadMapSize() {
-        return cctx.tm().threadMapSize();
+        return 0;
     }
 
     /** {@inheritDoc} */
@@ -328,7 +328,7 @@ public class CacheMetricsImpl implements CacheMetrics {
 
     /** {@inheritDoc} */
     @Override public int getTxDhtThreadMapSize() {
-        return cctx.isNear() && dhtCtx != null ? dhtCtx.tm().threadMapSize() : -1;
+        return 0;
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 92a8245..13813ed 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -1857,7 +1857,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                 return new GridFinishedFuture<>(e);
             }
 
-            tx = ctx.tm().threadLocalTx(ctx.systemTx() ? ctx : null);
+            tx = ctx.tm().currentThreadTx(ctx);
         }
 
         if (tx == null || tx.implicit()) {
@@ -3236,7 +3236,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
     /** {@inheritDoc} */
     @Nullable @Override public GridNearTxLocal tx() {
-        return ctx.tm().threadLocalTx(ctx);
+        return ctx.tm().currentThreadTx(ctx);
     }
 
     /** {@inheritDoc} */
@@ -3962,6 +3962,8 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
      */
     @SuppressWarnings("unchecked")
     IgniteInternalFuture<IgniteInternalTx> commitTxAsync(final GridNearTxLocal tx) {
+        ctx.tm().clearThreadLocalTx(tx);
+
         FutureHolder holder = lastFut.get();
 
         holder.lock();
@@ -3973,7 +3975,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                 IgniteInternalFuture<IgniteInternalTx> f = new GridEmbeddedFuture<>(fut,
                     new C2<Object, Exception, IgniteInternalFuture<IgniteInternalTx>>() {
                         @Override public IgniteInternalFuture<IgniteInternalTx> apply(Object o, Exception e) {
-                            return tx.commitNearTxLocalAsync();
+                            return tx.commitNearTxLocalAsync(false);
                         }
                     });
 
@@ -3982,7 +3984,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                 return f;
             }
 
-            IgniteInternalFuture<IgniteInternalTx> f = tx.commitNearTxLocalAsync();
+            IgniteInternalFuture<IgniteInternalTx> f = tx.commitNearTxLocalAsync(false);
 
             saveFuture(holder, f, /*retry*/false);
 
@@ -4027,7 +4029,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
 
         awaitLastFut();
 
-        GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
+        GridNearTxLocal tx = ctx.tm().currentThreadTx(ctx);
 
         if (tx == null || tx.implicit()) {
             TransactionConfiguration tCfg = CU.transactionConfiguration(ctx, ctx.kernalContext().config());
@@ -4123,7 +4125,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
         if (log.isDebugEnabled())
             log.debug("Performing async op: " + op);
 
-        GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
+        GridNearTxLocal tx = ctx.tm().currentThreadTx(ctx);
 
         CacheOperationContext opCtx = ctx.operationContextPerCall();
 
@@ -4207,7 +4209,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                                         }
                                         catch (IgniteCheckedException e1) {
                                             try {
-                                                tx0.rollbackNearTxLocalAsync();
+                                                tx0.rollbackNearTxLocalAsync(false);
                                             }
                                             catch (Throwable e2) {
                                                 e1.addSuppressed(e2);
@@ -4246,7 +4248,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
                         }
                         catch (IgniteCheckedException e1) {
                             try {
-                                tx0.rollbackNearTxLocalAsync();
+                                tx0.rollbackNearTxLocalAsync(false);
                             }
                             catch (Throwable e2) {
                                 e1.addSuppressed(e2);

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
index 958f156..7b60b9c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java
@@ -2463,7 +2463,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
     /** {@inheritDoc} */
     @Nullable @Override public CacheObject peek(@Nullable IgniteCacheExpiryPolicy plc)
         throws GridCacheEntryRemovedException, IgniteCheckedException {
-        IgniteInternalTx tx = cctx.tm().localTxx();
+        IgniteInternalTx tx = cctx.tm().localTx();
 
         AffinityTopologyVersion topVer = tx != null ? tx.topologyVersion() : cctx.affinity().affinityTopologyVersion();
 
@@ -3110,10 +3110,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
      * @return Current transaction.
      */
     private IgniteTxLocalAdapter currentTx() {
-        if (cctx.isDht())
-            return cctx.dht().near().context().tm().localTx();
-        else
-            return cctx.tm().localTx();
+        return cctx.tm().localTx();
     }
 
     /** {@inheritDoc} */
@@ -3491,7 +3488,7 @@ public abstract class GridCacheMapEntry extends GridMetadataAwareAdapter impleme
             }
         }
 
-        IgniteInternalTx tx = cctx.tm().localTxx();
+        IgniteInternalTx tx = cctx.tm().localTx();
 
         if (tx != null) {
             IgniteTxEntry e = tx.entry(txKey());

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
index d8614b5..a6cb8a4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
@@ -906,12 +906,13 @@ public class GridCacheSharedContext<K, V> {
      * @return Not null topology version if current thread holds lock preventing topology change.
      */
     @Nullable public AffinityTopologyVersion lockedTopologyVersion(IgniteInternalTx ignore) {
-        long threadId = Thread.currentThread().getId();
+        AffinityTopologyVersion topVer = txMgr.lockedTopologyVersion(ignore);
 
-        AffinityTopologyVersion topVer = txMgr.lockedTopologyVersion(threadId, ignore);
+        if (topVer == null) {
+            long threadId = Thread.currentThread().getId();
 
-        if (topVer == null)
             topVer = mvccMgr.lastExplicitLockTopologyVersion(threadId);
+        }
 
         return topVer;
     }
@@ -946,7 +947,7 @@ public class GridCacheSharedContext<K, V> {
         if (ctx == null) {
             tx.txState().awaitLastFuture(this);
 
-            return tx.commitNearTxLocalAsync();
+            return tx.commitNearTxLocalAsync(true);
         }
         else
             return ctx.cache().commitTxAsync(tx);
@@ -960,7 +961,7 @@ public class GridCacheSharedContext<K, V> {
     public IgniteInternalFuture rollbackTxAsync(GridNearTxLocal tx) throws IgniteCheckedException {
         tx.txState().awaitLastFuture(this);
 
-        return tx.rollbackNearTxLocalAsync();
+        return tx.rollbackNearTxLocalAsync(true);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
index 8449f3a..f98c1d7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
@@ -186,7 +186,7 @@ public class GridDhtColocatedCache<K, V> extends GridDhtTransactionalCacheAdapte
         if (keyCheck)
             validateCacheKey(key);
 
-        GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
+        GridNearTxLocal tx = ctx.tm().currentThreadTx(ctx);
 
         final CacheOperationContext opCtx = ctx.operationContextPerCall();
 
@@ -273,7 +273,7 @@ public class GridDhtColocatedCache<K, V> extends GridDhtTransactionalCacheAdapte
         if (keyCheck)
             validateCacheKeys(keys);
 
-        GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
+        GridNearTxLocal tx = ctx.tm().currentThreadTx(ctx);
 
         final CacheOperationContext opCtx = ctx.operationContextPerCall();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
index 58c6319..eb7d2c3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
@@ -54,6 +54,7 @@ import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLock
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockRequest;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal;
+import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
 import org.apache.ignite.internal.processors.cache.transactions.TxDeadlock;
@@ -226,12 +227,6 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
             log = U.logger(cctx.kernalContext(), logRef, GridDhtColocatedLockFuture.class);
         }
 
-        if (timeout > 0) {
-            timeoutObj = new LockTimeoutObject();
-
-            cctx.time().addTimeoutObject(timeoutObj);
-        }
-
         valMap = new ConcurrentHashMap8<>();
     }
 
@@ -399,7 +394,7 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
      * @param success Success flag.
      */
     public void complete(boolean success) {
-        onComplete(success, true);
+        onComplete(success, true, true);
     }
 
     /**
@@ -533,7 +528,7 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
     /** {@inheritDoc} */
     @Override public boolean cancel() {
         if (onCancelled())
-            onComplete(false, true);
+            onComplete(false, true, true);
 
         return isCancelled();
     }
@@ -556,7 +551,7 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
         if (err != null)
             success = false;
 
-        return onComplete(success, true);
+        return onComplete(success, true, true);
     }
 
     /**
@@ -564,9 +559,10 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
      *
      * @param success {@code True} if lock was acquired.
      * @param distribute {@code True} if need to distribute lock removal in case of failure.
+     * @param restoreTimeout {@code True} if need restore tx timeout callback.
      * @return {@code True} if complete by this operation.
      */
-    private boolean onComplete(boolean success, boolean distribute) {
+    private boolean onComplete(boolean success, boolean distribute, boolean restoreTimeout) {
         if (log.isDebugEnabled())
             log.debug("Received onComplete(..) callback [success=" + success + ", distribute=" + distribute +
                 ", fut=" + this + ']');
@@ -577,6 +573,12 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
         if (tx != null)
             cctx.tm().txContext(tx);
 
+        if (restoreTimeout && tx != null && tx.trackTimeout()) {
+            // Need restore timeout before onDone is called, but onComplete can be called concurrently,
+            // thus need ignore duplicated timeout objects.
+            tx.addTimeoutHandler(true);
+        }
+
         if (super.onDone(success, err)) {
             if (log.isDebugEnabled())
                 log.debug("Completing future: " + this);
@@ -675,12 +677,36 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
      * part. Note that if primary node leaves grid, the future will fail and transaction will be rolled back.
      */
     void map() {
+        if (tx != null && tx.trackTimeout()) {
+            if (!tx.removeTimeoutHandler()) {
+                tx.finishFuture().listen(new IgniteInClosure<IgniteInternalFuture<IgniteInternalTx>>() {
+                    @Override public void apply(IgniteInternalFuture<IgniteInternalTx> fut) {
+                        IgniteTxTimeoutCheckedException err = new IgniteTxTimeoutCheckedException("Failed to " +
+                            "acquire lock, transaction was rolled back on timeout [timeout=" + tx.timeout() +
+                            ", tx=" + tx + ']');
+
+                        onError(err);
+
+                        onComplete(false, false, false);
+                    }
+                });
+
+                return;
+            }
+        }
+
+        if (timeout > 0) {
+            timeoutObj = new LockTimeoutObject();
+
+            cctx.time().addTimeoutObject(timeoutObj);
+        }
+
         // Obtain the topology version to use.
         AffinityTopologyVersion topVer = cctx.mvcc().lastExplicitLockTopologyVersion(threadId);
 
         // If there is another system transaction in progress, use it's topology version to prevent deadlock.
         if (topVer == null && tx != null && tx.system())
-            topVer = cctx.tm().lockedTopologyVersion(Thread.currentThread().getId(), tx);
+            topVer = cctx.tm().lockedTopologyVersion(tx);
 
         if (topVer != null && tx != null)
             tx.topologyVersion(topVer);
@@ -930,7 +956,7 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
                             if (log.isDebugEnabled())
                                 log.debug("Entry being locked did not pass filter (will not lock): " + entry);
 
-                            onComplete(false, false);
+                            onComplete(false, false, true);
 
                             return;
                         }
@@ -1307,7 +1333,7 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
             if (log.isDebugEnabled())
                 log.debug("Entry being locked did not pass filter (will not lock): " + entry);
 
-            onComplete(false, false);
+            onComplete(false, false, true);
 
             return false;
         }
@@ -1419,12 +1445,12 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
                             U.warn(log, "Failed to detect deadlock.", e);
                         }
 
-                        onComplete(false, true);
+                        onComplete(false, true, true);
                     }
                 });
             }
             else
-                onComplete(false, true);
+                onComplete(false, true, true);
         }
 
         /** {@inheritDoc} */
@@ -1673,4 +1699,4 @@ public final class GridDhtColocatedLockFuture extends GridCacheCompoundIdentityF
             return S.toString(MiniFuture.class, this, "node", node.id(), "super", super.toString());
         }
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
index c947715..97a72cc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearLockFuture.java
@@ -50,6 +50,7 @@ import org.apache.ignite.internal.processors.cache.distributed.GridDistributedCa
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheEntry;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTransactionalCacheAdapter;
+import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
 import org.apache.ignite.internal.processors.cache.transactions.TxDeadlock;
@@ -230,12 +231,6 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
         if (log == null)
             log = U.logger(cctx.kernalContext(), logRef, GridNearLockFuture.class);
 
-        if (timeout > 0) {
-            timeoutObj = new LockTimeoutObject();
-
-            cctx.time().addTimeoutObject(timeoutObj);
-        }
-
         valMap = new ConcurrentHashMap8<>();
     }
 
@@ -434,7 +429,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
      * @param success Success flag.
      */
     public void complete(boolean success) {
-        onComplete(success, true);
+        onComplete(success, true, true);
     }
 
     /**
@@ -655,7 +650,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
                     log.debug("Local lock acquired for entries [fut=" + this + ", entries=" + entries + "]");
             }
 
-            onComplete(true, true);
+            onComplete(true, true, true);
 
             return true;
         }
@@ -666,7 +661,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
     /** {@inheritDoc} */
     @Override public boolean cancel() {
         if (onCancelled())
-            onComplete(false, true);
+            onComplete(false, true, true);
 
         return isCancelled();
     }
@@ -690,7 +685,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
         if (err != null)
             success = false;
 
-        return onComplete(success, true);
+        return onComplete(success, true, true);
     }
 
     /**
@@ -698,9 +693,10 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
      *
      * @param success {@code True} if lock was acquired.
      * @param distribute {@code True} if need to distribute lock removal in case of failure.
+     * @param restoreTimeout {@code True} if need restore tx timeout callback.
      * @return {@code True} if complete by this operation.
      */
-    private boolean onComplete(boolean success, boolean distribute) {
+    private boolean onComplete(boolean success, boolean distribute, boolean restoreTimeout) {
         if (log.isDebugEnabled())
             log.debug("Received onComplete(..) callback [success=" + success + ", distribute=" + distribute +
                 ", fut=" + this + ']');
@@ -711,6 +707,12 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
         if (tx != null)
             cctx.tm().txContext(tx);
 
+        if (restoreTimeout && tx != null && tx.trackTimeout()) {
+            // Need restore timeout before onDone is called, but onComplete can be called concurrently,
+            // thus need ignore duplicated timeout objects.
+            tx.addTimeoutHandler(true);
+        }
+
         if (super.onDone(success, err)) {
             if (log.isDebugEnabled())
                 log.debug("Completing future: " + this);
@@ -770,6 +772,30 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
      * part. Note that if primary node leaves grid, the future will fail and transaction will be rolled back.
      */
     void map() {
+        if (tx != null && tx.trackTimeout()) {
+            if (!tx.removeTimeoutHandler()) {
+                tx.finishFuture().listen(new IgniteInClosure<IgniteInternalFuture<IgniteInternalTx>>() {
+                    @Override public void apply(IgniteInternalFuture<IgniteInternalTx> fut) {
+                        IgniteTxTimeoutCheckedException err = new IgniteTxTimeoutCheckedException("Failed to " +
+                            "acquire lock, transaction was rolled back on timeout [timeout=" + tx.timeout() +
+                            ", tx=" + tx + ']');
+
+                        onError(err);
+
+                        onComplete(false, false, false);
+                    }
+                });
+
+                return;
+            }
+        }
+
+        if (timeout > 0) {
+            timeoutObj = new LockTimeoutObject();
+
+            cctx.time().addTimeoutObject(timeoutObj);
+        }
+
         // Obtain the topology version to use.
         long threadId = Thread.currentThread().getId();
 
@@ -777,7 +803,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
 
         // If there is another system transaction in progress, use it's topology version to prevent deadlock.
         if (topVer == null && tx != null && tx.system())
-            topVer = cctx.tm().lockedTopologyVersion(threadId, tx);
+            topVer = cctx.tm().lockedTopologyVersion(tx);
 
         if (topVer != null && tx != null)
             tx.topologyVersion(topVer);
@@ -981,9 +1007,7 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
                                     if (log.isDebugEnabled())
                                         log.debug("Entry being locked did not pass filter (will not lock): " + entry);
 
-                                    onComplete(
-                                        false,
-                                        false);
+                                    onComplete(false, false, true);
 
                                     return;
                                 }
@@ -1476,12 +1500,12 @@ public final class GridNearLockFuture extends GridCacheCompoundIdentityFuture<Bo
                             U.warn(log, "Failed to detect deadlock.", e);
                         }
 
-                        onComplete(false, true);
+                        onComplete(false, true, true);
                     }
                 });
             }
             else
-                onComplete(false, true);
+                onComplete(false, true, true);
         }
 
         /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
index 77c68bd..6d7a862 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
@@ -913,8 +913,7 @@ public class GridNearOptimisticTxPrepareFuture extends GridNearOptimisticTxPrepa
                 return;
 
             if (RCV_RES_UPD.compareAndSet(this, 0, 1)) {
-                if (parent.cctx.tm().deadlockDetectionEnabled() &&
-                    (parent.tx.remainingTime() == -1 || res.error() instanceof IgniteTxTimeoutCheckedException)) {
+                if (parent.tx.remainingTime() == -1 || res.error() instanceof IgniteTxTimeoutCheckedException) {
                     parent.onTimeout();
 
                     return;

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFutureAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFutureAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFutureAdapter.java
index f09b6c8..9e5be1c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFutureAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFutureAdapter.java
@@ -55,7 +55,7 @@ public abstract class GridNearOptimisticTxPrepareFutureAdapter extends GridNearT
 
         // If there is another system transaction in progress, use it's topology version to prevent deadlock.
         if (topVer == null && tx.system()) {
-            topVer = cctx.tm().lockedTopologyVersion(threadId, tx);
+            topVer = cctx.tm().lockedTopologyVersion(tx);
 
             if (topVer == null)
                 topVer = tx.topologyVersionSnapshot();

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTransactionalCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTransactionalCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTransactionalCache.java
index 9d0b186..ca07485 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTransactionalCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTransactionalCache.java
@@ -133,7 +133,7 @@ public class GridNearTransactionalCache<K, V> extends GridNearCacheAdapter<K, V>
         if (keyCheck)
             validateCacheKeys(keys);
 
-        GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
+        GridNearTxLocal tx = ctx.tm().currentThreadTx(ctx);
 
         CacheOperationContext opCtx = ctx.operationContextPerCall();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxLocal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxLocal.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxLocal.java
index 058a3ff..9f3cccf 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxLocal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxLocal.java
@@ -67,6 +67,7 @@ import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
 import org.apache.ignite.internal.processors.cache.transactions.TransactionProxy;
 import org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
+import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
 import org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException;
 import org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException;
 import org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException;
@@ -107,6 +108,7 @@ import static org.apache.ignite.internal.processors.cache.transactions.IgniteTxE
 import static org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry.SER_READ_NOT_EMPTY_VER;
 import static org.apache.ignite.transactions.TransactionState.COMMITTED;
 import static org.apache.ignite.transactions.TransactionState.COMMITTING;
+import static org.apache.ignite.transactions.TransactionState.MARKED_ROLLBACK;
 import static org.apache.ignite.transactions.TransactionState.PREPARED;
 import static org.apache.ignite.transactions.TransactionState.PREPARING;
 import static org.apache.ignite.transactions.TransactionState.ROLLED_BACK;
@@ -117,7 +119,7 @@ import static org.apache.ignite.transactions.TransactionState.UNKNOWN;
  * Replicated user transaction.
  */
 @SuppressWarnings("unchecked")
-public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoCloseable  {
+public class GridNearTxLocal extends GridDhtTxLocalAdapter implements GridTimeoutObject, AutoCloseable {
     /** */
     private static final long serialVersionUID = 0L;
 
@@ -229,6 +231,9 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
         mappings = implicitSingle ? new IgniteTxMappingsSingleImpl() : new IgniteTxMappingsImpl();
 
         initResult();
+
+        if (trackTimeout())
+            addTimeoutHandler(false);
     }
 
     /** {@inheritDoc} */
@@ -1621,7 +1626,7 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
                 // with prepare response, if required.
                 assert loadFut.isDone();
 
-                return nonInterruptable(commitNearTxLocalAsync().chain(new CX1<IgniteInternalFuture<IgniteInternalTx>, GridCacheReturn>() {
+                return nonInterruptable(commitNearTxLocalAsync(false).chain(new CX1<IgniteInternalFuture<IgniteInternalTx>, GridCacheReturn>() {
                     @Override public GridCacheReturn applyx(IgniteInternalFuture<IgniteInternalTx> txFut)
                         throws IgniteCheckedException {
                         try {
@@ -1631,7 +1636,7 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
                                 implicitRes.value(), implicitRes.success());
                         }
                         catch (IgniteCheckedException | RuntimeException e) {
-                            rollbackNearTxLocalAsync();
+                            rollbackNearTxLocalAsync(false);
 
                             throw e;
                         }
@@ -2389,7 +2394,7 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
                 return new GridFinishedFuture<>(e);
             }
 
-            return nonInterruptable(commitNearTxLocalAsync().chain(
+            return nonInterruptable(commitNearTxLocalAsync(false).chain(
                 new CX1<IgniteInternalFuture<IgniteInternalTx>, GridCacheReturn>() {
                     @Override public GridCacheReturn applyx(IgniteInternalFuture<IgniteInternalTx> txFut)
                         throws IgniteCheckedException {
@@ -2408,7 +2413,7 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
                         }
                         catch (IgniteCheckedException | RuntimeException e) {
                             if (!(e instanceof NodeStoppingException))
-                                rollbackNearTxLocalAsync();
+                                rollbackNearTxLocalAsync(false);
 
                             throw e;
                         }
@@ -3132,6 +3137,8 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
         GridNearTxPrepareFutureAdapter fut = (GridNearTxPrepareFutureAdapter)prepFut;
 
         if (fut == null) {
+            removeTimeoutHandler();
+
             long timeout = remainingTime();
 
             // Future must be created before any exception can be thrown.
@@ -3178,30 +3185,26 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
         if (awaitLastFuture)
             txState().awaitLastFuture(cctx);
 
-        prepareAsync().get();
-    }
-
-    /**
-     * @return Prepare future.
-     */
-    private IgniteInternalFuture<?> prepareAsync() {
-        return prepareNearTxLocal();
+        prepareNearTxLocal().get();
     }
 
     /**
      * @throws IgniteCheckedException If failed.
      */
     public void commit() throws IgniteCheckedException {
-        commitNearTxLocalAsync().get();
+        commitNearTxLocalAsync(true).get();
     }
 
     /**
      * @return Finish future.
      */
-    public IgniteInternalFuture<IgniteInternalTx> commitNearTxLocalAsync() {
+    public IgniteInternalFuture<IgniteInternalTx> commitNearTxLocalAsync(boolean clearThreadLocal) {
         if (log.isDebugEnabled())
             log.debug("Committing near local tx: " + this);
 
+        if (clearThreadLocal)
+            cctx.tm().clearThreadLocalTx(this);
+
         if (fastFinish()) {
             state(PREPARING);
             state(PREPARED);
@@ -3255,23 +3258,28 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
 
     /** {@inheritDoc} */
     @Override public IgniteInternalFuture<IgniteInternalTx> commitAsync() {
-        return commitNearTxLocalAsync();
+        return commitNearTxLocalAsync(true);
     }
 
     /**
      * @throws IgniteCheckedException If failed.
      */
     public void rollback() throws IgniteCheckedException {
-        rollbackNearTxLocalAsync().get();
+        rollbackNearTxLocalAsync(true).get();
     }
 
     /**
      * @return Rollback future.
      */
-    public IgniteInternalFuture<IgniteInternalTx> rollbackNearTxLocalAsync() {
+    public IgniteInternalFuture<IgniteInternalTx> rollbackNearTxLocalAsync(boolean clearThreadLocal) {
         if (log.isDebugEnabled())
             log.debug("Rolling back near tx: " + this);
 
+        if (clearThreadLocal)
+            cctx.tm().clearThreadLocalTx(this);
+
+        removeTimeoutHandler();
+
         if (fastFinish()) {
             state(PREPARING);
             state(PREPARED);
@@ -3333,7 +3341,7 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
 
     /** {@inheritDoc} */
     @Override public IgniteInternalFuture<IgniteInternalTx> rollbackAsync() {
-        return rollbackNearTxLocalAsync();
+        return rollbackNearTxLocalAsync(true);
     }
 
     /**
@@ -3695,6 +3703,11 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
 
         if (state != ROLLING_BACK && state != ROLLED_BACK && state != COMMITTING && state != COMMITTED)
             rollback();
+        else {
+            cctx.tm().clearThreadLocalTx(this);
+
+            removeTimeoutHandler();
+        }
 
         synchronized (this) {
             try {
@@ -4000,13 +4013,65 @@ public class GridNearTxLocal extends GridDhtTxLocalAdapter implements AutoClosea
 
     /**
      * @param threadId new owner of transaction.
-     * @throws IgniteCheckedException if method executed not in the middle of resume or suspend.
      */
     public void threadId(long threadId) {
         this.threadId = threadId;
     }
 
     /**
+     * @return {@code True} if need register callback which cancels tx on timeout.
+     */
+    public boolean trackTimeout() {
+        return timeout() > 0 && !implicit();
+    }
+
+    /**
+     * Removes timeout handler.
+     *
+     * @return {@code True} if handler was removed.
+     */
+    public boolean removeTimeoutHandler() {
+        return trackTimeout() && cctx.time().removeTimeoutObject(this);
+    }
+
+    /**
+     * @param ignoreDuplicated {@code True} if do need check for duplicated timeout object.
+     */
+    public void addTimeoutHandler(boolean ignoreDuplicated) {
+        assert trackTimeout();
+
+        cctx.time().addTimeoutObject(this, ignoreDuplicated);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteUuid timeoutId() {
+        return xid();
+    }
+
+    /** {@inheritDoc} */
+    @Override public long endTime() {
+        return startTime() + timeout();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onTimeout() {
+        if (state(MARKED_ROLLBACK, true) || (state() == MARKED_ROLLBACK)) {
+            if (log.isDebugEnabled())
+                log.debug("Will rollback tx on timeout: " + this);
+
+            cctx.kernalContext().closure().runLocalSafe(new Runnable() {
+                @Override public void run() {
+                    rollbackNearTxLocalAsync(false);
+                }
+            });
+        }
+        else {
+            if (log.isDebugEnabled())
+                log.debug("Skip rollback tx on timeout: " + this);
+        }
+    }
+
+    /**
      * Post-lock closure.
      *
      * @param <T> Return type.

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java
index 7598003..9e06d9d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java
@@ -634,4 +634,4 @@ public interface IgniteInternalTx {
      * @param e Commit error.
      */
     public void commitError(Throwable e);
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxAdapter.java
index c447436..ee5752c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxAdapter.java
@@ -483,7 +483,7 @@ public abstract class IgniteTxAdapter extends GridMetadataAwareAdapter implement
 
         if (res.equals(AffinityTopologyVersion.NONE)) {
             if (system()) {
-                AffinityTopologyVersion topVer = cctx.tm().lockedTopologyVersion(Thread.currentThread().getId(), this);
+                AffinityTopologyVersion topVer = cctx.tm().lockedTopologyVersion(this);
 
                 if (topVer != null)
                     return topVer;
@@ -987,7 +987,7 @@ public abstract class IgniteTxAdapter extends GridMetadataAwareAdapter implement
      * @return {@code True} if state changed.
      */
     @SuppressWarnings({"TooBroadScope"})
-    protected boolean state(TransactionState state, boolean timedOut) {
+    protected final boolean state(TransactionState state, boolean timedOut) {
         boolean valid = false;
 
         TransactionState prev;
@@ -1068,7 +1068,9 @@ public abstract class IgniteTxAdapter extends GridMetadataAwareAdapter implement
 
             if (valid) {
                 this.state = state;
-                this.timedOut = timedOut;
+
+                if (timedOut)
+                    this.timedOut = true;
 
                 if (log.isDebugEnabled())
                     log.debug("Changed transaction state [prev=" + prev + ", new=" + this.state + ", tx=" + this + ']');

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
index b60bab5..8566ece 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
@@ -257,7 +257,7 @@ public class IgniteTxHandler {
         IgniteInternalFuture<GridNearTxPrepareResponse> fut = locTx.prepareAsyncLocal(req);
 
         if (locTx.isRollbackOnly())
-            locTx.rollbackNearTxLocalAsync();
+            locTx.rollbackNearTxLocalAsync(false);
 
         return fut.chain(new C1<IgniteInternalFuture<GridNearTxPrepareResponse>, GridNearTxPrepareResponse>() {
             @Override public GridNearTxPrepareResponse apply(IgniteInternalFuture<GridNearTxPrepareResponse> f) {
@@ -1010,7 +1010,7 @@ public class IgniteTxHandler {
 
             if (tx != null)
                 try {
-                    return tx.rollbackNearTxLocalAsync();
+                    return tx.rollbackNearTxLocalAsync(false);
                 }
                 catch (Throwable e1) {
                     e.addSuppressed(e1);

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxManager.java
index 9a8280f..8eeb804 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxManager.java
@@ -22,7 +22,6 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
@@ -150,11 +149,11 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     /** Topology version should be used when mapping internal tx. */
     private final ThreadLocal<AffinityTopologyVersion> txTop = new ThreadLocal<>();
 
-    /** Per-thread transaction map. */
-    private final ConcurrentMap<Long, IgniteInternalTx> threadMap = newMap();
+    /** Current thread's tx. */
+    private final ThreadLocal<GridNearTxLocal> threadTx = new ThreadLocal<>();
 
-    /** Per-thread system transaction map. */
-    private final ConcurrentMap<TxThreadKey, IgniteInternalTx> sysThreadMap = newMap();
+    /** Current thread's system tx. */
+    private final ThreadLocal<GridNearTxLocal> threadSysTx = new ThreadLocal<>();
 
     /** Per-ID map. */
     private final ConcurrentMap<GridCacheVersion, IgniteInternalTx> idMap = newMap();
@@ -291,7 +290,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     public void rollbackTransactionsForCache(int cacheId) {
         rollbackTransactionsForCache(cacheId, nearIdMap);
 
-        rollbackTransactionsForCache(cacheId, threadMap);
+        rollbackTransactionsForCache(cacheId, idMap);
     }
 
     /**
@@ -316,8 +315,10 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     @Override public void onDisconnected(IgniteFuture reconnectFut) {
         txFinishSync.onDisconnected(reconnectFut);
 
-        for (Map.Entry<Long, IgniteInternalTx> e : threadMap.entrySet())
-            rollbackTx(e.getValue());
+        for (IgniteInternalTx tx : idMap.values())
+            rollbackTx(tx);
+        for (IgniteInternalTx tx : nearIdMap.values())
+            rollbackTx(tx);
 
         IgniteClientDisconnectedException err =
             new IgniteClientDisconnectedException(reconnectFut, "Client node disconnected.");
@@ -376,20 +377,13 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     @Override public void printMemoryStats() {
         X.println(">>> ");
         X.println(">>> Transaction manager memory stats [igniteInstanceName=" + cctx.igniteInstanceName() + ']');
-        X.println(">>>   threadMapSize: " + threadMap.size());
         X.println(">>>   idMap [size=" + idMap.size() + ']');
+        X.println(">>>   nearIdMap [size=" + nearIdMap.size() + ']');
         X.println(">>>   completedVersSortedSize: " + completedVersSorted.size());
         X.println(">>>   completedVersHashMapSize: " + completedVersHashMap.sizex());
     }
 
     /**
-     * @return Thread map size.
-     */
-    public int threadMapSize() {
-        return threadMap.size();
-    }
-
-    /**
      * @return ID map size.
      */
     public int idMapSize() {
@@ -459,7 +453,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
             taskNameHash);
 
         if (tx.system()) {
-            AffinityTopologyVersion topVer = cctx.tm().lockedTopologyVersion(Thread.currentThread().getId(), tx);
+            AffinityTopologyVersion topVer = cctx.tm().lockedTopologyVersion(tx);
 
             // If there is another system transaction in progress, use it's topology version to prevent deadlock.
             if (topVer != null)
@@ -490,14 +484,15 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
         IgniteInternalTx t;
 
         if ((t = txIdMap.putIfAbsent(tx.xidVersion(), tx)) == null) {
-            // Add both, explicit and implicit transactions.
-            // Do not add remote and dht local transactions as remote node may have the same thread ID
-            // and overwrite local transaction.
             if (tx.local() && !tx.dht()) {
-                if (cacheCtx == null || !cacheCtx.systemTx())
-                    threadMap.put(tx.threadId(), tx);
-                else
-                    sysThreadMap.put(new TxThreadKey(tx.threadId(), cacheCtx.cacheId()), tx);
+                assert tx instanceof GridNearTxLocal : tx;
+
+                if (!tx.implicit()) {
+                    if (cacheCtx == null || !cacheCtx.systemTx())
+                        threadTx.set((GridNearTxLocal)tx);
+                    else
+                        threadSysTx.set((GridNearTxLocal)tx);
+                }
             }
 
             // Handle mapped versions.
@@ -633,27 +628,10 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     /**
      * @return Local transaction.
      */
-    @SuppressWarnings({"unchecked"})
-    @Nullable public <T> T localTx() {
-        IgniteInternalTx tx = tx();
-
-        return tx != null && tx.local() ? (T)tx : null;
-    }
-
-    /**
-     * @param cctx Cache context.
-     * @return Transaction for current thread.
-     */
-    public GridNearTxLocal threadLocalTx(GridCacheContext cctx) {
-        IgniteInternalTx tx = tx(cctx, Thread.currentThread().getId());
+    @Nullable public IgniteTxLocalAdapter localTx() {
+        IgniteTxLocalAdapter tx = tx();
 
-        if (tx != null && tx.local() && (!tx.dht() || tx.colocated()) && !tx.implicit()) {
-            assert tx instanceof GridNearTxLocal : tx;
-
-            return (GridNearTxLocal)tx;
-        }
-
-        return null;
+        return tx != null && tx.local() ? tx : null;
     }
 
     /**
@@ -663,16 +641,22 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     public <T> T tx() {
         IgniteInternalTx tx = txContext();
 
-        return tx != null ? (T)tx : (T)tx(null, Thread.currentThread().getId());
+        return tx != null ? (T)tx : (T)currentThreadTx(null);
     }
 
     /**
-     * @param threadId Thread ID.
      * @param ignore Transaction to ignore.
      * @return Not null topology version if current thread holds lock preventing topology change.
      */
-    @Nullable public AffinityTopologyVersion lockedTopologyVersion(long threadId, IgniteInternalTx ignore) {
-        IgniteInternalTx tx = threadMap.get(threadId);
+    @Nullable public AffinityTopologyVersion lockedTopologyVersion(IgniteInternalTx ignore) {
+        IgniteInternalTx tx = threadTx.get();
+
+        if (tx == null) {
+            tx = threadSysTx.get();
+
+            if (tx == ignore)
+                tx = null;
+        }
 
         if (tx != null) {
             AffinityTopologyVersion topVer = tx.topologyVersionSnapshot();
@@ -681,22 +665,6 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
                 return topVer;
         }
 
-        if (!sysThreadMap.isEmpty()) {
-            for (GridCacheContext cacheCtx : cctx.cache().context().cacheContexts()) {
-                if (!cacheCtx.systemTx())
-                    continue;
-
-                tx = sysThreadMap.get(new TxThreadKey(threadId, cacheCtx.cacheId()));
-
-                if (tx != null && tx != ignore) {
-                    AffinityTopologyVersion topVer = tx.topologyVersionSnapshot();
-
-                    if (topVer != null)
-                        return topVer;
-                }
-            }
-        }
-
         return txTop.get();
     }
 
@@ -719,15 +687,6 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     }
 
     /**
-     * @return Local transaction.
-     */
-    @Nullable public IgniteInternalTx localTxx() {
-        IgniteInternalTx tx = tx();
-
-        return tx != null && tx.local() ? tx : null;
-    }
-
-    /**
      * @return User transaction for current thread.
      */
     @Nullable public GridNearTxLocal userTx() {
@@ -736,7 +695,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
         if (activeUserTx(tx))
             return (GridNearTxLocal)tx;
 
-        tx = tx(null, Thread.currentThread().getId());
+        tx = currentThreadTx(null);
 
         if (activeUserTx(tx))
             return (GridNearTxLocal)tx;
@@ -749,7 +708,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
      * @return User transaction for current thread.
      */
     @Nullable GridNearTxLocal userTx(GridCacheContext cctx) {
-        IgniteInternalTx tx = tx(cctx, Thread.currentThread().getId());
+        IgniteInternalTx tx = currentThreadTx(cctx);
 
         if (activeUserTx(tx))
             return (GridNearTxLocal)tx;
@@ -773,17 +732,14 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
 
     /**
      * @param cctx Cache context.
-     * @param threadId Id of thread for transaction.
      * @return Transaction for thread with given ID.
      */
     @SuppressWarnings({"unchecked"})
-    private <T> T tx(GridCacheContext cctx, long threadId) {
+    public GridNearTxLocal currentThreadTx(GridCacheContext cctx) {
         if (cctx == null || !cctx.systemTx())
-            return (T)threadMap.get(threadId);
+            return threadTx.get();
 
-        TxThreadKey key = new TxThreadKey(threadId, cctx.cacheId());
-
-        return (T)sysThreadMap.get(key);
+        return threadSysTx.get();
     }
 
     /**
@@ -1215,32 +1171,29 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
                 collectPendingVersions(dhtTxLoc);
             }
 
-            // 4. Unlock write resources.
+            // 3. Unlock write resources.
             unlockMultiple(tx, tx.writeEntries());
 
-            // 5. Unlock read resources if required.
+            // 4. Unlock read resources if required.
             if (unlockReadEntries(tx))
                 unlockMultiple(tx, tx.readEntries());
 
-            // 6. Notify evictions.
+            // 5. Notify evictions.
             notifyEvictions(tx);
 
-            // 7. Remove obsolete entries from cache.
+            // 6. Remove obsolete entries from cache.
             removeObsolete(tx);
 
-            // 8. Assign transaction number at the end of transaction.
+            // 7. Assign transaction number at the end of transaction.
             tx.endVersion(cctx.versions().next(tx.topologyVersion()));
 
-            // 9. Remove from per-thread storage.
-            clearThreadMap(tx);
-
-            // 10. Unregister explicit locks.
+            // 8. Unregister explicit locks.
             if (!tx.alternateVersions().isEmpty()) {
                 for (GridCacheVersion ver : tx.alternateVersions())
                     idMap.remove(ver);
             }
 
-            // 11. Remove Near-2-DHT mappings.
+            // 9. Remove Near-2-DHT mappings.
             if (tx instanceof GridCacheMappedVersion) {
                 GridCacheVersion mapped = ((GridCacheMappedVersion)tx).mappedVersion();
 
@@ -1248,10 +1201,10 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
                     mappedVers.remove(mapped);
             }
 
-            // 12. Clear context.
+            // 10. Clear context.
             resetContext();
 
-            // 14. Update metrics.
+            // 11. Update metrics.
             if (!tx.dht() && tx.local()) {
                 if (!tx.system())
                     cctx.txMetrics().onTxCommit();
@@ -1301,22 +1254,19 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
             // 5. Remove obsolete entries.
             removeObsolete(tx);
 
-            // 6. Remove from per-thread storage.
-            clearThreadMap(tx);
-
-            // 7. Unregister explicit locks.
+            // 6. Unregister explicit locks.
             if (!tx.alternateVersions().isEmpty())
                 for (GridCacheVersion ver : tx.alternateVersions())
                     idMap.remove(ver);
 
-            // 8. Remove Near-2-DHT mappings.
+            // 7. Remove Near-2-DHT mappings.
             if (tx instanceof GridCacheMappedVersion)
                 mappedVers.remove(((GridCacheMappedVersion)tx).mappedVersion());
 
-            // 9. Clear context.
+            // 8. Clear context.
             resetContext();
 
-            // 10. Update metrics.
+            // 9. Update metrics.
             if (!tx.dht() && tx.local()) {
                 if (!tx.system())
                     cctx.txMetrics().onTxRollback();
@@ -1357,13 +1307,10 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
             // 3. Remove obsolete entries.
             removeObsolete(tx);
 
-            // 4. Remove from per-thread storage.
-            clearThreadMap(tx);
-
-            // 5. Clear context.
+            // 4. Clear context.
             resetContext();
 
-            // 6. Update metrics.
+            // 5. Update metrics.
             if (!tx.dht() && tx.local()) {
                 if (!tx.system()) {
                     if (commit)
@@ -1401,20 +1348,17 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
             // 3. Notify evictions.
             notifyEvictions(tx);
 
-            // 4. Remove from per-thread storage.
-            clearThreadMap(tx);
-
-            // 5. Unregister explicit locks.
+            // 4. Unregister explicit locks.
             if (!tx.alternateVersions().isEmpty()) {
                 for (GridCacheVersion ver : tx.alternateVersions())
                     idMap.remove(ver);
             }
 
-            // 6. Remove Near-2-DHT mappings.
+            // 5. Remove Near-2-DHT mappings.
             if (tx instanceof GridCacheMappedVersion)
                 mappedVers.remove(((GridCacheMappedVersion)tx).mappedVersion());
 
-            // 7. Clear context.
+            // 6. Clear context.
             resetContext();
 
             if (log.isDebugEnabled())
@@ -1427,28 +1371,14 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
     /**
      * @param tx Transaction to clear.
      */
-    private void clearThreadMap(IgniteInternalTx tx) {
-        if (tx.local() && !tx.dht()) {
-            if (!tx.system())
-                threadMap.remove(tx.threadId(), tx);
-            else {
-                Integer cacheId = tx.txState().firstCacheId();
-
-                if (cacheId != null)
-                    sysThreadMap.remove(new TxThreadKey(tx.threadId(), cacheId), tx);
-                else {
-                    for (Iterator<IgniteInternalTx> it = sysThreadMap.values().iterator(); it.hasNext(); ) {
-                        IgniteInternalTx txx = it.next();
-
-                        if (tx == txx) {
-                            it.remove();
+    public void clearThreadLocalTx(GridNearTxLocal tx) {
+        if (tx.implicit())
+            return;
 
-                            break;
-                        }
-                    }
-                }
-            }
-        }
+        if (tx.system())
+            threadSysTx.set(null);
+        else
+            threadTx.set(null);
     }
 
     /**
@@ -2257,6 +2187,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
      * @see #resumeTx(GridNearTxLocal)
      * @see GridNearTxLocal#suspend()
      * @see GridNearTxLocal#resume()
+     * @throws IgniteCheckedException If failed to suspend transaction.
      */
     public void suspendTx(final GridNearTxLocal tx) throws IgniteCheckedException {
         assert tx != null && !tx.system() : tx;
@@ -2266,7 +2197,7 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
                 + "[expected=" + ACTIVE + ", actual=" + tx.state() + ']');
         }
 
-        clearThreadMap(tx);
+        clearThreadLocalTx(tx);
 
         transactionMap(tx).remove(tx.xidVersion(), tx);
     }
@@ -2280,45 +2211,30 @@ public class IgniteTxManager extends GridCacheSharedManagerAdapter {
      * @see #suspendTx(GridNearTxLocal)
      * @see GridNearTxLocal#suspend()
      * @see GridNearTxLocal#resume()
+     * @throws IgniteCheckedException If failed to resume tx.
      */
     public void resumeTx(GridNearTxLocal tx) throws IgniteCheckedException {
         assert tx != null && !tx.system() : tx;
-        assert !threadMap.containsValue(tx) : tx;
         assert !transactionMap(tx).containsValue(tx) : tx;
-        assert !haveSystemTxForThread(Thread.currentThread().getId());
+        assert threadSysTx.get() == null;
 
-        if(!tx.state(ACTIVE)) {
+        if (!tx.state(ACTIVE)) {
             throw new IgniteCheckedException("Trying to resume transaction with incorrect state "
                 + "[expected=" + SUSPENDED + ", actual=" + tx.state() + ']');
         }
 
-        long threadId = Thread.currentThread().getId();
+        if (threadTx.get() != null)
+            throw new IgniteCheckedException("Thread already has started a transaction.");
 
-        if (threadMap.putIfAbsent(threadId, tx) != null)
-            throw new IgniteCheckedException("Thread already start a transaction.");
+        threadTx.set(tx);
 
-        if (transactionMap(tx).putIfAbsent(tx.xidVersion(), tx) != null)
-            throw new IgniteCheckedException("Thread already start a transaction.");
+        if (transactionMap(tx).putIfAbsent(tx.xidVersion(), tx) != null) {
+            threadTx.set(null);
 
-        tx.threadId(threadId);
-    }
-
-    /**
-     * @param threadId Thread id.
-     * @return True if thread have system transaction. False otherwise.
-     */
-    private boolean haveSystemTxForThread(long threadId) {
-        if (!sysThreadMap.isEmpty()) {
-            for (GridCacheContext cacheCtx : cctx.cache().context().cacheContexts()) {
-                if (!cacheCtx.systemTx())
-                    continue;
-
-                if (sysThreadMap.containsKey(new TxThreadKey(threadId, cacheCtx.cacheId())))
-                    return true;
-            }
+            throw new IgniteCheckedException("Thread already has started a transaction.");
         }
 
-        return false;
+        tx.threadId(Thread.currentThread().getId());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java
index 8c71f76..e69306f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/timeout/GridTimeoutProcessor.java
@@ -85,15 +85,23 @@ public class GridTimeoutProcessor extends GridProcessorAdapter {
     /**
      * @param timeoutObj Timeout object.
      */
-    @SuppressWarnings({"NakedNotify", "CallToNotifyInsteadOfNotifyAll"})
     public void addTimeoutObject(GridTimeoutObject timeoutObj) {
+        addTimeoutObject(timeoutObj, false);
+    }
+
+    /**
+     * @param timeoutObj Timeout object.
+     * @param ignoreDuplicated {@code True} if do need check for duplicated object.
+     */
+    @SuppressWarnings({"NakedNotify", "CallToNotifyInsteadOfNotifyAll"})
+    public void addTimeoutObject(GridTimeoutObject timeoutObj, boolean ignoreDuplicated) {
         if (timeoutObj.endTime() <= 0 || timeoutObj.endTime() == Long.MAX_VALUE)
             // Timeout will never happen.
             return;
 
         boolean added = timeoutObjs.add(timeoutObj);
 
-        assert added : "Duplicate timeout object found: " + timeoutObj;
+        assert ignoreDuplicated || added : "Duplicate timeout object found: " + timeoutObj;
 
         if (timeoutObjs.firstx() == timeoutObj) {
             synchronized (mux) {
@@ -124,9 +132,10 @@ public class GridTimeoutProcessor extends GridProcessorAdapter {
 
     /**
      * @param timeoutObj Timeout object.
+     * @return {@code True} if timeout object was removed.
      */
-    public void removeTimeoutObject(GridTimeoutObject timeoutObj) {
-        timeoutObjs.remove(timeoutObj);
+    public boolean removeTimeoutObject(GridTimeoutObject timeoutObj) {
+        return timeoutObjs.remove(timeoutObj);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxConfigCacheSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxConfigCacheSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxConfigCacheSelfTest.java
index 2efa0cb..f2e17e4 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxConfigCacheSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteTxConfigCacheSelfTest.java
@@ -185,6 +185,8 @@ public class IgniteTxConfigCacheSelfTest extends GridCommonAbstractTest {
         try (final Transaction tx = ignite.transactions().txStart()) {
             assert tx != null;
 
+            cache.put("key0", "val0");
+
             sleepForTxFailure();
 
             cache.put("key", "val");
@@ -195,7 +197,19 @@ public class IgniteTxConfigCacheSelfTest extends GridCommonAbstractTest {
             assert e.getCause() instanceof TransactionTimeoutException;
         }
 
+        assertNull(ignite.transactions().tx());
+
+        assert !cache.containsKey("key0");
         assert !cache.containsKey("key");
+
+        // New transaction must succeed.
+        try (final Transaction tx = ignite.transactions().txStart()) {
+            cache.put("key", "val");
+
+            tx.commit();
+        }
+
+        assert cache.containsKey("key");
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheSystemTransactionsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheSystemTransactionsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheSystemTransactionsSelfTest.java
index eb19873..bb5e653 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheSystemTransactionsSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheSystemTransactionsSelfTest.java
@@ -115,8 +115,8 @@ public class IgniteCacheSystemTransactionsSelfTest extends GridCacheAbstractSelf
         try (GridNearTxLocal itx = utilityCache.txStartEx(OPTIMISTIC, SERIALIZABLE)) {
             utilityCache.put("1", "1");
 
-            itx.commitNearTxLocalAsync();
-            itx.commitNearTxLocalAsync().get();
+            itx.commitNearTxLocalAsync(false);
+            itx.commitNearTxLocalAsync(true).get();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheThreadLocalTxTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheThreadLocalTxTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheThreadLocalTxTest.java
new file mode 100644
index 0000000..4b08500
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheThreadLocalTxTest.java
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.distributed;
+
+import java.util.concurrent.ThreadLocalRandom;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteTransactions;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteKernal;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.lang.IgniteFuture;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.apache.ignite.transactions.Transaction;
+import org.apache.ignite.transactions.TransactionConcurrency;
+import org.apache.ignite.transactions.TransactionIsolation;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+
+/**
+ *
+ */
+public class IgniteCacheThreadLocalTxTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private boolean client;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);
+
+        cfg.setClientMode(client);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testSingleNode() throws Exception {
+        threadLocalTx(startGrid(0));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testMultiNode() throws Exception {
+        startGridsMultiThreaded(4);
+
+        client = true;
+
+        startGrid(4);
+
+        for (Ignite node : G.allGrids())
+            threadLocalTx(node);
+    }
+
+    /**
+     * @param node Node.
+     * @throws Exception If failed.
+     */
+    @SuppressWarnings("unchecked")
+    private void threadLocalTx(Ignite node) throws Exception {
+        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
+
+        ccfg.setAtomicityMode(TRANSACTIONAL);
+        ccfg.setBackups(2);
+
+        IgniteCache<Object, Object> cache = node.getOrCreateCache(ccfg);
+
+        checkNoTx(node);
+
+        boolean[] reads = {true, false};
+        boolean[] writes = {true, false};
+        int endOps = 5;
+
+        for (TransactionConcurrency concurrency : TransactionConcurrency.values()) {
+            for (TransactionIsolation isolation : TransactionIsolation.values()) {
+                for (boolean read : reads) {
+                    for (boolean write : writes) {
+                        for (int i = 0; i < endOps; i++)
+                            checkTx(concurrency, isolation, node, cache, read, write, i);
+                    }
+                }
+            }
+        }
+
+        checkNoTx(node);
+
+        cache.put(1, 1);
+
+        checkNoTx(node);
+    }
+
+    /**
+     * @param concurrency Tx concurrency.
+     * @param isolation Tx isolation.
+     * @param node Node.
+     * @param cache Cache.
+     * @param read {@code True} if read in tx.
+     * @param write {@code True} if write in tx.
+     * @param endOp Operation to test.
+     */
+    private void checkTx(TransactionConcurrency concurrency,
+        TransactionIsolation isolation,
+        Ignite node,
+        IgniteCache<Object, Object> cache,
+        boolean read,
+        boolean write,
+        int endOp) {
+        IgniteTransactions txs = node.transactions();
+
+        checkNoTx(node);
+
+        Transaction tx = txs.txStart(concurrency, isolation);
+
+        assertEquals(tx, txs.tx());
+
+        try {
+            txs.txStart(concurrency, isolation);
+
+            fail();
+        }
+        catch (IllegalStateException expected) {
+            // No-op.
+        }
+
+        if (read)
+            cache.get(ThreadLocalRandom.current().nextInt(100_000));
+
+        if (write)
+            cache.put(ThreadLocalRandom.current().nextInt(100_000), 1);
+
+
+        try {
+            txs.txStart(concurrency, isolation);
+
+            fail();
+        }
+        catch (IllegalStateException expected) {
+            // No-op.
+        }
+
+        assertEquals(tx, txs.tx());
+
+        IgniteFuture fut = null;
+
+        switch (endOp) {
+            case 0:
+                tx.commit();
+
+                break;
+
+            case 1:
+                fut = tx.commitAsync();
+
+                break;
+
+            case 2:
+                tx.rollback();
+
+                break;
+
+            case 3:
+                fut = tx.rollbackAsync();
+
+                break;
+
+            case 4:
+                tx.close();
+
+                break;
+
+            default:
+                fail();
+        }
+
+        checkNoTx(node);
+
+        if (fut != null)
+            fut.get();
+
+        checkNoTx(node);
+    }
+
+    /**
+     * @param node Node.
+     */
+    private void checkNoTx(Ignite node) {
+        IgniteTransactions txs = node.transactions();
+
+        assertNull(txs.tx());
+        assertNull(((IgniteKernal)node).context().cache().context().tm().tx());
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteOptimisticTxSuspendResumeTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteOptimisticTxSuspendResumeTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteOptimisticTxSuspendResumeTest.java
index 37003a7..86c0fa4 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteOptimisticTxSuspendResumeTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteOptimisticTxSuspendResumeTest.java
@@ -46,7 +46,6 @@ import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
 import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
 import static org.apache.ignite.transactions.TransactionState.ACTIVE;
 import static org.apache.ignite.transactions.TransactionState.COMMITTED;
-import static org.apache.ignite.transactions.TransactionState.MARKED_ROLLBACK;
 import static org.apache.ignite.transactions.TransactionState.ROLLED_BACK;
 import static org.apache.ignite.transactions.TransactionState.SUSPENDED;
 
@@ -60,6 +59,7 @@ public class IgniteOptimisticTxSuspendResumeTest extends GridCommonAbstractTest
     /** Future timeout */
     private static final int FUT_TIMEOUT = 5000;
 
+    /** */
     private boolean client = false;
 
     /**
@@ -442,7 +442,7 @@ public class IgniteOptimisticTxSuspendResumeTest extends GridCommonAbstractTest
                         }
                     }, TransactionTimeoutException.class);
 
-                    assertEquals(MARKED_ROLLBACK, tx.state());
+                    assertEquals(ROLLED_BACK, tx.state());
 
                     tx.close();
                 }
@@ -476,7 +476,7 @@ public class IgniteOptimisticTxSuspendResumeTest extends GridCommonAbstractTest
                         }
                     }, TransactionTimeoutException.class);
 
-                    assertEquals(MARKED_ROLLBACK, tx.state());
+                    assertEquals(ROLLED_BACK, tx.state());
 
                     tx.close();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNearCacheTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNearCacheTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNearCacheTest.java
new file mode 100644
index 0000000..7c1a6dd
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNearCacheTest.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.transactions;
+
+/**
+ *
+ */
+public class TxRollbackOnTimeoutNearCacheTest extends TxRollbackOnTimeoutTest {
+    /** {@inheritDoc} */
+    @Override protected boolean nearCacheEnabled() {
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/685f051c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNoDeadlockDetectionTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNoDeadlockDetectionTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNoDeadlockDetectionTest.java
new file mode 100644
index 0000000..5123329
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/transactions/TxRollbackOnTimeoutNoDeadlockDetectionTest.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.transactions;
+
+import org.apache.ignite.transactions.TransactionTimeoutException;
+
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_TX_DEADLOCK_DETECTION_MAX_ITERS;
+
+/**
+ * Tests an ability to eagerly rollback timed out transactions.
+ */
+public class TxRollbackOnTimeoutNoDeadlockDetectionTest extends TxRollbackOnTimeoutTest {
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        System.setProperty(IGNITE_TX_DEADLOCK_DETECTION_MAX_ITERS, "0");
+
+        super.beforeTestsStarted();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        super.afterTestsStopped();
+
+        System.clearProperty(IGNITE_TX_DEADLOCK_DETECTION_MAX_ITERS);
+    }
+
+    /** */
+    @Override protected void validateDeadlockException(Exception e) {
+        assertEquals("TimeoutException is expected",
+            TransactionTimeoutException.class, e.getCause().getClass());
+    }
+}
\ No newline at end of file