Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

For a travel booking web application, where there are 100 concurrent users logged in, should ticket booking and generating an "E-Ticket Number" be implemented by a "synchronized" or a "static synchronized" method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, are you aware of the difference between a static method and an instance method in general?

The only difference that synchronized makes is that before the VM starts running that method, it has to acquire a monitor. For an instance method, the lock acquired is the one associated with the object you're calling the method on. For a static method, the lock acquired is associated with the type itself - so no other threads will be able to call any other synchronized static methods at the same time.

In other words, this:

class Test
{
    static synchronized void Foo() { ... }

    synchronized void Bar() { ... }
}

is roughly equivalent to:

class Test
{
    static void Foo()
    {
        synchronized(Test.class)
        {
            ...
        }
    }

    void Bar()
    {
        synchronized(this)
        {
            ...
        }
    }
}

Generally I tend not to use synchronized methods at all - I prefer to explicitly synchronize on a private lock reference:

private final Object lock = new Object();

...

void Bar()
{
    synchronized(lock)
    {
        ...
    }
}

You haven't provided nearly enough information to determine whether your method should be a static or instance method, or whether it should be synchronized at all. Multithreading is a complex issue - I strongly suggest that you read up on it (through books, tutorials etc).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...