File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes The question about LOCK,UNLOCK method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "The question about LOCK,UNLOCK method" Watch "The question about LOCK,UNLOCK method" New topic
Author

The question about LOCK,UNLOCK method

xin dong
Ranch Hand

Joined: Mar 24, 2003
Posts: 33
Hello,I'm going SCJD now.but there is a question I confused.
I use RMI to implements Client-Server connection.in assignment it said
-------------------------------------------
public void lock(int record)
The aim is to ensure that if two customers attempt to book a seat on the same flight concurrently, then the number of available seats is definitely reduced by two, unless there was only one seat, in which case, one customer will be advised at booking time that no more seats are available.
--------------------------------------------
but I found that modify method in Data class has been set synchronized.if one user modify the a record,the others will be blocked until he completed.it seems that it's no necessary to implement lock and unlock method.
any answer is apperciated
[ March 24, 2003: Message edited by: xin dong ]
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

but I found that modify method in Data class has been set synchronized.if one user modify the a record,the others will be blocked until he completed.it seems that it's no necessary to implement lock and unlock method.

Here is a scenario:
1. There is one seat left for flight F.
2. Client A reads the database and sees that 1 seat is left.
3. Client B reads the database and sees that there is 1 seat left.
4. Client A enters the modify() method, reduces the number of seats to 0, and exits the modify().
5. Client B enters the modify(), reduces the number of seats to 0, and exits modify().
6. Now your flight is overbooked. The airline bumps the passenger, notifies the Fly By Night agency, the agency fires you the programmer.
7. You can't find another job and enter homeless shelter. Your wife leaves you, your kids are dealing drugs to survive. On top of all, some superpower invades your country.
Eugene.
xin dong
Ranch Hand

