Emil Grigore
Emil Grigore

Reputation: 959

How do I block a query thread when another thread is updating the database?

I have a server that makes a child thread for every user that connects to the server.The child server class has the run method and other methods.

One method searches a mysql database with select.

Another method updates the databases.

How can I block the method that searches the database when another thread uses the method that updates the database ?

Upvotes: 1

Views: 162

Answers (3)

75inchpianist
75inchpianist

Reputation: 4102

Not sure if you have a good design doing this, but if you want mutex on a method, declare the method as synchronized like

public synchronized void putInDbase(String value) {
  //only one thread will execute here at a time
}

But if you have two seperate methods within the same class, you want to synchronize the actual code dealing with the database, you can make synchronized blocks

public class myDbase {
     public void search() {

    synchronized(this) {
     //database code
    }

}

public void update() {

   synchronized(this) {
      //database code
   }

}

}

Upvotes: 0

Trying
Trying

Reputation: 14278

Best way to do this is database transaction and proper isolation level.

Below are some isolation levels in MySql:

Read uncommitted

Read committed

Repeatable reads

Serializable

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200296

The proper way to handle your requirement is to do all database operations within a transaction. This will avoid any need of the mutual exclusion of database code and will also guarantee isolation between your Java process and any other database client doing its own operations.

Upvotes: 7

Related Questions