EzDevInfo.com

locking interview questions

Top locking frequently asked interview questions

Why is lock(this) {...} bad?

The MSDN documentation says that

public class SomeObject
{
  public void SomeOperation()
  {
    lock(this)
    {
      //Access instance variables
    }
  }
}

is "a problem if the instance can be accessed publicly". I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?


Source: (StackOverflow)

How does lock work exactly?

I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?


Source: (StackOverflow)

Advertisements

Lock, mutex, semaphore... what's the difference?

I've heard these words related to concurrent programming, but what's the difference between them?


Source: (StackOverflow)

What are the differences between various threading synchronization options in C#?

Can someone explain the difference between:

  • lock (someobject) {}
  • Using Mutex
  • Using Semaphore
  • Using Monitor
  • Using Other .Net synchronization classes

I just can't figure it out. It seems to me the first two are the same?


Source: (StackOverflow)

Why the Global Interpreter Lock?

What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?


Source: (StackOverflow)

Python: single instance of program

Is there a Pythonic way to have only one instance of a program running?

The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?

(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)

Update: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.


Source: (StackOverflow)

Java synchronized method lock on object, or method?

If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method?

Example:

class X {

    private int a;
    private int b;

    public synchronized void addA(){
        a++;
    }

    public synchronized void addB(){
        b++;
    }

}

Can 2 threads access the same instance of class X performing x.addA() and x.addB() at the same time?


Source: (StackOverflow)

Optimistic vs. Pessimistic locking

I understand the differences between optimistic and pessimistic locking*. Now could someone explain to me when I would use either one in general?

And does the answer to this question change depending on whether or not I'm using a stored procedure to perform the query?

*But just to check, optimistic means "don't lock the table while reading" and pessimistic means "lock the table while reading."


Source: (StackOverflow)

Reference for proper handling of PID file on Unix

Where can I find a well-respected reference that details the proper handling of PID files on Unix?

On Unix operating systems, it is common practice to “lock” a program (often a daemon) by use of a special lock file: the PID file.

This is a file in a predictable location, often ‘/var/run/foo.pid’. The program is supposed to check when it starts up whether the PID file exists and, if the file does exist, exit with an error. So it's a kind of advisory, collaborative locking mechanism.

The file contains a single line of text, being the numeric process ID (hence the name “PID file”) of the process that currently holds the lock; this allows an easy way to automate sending a signal to the process that holds the lock.

What I can't find is a good reference on expected or “best practice” behaviour for handling PID files. There are various nuances: how to actually lock the file (don't bother? use the kernel? what about platform incompatibilities?), handling stale locks (silently delete them? when to check?), when exactly to acquire and release the lock, and so forth.

Where can I find a respected, most-authoritative reference (ideally on the level of W. Richard Stevens) for this small topic?


Source: (StackOverflow)

mySQL Transactions vs Locking Tables

I'm a bit confused with transactions vs locking tables to ensure database integrity and make sure a SELECT and UPDATE remain in sync and no other connection interferes with it. I need to:

SELECT * FROM table WHERE (...) LIMIT 1

if (condition passes) {
   // Update row I got from the select 
   UPDATE table SET column = "value" WHERE (...)

   ... other logic (including INSERT some data) ...
}

I need to ensure that no other queries will interfere and perform the same SELECT (reading the 'old value' before that connection finishes updating the row.

I know I can default to LOCK TABLES table to just make sure that only 1 connection is doing this at a time, and unlock it when I'm done, but that seems like overkill. Would wrapping that in a transaction do the same thing (ensuring no other connection attempts the same process while another is still processing)? Or would a SELECT ... FOR UPDATE or SELECT ... LOCK IN SHARE MODE be better?


Source: (StackOverflow)

How to disable Home and other system buttons in Android?

I need to disable Home and other system buttons in my Android application.

Example: MX Player (see at Google Play) - you can press "lock" icon at player screen and it locks all hardware and software system buttons.

It works fine WITHOUT ROOTING.

I tested it on some devices with different Android versions. I tried to disassemble Kids Lock (plugin) but has no clue how it works yet.

I need same solution like the Kids Lock (plugin) for MX Player: - disable Home, Back and all other system buttons.

Any suggestions?


Source: (StackOverflow)

Only inserting a row if it's not already there

I had always used something similar to the following to achieve it:

INSERT INTO TheTable
SELECT
    @primaryKey,
    @value1,
    @value2
WHERE
    NOT EXISTS
    (SELECT
        NULL
    FROM
        TheTable
    WHERE
        PrimaryKey = @primaryKey)

...but once under load, a primary key violation occurred. This is the only statement which inserts into this table at all. So does this mean that the above statement is not atomic?

The problem is that this is almost impossible to recreate at will.

Perhaps I could change it to the something like the following:

INSERT INTO TheTable
WITH
    (HOLDLOCK,
    UPDLOCK,
    ROWLOCK)
SELECT
    @primaryKey,
    @value1,
    @value2
WHERE
    NOT EXISTS
    (SELECT
        NULL
    FROM
        TheTable
    WITH
        (HOLDLOCK,
        UPDLOCK,
        ROWLOCK)
    WHERE
        PrimaryKey = @primaryKey)

Although, maybe I'm using the wrong locks or using too much locking or something.

I have seen other questions on stackoverflow.com where answers are suggesting a "IF (SELECT COUNT(*) ... INSERT" etc., but I was always under the (perhaps incorrect) assumption that a single SQL statement would be atomic.

Does anyone have any ideas?


Source: (StackOverflow)

Locking Executing Files: Windows does, Linux doesn't. Why?

I noticed when a file is executed on Windows (.exe or .dll), it is locked and cannot be deleted, moved or modified.

Linux, on the other hand, does not lock executing files and you can delete, move, or modify them.

Why does Windows lock when Linux does not? Is there an advantage to locking?


Source: (StackOverflow)

Does a locked object stay locked if an exception occurs inside it?

In a c# threading app, if I were to lock an object, let us say a queue, and if an exception occurs, will the object stay locked? Here is the pseudo-code:

int ii;
lock(MyQueue)
{
   MyClass LclClass = (MyClass)MyQueue.Dequeue();
   try
   {
      ii = int.parse(LclClass.SomeString);
   }
   catch
   {
     MessageBox.Show("Error parsing string");
   }
}

As I understand it, code after the catch doesn't execute - but I have been wondering if the lock will be freed.


Source: (StackOverflow)

ZooKeeper alternatives? (cluster coordination service)

ZooKeeper is a highly available coordination service for data centers. It originated in the Hadoop project. One can implement locking, fail over, leader election, group membership and other coordination issues on top of it. Are there any alternatives to ZooKeeper? (free software of course)


Source: (StackOverflow)