Joined: Mar 24, 2003
Posts: 33
Thanks your answer,but I don't think so.any book should examine valid seats first.
here's my solution:
  • There is one seat left for flight F.
  • Client A reads the database and *user* sees that 1 seat is left.
  • Client B reads the database and *user* sees that there is 1 seat left.
  • Client A enters the modify() method,first check "seats = 1",then reduces the number of seats to 0, and exits the modify().
  • Client B enters the modify(), found that "seats=0",so sends user an information and exits modify().

  • John Smith
    Ranch Hand

    Joined: Oct 08, 2001
    Posts: 2937

    Client A enters the modify() method,first check "seats = 1",then reduces the number of seats to 0, and exits the modify().

    That will work, but it means that you will be adding businees logic to a completely generic modify() method of a completely generic class Data. Not a good idea.
    Eugene.
    aadhi agathi
    Ranch Hand

    Joined: Apr 29, 2002
    Posts: 263
    Originally posted by xin dong:
    Client A enters the modify() method,first check "seats = 1",then reduces the number of seats to 0, and exits the modify().
  • Client B enters the modify(), found that "seats=0",so sends user an information and exits modify().

  • [/list]

    ok , you have decided that there will be some kind of seats, which can be used by both A and B.
    1.think it in terms of layered architecture.
    Why should the lower layer(db) should be aware of the upper layer like reservation layer.
    If i say seats=1 in modify , i cant the Data class generically.say for example an employee data storage.
    hope this helps!


    Aadhi
    Arun Bommannavar
    Ranch Hand

    Joined: Jan 11, 2003
    Posts: 53
    Originally posted by xin dong:
    Thanks your answer,but I don't think so.any book should examine valid seats first.
    here's my solution:
  • There is one seat left for flight F.
  • Client A reads the database and *user* sees that 1 seat is left.
  • Client B reads the database and *user* sees that there is 1 seat left.
  • Client A enters the modify() method,first check "seats = 1",then reduces the number of seats to 0, and exits the modify().
  • Client B enters the modify(), found that "seats=0",so sends user an information and exits modify().


  • No, its not going to work.
    I have written some generic code below to illustrate the subtlety of multithreading.
    *****************
    public void bookSeats(int seats){
    int availableSeats = getAvailableSeats(); //Step 1
    if (availableSeats > seats) // Step 2
    modify(seats); //Step 3
    }
    public void modify(int seats){
    //code to reduce number of available seats
    }
    ****************************
    Thread 1.
    Client A executes Step 1. Finds availableSeats =1.
    Client A executes Step 2. The condition is true.
    Thread 2.
    Client B executes Step 1. Finds availableSeats =1.
    Client B executes Step 2. The condition is true.

    Thread 1.
    Client A executes Step 3
    Thread 2.
    Client B executes Step 3
    So if we started with 1 available seat, at the end of the scenario we are left with -1 seats available.
    Now if the "bookSeats" method is synchronised, step1, 2 and 3 are all executed by one client and then only another client can enter it.
    Regards
    Arun
    Arun Bommannavar
    Ranch Hand

    Joined: Jan 11, 2003
    Posts: 53
    Originally posted by xin dong:
    [QB]
    Client A enters the modify() method,first check "seats = 1",then reduces the number of seats to 0, and exits the modify().
    QB]

    Chek the following scenario.
    Thread 1.
    Client A enters the modify(), first checks "seats =1".
    Thread 2.
    Client B enters the modify(), first checks "seats =1"
    Thread 1.
    Client A reduces the number of seats by 1
    Thread 2.
    Client B reduces the number of seats by 1
    Regards
    Arun
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    To Arun : Sorry,the method is synchonized.thats means there is only 1 client can access the method
    .when A is executing method,B will be blocked until A complete it.
    what I want to know is:Since sun provides it.that means that lock method must be implemented.
    but I think synchonized method has had lock function.so I think it 's no necessary to implement lock method.
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    To Eugene
    I can provide a method named bookSeat.the code looks as:
    any Client wants to book seats uses this method.
    does it have same function with Lock()method?
    John Smith
    Ranch Hand

    Joined: Oct 08, 2001
    Posts: 2937

    I can provide a method named bookSeat.

    You are palnning to add this method to Data class? Bad idea, -- the responsibility of Data class is to access the database, not to implement business logic.
    Eugene.
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    the responsibility of Data class is to access the database, not to implement business logic.

    how do you think criteriaFind method in Data class?is there any business logic in it? at least it has to check the String user input.
    Eugene,I feel sorry,I think you mistake my meaning.I don't want to discuss where the method should be placed or what the Data Class should includes.
    I think there is somthing will prove that I can't simply set method synchronized instead of lock method.but no compellent proof appears as yet.
    John Smith
    Ranch Hand

    Joined: Oct 08, 2001
    Posts: 2937

    how do you think criteriaFind method in Data class?is there any business logic in it?

    No, none whatsoever, the criteriaFind() method should be completely generic, and it should work even if database schema changes.

    I think there is somthing will prove that I can't simply set method synchronized instead of lock method.but no compellent proof appears as yet.

    The proof is in the principles of good software engineering. To accomplish the business reuirements without lock/unlock, you would need to add your business rules to the modify() method of Data. This grossly violates the principle of separation of responsibilities among the classes. That's all.
    Eugene.
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    Thank you very much.Eugene,you are a warmhearted man.I think I have understand your meaning.
    thanks again.
    Max Habibi
    town drunk
    ( and author)
    Sheriff

    Joined: Jun 27, 2002
    Posts: 4118
    Originally posted by xin dong:
    Hello,I'm going SCJD now.but there is a question I confused.
    I use RMI to implements Client-Server connection.in assignment it said
    -------------------------------------------
    public void lock(int record)
    The aim is to ensure that if two customers attempt to book a seat on the same flight concurrently, then the number of available seats is definitely reduced by two, unless there was only one seat, in which case, one customer will be advised at booking time that no more seats are available.
    --------------------------------------------
    but I found that modify method in Data class has been set synchronized.if one user modify the a record,the others will be blocked until he completed.it seems that it's no necessary to implement lock and unlock method.
    any answer is apperciated
    [ March 24, 2003: Message edited by: xin dong ]

    Hi Xin,
    Let's start with the premise that a given client has thier own instance copy of the Data class. Thus, say we have three clients A,B,and C. Client A calls modify on his instance of the data object(we'll think of that as aata_A), and you're right, that is a synchronized call. However, that doesn't get you what you want. Why?
    Because when you synchronize a method, in this case, data_A.modiy(), what you get is that data_A won't be interupted while it's busy working. Remember, synchronizing a method is exactly the same thing as synchronizing on the this member variable. However, that's not good enough, because you need the various Data objects to coordinate with each other. How do you achieve that? One simple way is to provide a static HashMap(or WeakHashMap) that is shared by all instances of the Data class. Then, you explicitly synchronize on that Map in your lock/unlock methods.
    Think of it this way: you have three people at the gym, and they are all trying to run on the threadmill, but there is only one treadmill. So it's not enough that they coordinate thier own tasks: they need to coordinate the task of using the treadmill therwise, one on them might just bump the other on off . How is this accomplished? By synchronizing on the treadmill: that is, the single shared object. Does this make sense so far? How is that accomplished? By providing some kind of 'sign up sheet' in the form of the hashmap. Then, the given person could start sign the threadmill out and start running. When done, they would remove thier name from the sign out sheet, and let someone else have a go. Does this make sense so far?
    M, author
    The Sun Certified Java Developer Exam with J2SE 1.4
    [ March 25, 2003: Message edited by: Max Habibi ]

    Java Regular Expressions
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    One simple way is to provide a static HashMap(or WeakHashMap) that is shared by all instances of the Data class. Then, you explicitly synchronize on that Map in your lock/unlock methods.

    Thanks for your comment.but I'm unapprehensive..could you explain further?
    in other words. I don't know how to make use of your advice.
    Sure Vat
    Greenhorn

    Joined: Mar 25, 2003
    Posts: 6
    The problem here is very simple but made complicated due to confusion. I think most of the people have got the right opinion, but it become unclear due to the way of presentation. I am here trying to put all your comments in order 
    Initial question was - the method modify() is synchronized, but why we need a locking mechanism? A reply to it was to separate the business logic from the utility layer. {consider suncertify.db package as an utility package, used across many application}.
    The person, who raises this doubt, was considering only the present minimum requirement, but as per the requirements, a generic solution is expected.
    For better understanding, assume that the requirement is like this.
    [1] For all airlines, except "SpeedyAir" , it must work as per the requirement specified in the instruction. That is if there is one seat remaining and two people try to book simultaneously, only one should be allowed to book and the second must be notified about the non-availability.
    [2] For "SpeedyAir" reservation, along with above requirement, there is an additional condition - passenger must be above 18 years of age. {This is an additional requirement from my side, for a better explanation}
    Considering this as the requirement, it is not wise to code all these logic in the modify() method, though purpose can be met. So here the approach of design must be based on following facts..
    [a] Business rules can change frequently and system must be easily tuned with the new requirements
    [b] Reusability of classes { suncertify.db package usuage across applications}
    So considering the facts, we have to design as follows.
    Make the suncertify.db package very generic
    Provide a business class to handle the business rules, say a class suncertify.flight.Reservation
    When users try to reserve the seat, the request will be handed over to the Reservation class. It will check whether the request can be fulfilled. If so it will request for the service of the db package through the lock call. If the locking went successful, it will check for the seatavailability. If seats are available, the Reservation class will book a seat else throw an exception {say ReservationException}. At the end the business class will release the lock
    By doing so, the suncertify.db package will become very generic and it can be used for database operations across various projects.
    This is exactly what SUN try to convey, by coming up with the lock() & unlock() requirement. This requirement made us all to think and debate about its necessity and we learned a lot about good design approach. This is the best part in SCJD.
    So enjoy
    John Smith
    Ranch Hand

    Joined: Oct 08, 2001
    Posts: 2937
    Nice summary. To put it all in a short sentence, "Identify what can change and isolate it". Or, "Divide the responsibilities and conquer".
    Eugene.
    [ March 26, 2003: Message edited by: Eugene Kononov ]
    Max Habibi
    town drunk
    ( and author)
    Sheriff

    Joined: Jun 27, 2002
    Posts: 4118
    Originally posted by xin dong:

    Thanks for your comment.but I'm unapprehensive..could you explain further?
    in other words. I don't know how to make use of your advice.

    Sure. Here's the basic problem Xin. When though the modify method is synchronized, that's not sufficient to guarantee a safe threading strategy. Why? Because you need to synchronized on a different object all together.
    When you have a synchronized method, it is only synchronized for a given object instance. However, other clients could have other object instances, so it's irrelevant to them that your object instance is synchronized. I'll expand from here, but does this make sense?
    M, author
    The Sun Certified Java Developer Exam with J2SE 1.4
    M
    Max Habibi
    town drunk
    ( and author)
    Sheriff

    Joined: Jun 27, 2002
    Posts: 4118
    Originally posted by Sure Vat:
    The person, who raises this doubt, was considering only the present minimum requirement, but as per the requirements, a generic solution is expected.

    To be correct, that is not part of the requirements, and has not been for years, AFIW. IT is, however, a good guiding light.
    M, author
    The Sun Certified Java Developer Exam with J2SE 1.4
    xin dong
    Ranch Hand

    Joined: Mar 24, 2003
    Posts: 33
    yes sir ,perfect clear
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: The question about LOCK,UNLOCK method
     
    Similar Threads
    lock() and unlock() methods
    no need to lock! ??
    LockManger Issues ?
    Locks without Client IDs?
    lock and unlock