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 (2)

In the section before, we saw that we can simulatenously insert records into the same table. But is that really always the case?

The inserts from the last section were a bit of a best case scenario. More specifically, our items table does not have any constraints on its columns. (Like a unique constraint or similar). And as soon as we add a unique constraint, you cannot insert two records into the same table anymore and your connections will (dead)lock.

Check out the code below and the only thing that changed is the unique constraint on the name column.

Create This .java File And Run It

package part_01_jdbc.code;

import org.h2.jdbc.JdbcSQLException;
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 DeadlocksInsert2Exercise {

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


    @Test(expected = JdbcSQLException.class)
    public void deadlock_insert_exercise_part2() 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.rntplin("es!Y");
    }

    vpaitre iovd tTrcelaeeabs(nCeoctionn ncon) {
        rty {
            cnon.caarteStmeetent)(.ceuxtee(b("b  seiteleddacri a t" +
                    y ttm, en TVrPiuA,CAeRMS TMEIRHe"sid,Ati " +
                    URayR nR rVmeNtn oAuc,B"A MHECu )cr");
            conn.Settteecmneaart)(.uetecxe(iretteteei  m( alsa dbc"" +
                    iRtt ei ,HnCyneRiuqAundAVaem)" ");
        } tcach (cxLStQiEpeon e) {
            e.rtarptcniTcaSke)(;
        }
    }

     evpponoar/ 6JienxyOe/wi./a victnEmhnendil   esai7astCdcjwa
    rptiave ioetnCconn gientocoetCnn() orhwts opSQitcELexn {
        rreutn reniMarvagDer.eCencnitgtoon(mc":;:xjmier_ed:hsb2dceeb" +
                -EDLB1"Y__=AODSELC");
    }


}

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

oYaWohuhSS eltdue

Console Output After Running The Test
-er6ui2gF.Console Output After Running The Test

t thdnJbc w,neooennldoa2rily n bfii oss seddi anEenfswtc h’ghhaoheemeaQeu cndksodSaol modadi bhtpI ahndv t LrtoeHtsee ee wu e net rcane Taoca aterc ptaxnb ectre eox .peti x .

tullyDSid rs

  1. ithd ei mhrfnatoe in drymamWeni as.ednteehc epcwisphtd atiar essrn, a ewt gshntsha o trn ioatge Ierr?

  2. er tmuhamsaA Wri uCe o aem oo:h esohonmrnewrhiyeh ttts ?o Dtgooeecttet fm ftor.iyh u- yabbvo ?

tAueTeuoeensrh Nom QDrbis

p lne urao aAlrftetskQtnw:tcsa bti gieloao y n?

rsuuudtraibih,(ru ncwstaca rnminnettyce regsmun a slre sii ac i ke, nr,e o shoiaoerynm ,f rdar qd uy roiku moif t a yassony lnCnnrdugrvioAyfl eputylc,gyvafstealeAisgoot:p ntisIedha otnt rewetrueatiui n .nnei dtehhmldndecskrletea qt oassyn)


sroye_lldht kae_dc laaIQ:s i ?

esr ce elti leminsaoetdoewnp dtthn tenro eeo iCnns ypm npiprTs gsn: ol en a kgie cmdte.ddheye w s oor td o n.ietwhebmn h,eii islcfilosc tw.tmf pwa inoh i geaTcnvn tiiltrkoncemtabn.t lnteweRreeatuuertonrahe u t.iunethievyfua-ien oh e ckc otlrtima ,ttoansoloeencd toosec ycircplc nn aci a nftonco moco hIaauaIos le invetk ohoc.tanfe te oAn chr nlmsr si e oo,uayl taao,teis osedfthnht ll c tnrrhhenetacf wTioonilht lia t rlsirmoe wstoxecsoesiseoeevn exln eteeteimunelx ettohe bmn ion!


chwsts nbcQh r eIynitealed d haseab toeeo k l: ueraennsn wcwg iacpaooxatdra?

dr of caheniLtraJuodis Te sv, ioal . djri r eoe hvpe Molie(vowSaltlf uac:ifaoCltteueAnlngcnocdOunssiboti)lni s et tyeeeg ceatch ei a . o ohiy genomedsnkw geqahbbea ndn rslhw, tbs eiau Qoeirsi ipahsrniw vsB aoiei tl dhrr (h srdrieHoeoe er2tntftdenz nny)yger u clDudo ticowja/d hvnyalalccohhd.

comments