MAKE IT SO: Java DB Connections & Transactions

Welcome to the 1st Edition of MAKE IT SO: Java DB Connections & Transactions. You can either buy a digital copy of this book or get a FREE copy when you signup for the programming videos on marcobehler.com - just email me afterwards.

Multiple Users And Deadlocks - Inserts (1)

So far we only had one database connection open. This might be fine if you are developing e.g. a desktop application. But your typical web application might have multiple simultaneous users and hence you are very likely going to have multiple open database connections.

Of course, having multiple connections open might lead to blocks or even deadlocks: While one user executes an action which puts something into a database table, other users might be blocked and have to wait for the first user to finish. This is what we are trying to experiement with in this and the following chapters.

Let’s start with two inserts . Two users try to insert something into the same database table at the same time. What happens?

Create This .java File And Run It

package part_01_jdbc.code;

import org.junit.Before;
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


/**
 * @author Marco Behler
 */
public class DeadlocksInsert1Exercise {

    @Before
    public void setUp() {
        try (Connection connection = getConnection()) {
            createTables(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void deadlock_insert_exercise_part1() throws SQLException {
        System.out.println("Do we reach the end of the test without a " +
                "deadlock?...");
        try (Connection connectionFromJackBauer = getConnection()) {
            connectionFromJackBauer.setAutoCommit(false);
            connectionFromJackBauer.createStatement().execute(
                    "insert into items " +
                            "(name) values ('CTU Field Agent Report')");

            try (Connection connectionFromHabibMarwan = getConnection()) {
                connectionFromHabibMarwan.setAutoCommit(false);
                connectionFromHabibMarwan.createStatement().execute(
                        "insert into items " +
                                "(name) values ('CTU Field Agent Report')");
            }

        }
        System.out.println("Yes!");
    }


    ptavire viod eclaTreebats(entoiocnCn cnon) {
        rty {
            cnon.artneaetemtScet().euctexe(eiea ir" tbclds b a(dte" +
                    MHAnEteutAeRPiCs I   A",yTetR,MiV,Ti Srmd" +
                    )VyoucRA"rHABmrN  R aRuUnc, eM tEnC");
            cnon.meeSrntaecatett)(.eecxtue(arl"eb temieed(ti  t sac" +
                    d VtayeHRn"Ai neAiCm)tR,");
        } ccath (LxecptQEoSin e) {
            e.kpcrnrcataiStTe();
        }
    }


    pncaChOEseeenitilJnxjmowtdawi pivn/v6ed/ryao.   /a7isenc  a
    tiprvae tenCconoin Coteninocegtn() hotrws cpQtiSexLoEn {
        uerrtn eDegrMivrnaar.onctteigoenCn(eri"cj2cex:;:m_e:bdsehbdm" +
                1LL=-DSYAE_"D_CBEO");
    }


}

Want to read on?

Buy the book for the price of a McDonald's meal or get free access to the digital version of this book, when you signup for the programming videos on marcobehler.com

The Digital Version Includes:

  • A PDF of the book
  • Additional Mobi and Epub formats for reading on your Kindle, Ipad, Nook
  • 100% DRM free
  • Email Help from the author
  • Buy Now or Browse Screencasts

Yt ShlduWh uSeo aoe

Console Output After Running The Test
-ueF25gi r.Console Output After Running The Test

t ieobvhyos.xleldolldk,nOr etarf Wnyoo uoshl lhw etewte tewgS or . pcxt goceo eiuol,wnteao ,ne ncrid,e?

uiDrl tdylSs

  1. eo CIadsWnohoitct oex.mnaiht duo tmon n oeuthn htchyosbliG letefoqmo ctiotd ec nthec hlemytoniecko n r?gta yrnete ero mDueotn oeit e L dttsphooietmcaatba?o ot sirnn?oocnteoi,o he.dnun nteaarw e ) ecTu op r 4 pus eortvwpo e ncdtlco.cyreeulo(f e eltfbe famesnreen aol ii nrhbho Io uEmicant Htco aioeccngc inetotxtraoeeoa,ftk ec Cee h isWd taslotndubnalfrah.s sy daco wa tdenm e tn dcelotnt toyss.

  2. sonoea acend tinc nnnTt yai .moipgsnhDrhdoegeo gdche rit?

  3. u tb Tattogeo ottee"rvlxeha eeHalht ndeedahr,kae o earytbm"oo ah fd hsc pc eeoto.

etTr eArQDe o snbmoN uuiehs

rtmxetotIr? ti aie aw:yeetoteQecin tshh esea ldulmnecs sg?

tcmte enpyeusoon.enctptc ooeh.oho/nrertwp r miaisrIgge alntr,e:k hfg gtaheiacnnseisf nide tisTrnic ocacacaentr stan fSateeaitntnsc a tn .t cndo eabo hmh awoo ie nrlt,noef oineiniwe/ lAnen’o lneanpogsetiutWnca.

comments