Synchronizing many reader threads with one writer thread?

Hi
I was wondering if there is a way in java to allow different threads to read an object simultaneously however to block them all only when the object is being updated. Here is an example:
I have the following object which is shared between many Servlet instances:
public class ActiveFlights
     private final HashMap<String,Flight> flights;
     private final Object lock;
     public ActiveFlights()
          flights = new HashMap<String, Flight>();
          lock = new Object();
     public void updateFlights(ArrayList<FlightData> newFlights)
          synchronized (lock)
               //some code which updates the HashMap
     public ArrayList<Flight> getSomeFlights()
          ArrayList<Flight> wantedFlights = new ArrayList<Flight>();
          synchronized (lock)
               //some code which selects flights from the HashMap
          return wantedFlights;
}Now all the Servlet doGet() functions call the getSomeFlights() method. There is also a Timer object which calls the updateFlights() method once every few minutes.
I need the synchronized blocks in order that the Timer doesn't try to update my object while it is being read by a Servlet however this is not optimal since it also causes each Servlet doGet() to block the others even though it would be possible for to doGet()'s to read the object simultaneously.
Is there a better way of doing this?
Thanks
Aharon

It is highly unlikely this is a real performance issue for you. Unless you know this is a bottle neck, you don't need to change your code.
However, as an exercise, you can just use ConcurentHashMap for lockless Map access. However, there is still a risk of getting a read in the middle of a write.
Instead you can take a snapshot copy of the Map and use this snapshot for reads. See below.
In term of coding style;
- I suggest you use the Map and List interfaces where ever possible.
- You don't need to create a seperate lock object, the Map will do the same job.
- Use can create the HashMap on the same line as it is declared removing the need to define a constructor.
public class ActiveFlights {
     private final Map<String, Flight> flights = new HashMap<String, Flight>();
     private volatile Map<String, Flight> flightCopy = new HashMap<String, Flight>();
     public void updateFlights(List<FlightData> newFlights) {
          //some code which updates the HashMap
          // this takes a snapshot copy of the flights.  Use the copy for reads.
          flightCopy = new HashMap<String, Flight>(flights);
     public List<Flight> getSomeFlights() {
          // take a copy of the reference, neither the reference, nor the map it refers to will change over the life of this method call.
          final Map<String, Flight> flightCopy = this.flightCopy;
          final List<Flight> wantedFlights = new ArrayList<Flight>();
          //some code which selects flightCopy from the HashMap
          return wantedFlights;
}

Similar Messages

  • Control many mac minis with one magic mouse

    Hello,
    I have installation with four macminis mounted to ceiling,
    I want to control and setup each of them without buying four magic mouses and keyboards.
    Is it possible to use only one magic mouse and magic keyboard to control all macminis?
    If not, is there any good solution for that?
    Thank you.

    Sure, turn on screem sharing under System Preferences -> Sharing. Then, connect to each of them using finder and share screen. So, one KB, one mouse, many minis. Monitor would be connected to the same machine that the KB and MOUSE are connected to.

  • Issue with read statement with one more key missing in mapping

    Hi All ,
    I have such data in two internals table :
    IT_bdc
    vbeln            posnr
    90000593     10
    90000576     10
    90000672     10
    90000672     20
    90000672     30
    it_konv
    kbetr          vbeln
    6250          90000576
    12160000          90000593
    500000          90000672
    600000          90000672
    700000          90000672
    My current program statement is :
    LOOP AT it_bdc.
    READ TABLE it_konv WITH KEY
          vbeln = it_bdocs-vbeln.
      currency =   it_konv-waers.
    endloop.
    as you can see the posnr is missing in it_konv how can i modify this read statement so
    that vbeln posnr from it_bdc should get correct kbetr from it_konv.
    Kindly help in this mapping.

    Hi
    sort it_konv by vbeln
    then
    loop at it_bdc.
    read table it_konv with key vbeln = it_bdc-vbeln binary search.
    if sy-subrc = 0.
    perform your logic/task.
    endif.
    endloop.
    also it depends what you want to do after reading it_konv.
    in my logic if there is a vbeln in it_konv which s present in it_bdc then sy-subrc will be 0
    and you can perform your logic.
    and if there will be no matching vbeln in it_konv then sy-subrc will not be 0.
    check the values in debugging.
    Thanks
    Lalit

  • Why does iTunes freeze up for minutes at a time when modifying INFO (CMD-i) ?  My files are not corrupted after it is done like many other threads i have readed.

    Why does iTunes freeze up for minutes at a time when modifying INFO (CMD-i) ?  My files are not corrupted after it is done like many other threads i have readed.  Sometimes it's changing the title of a movie or editing the season and episode number of a TV show ect.....

    Yup same here
    I am running the latest iTunes, the latest updates to the OS and on an iMac 3.4GHz Quad core i7 with 8GB of RAM and the music stored on local HDD.
    Still locks up iTunes for between 2 minutes up to 20 minutes.
    Really annoying.
    If you find a fix please, please let me know, I have just been throwing hardware at it with no joy at all

  • Synchronized execution of threads

    How do I synchronize the execution of two threads?
    I am using two threads, the main thread to handle input and output, and a secondary thread to execute third party procedural code.
    The main thread has to wait for commands from the procedural thread and then relay those to the client.
    While the client has control, the procedural thread has to wait and vice versa. I couldn't get this to work yet.
    Below is the simplest example I could extract from the code. I have tried it with java.util.concurrent as well but couldn't pause the main (servlet) thread with that, only threads in the thread pool.
    Your help will be greatly appreciated!
    Here is the code :
    [http://connexioncafe.info/java/SyncExample.java|http://connexioncafe.info/java/SyncExample.java]
    Thank you in advance!

    I'll try and post the code in three parts:
    * This is a simulation of a server.  It has two threads:
    * [1] main thread used for input and output (in this case communication with command line client).
    *      it could be a servlet in practice
    * [2] and a procedural thread for executing third party code (e.g. PHP)
    * The main thread start the procedural thread
    *      *the main thread waits
    * the procedural thread reads a stack, one item at a time
    * if the command in the stack is an input or output command
    * *the procedural thread sets the command on the main thread
    * *the procedural thread notifies/wakes up the main thread [A]
    * *the procedural thread waits
    * the main thread is woken up by the procedural thread [A]
    * *it executes the command as set by the procedural thread
    * *it sets the result on the message variable
    * *it notifies/wakes up the procedural thread
    * *the main thread waits for the next command from the procedural thread [B]
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class SyncExample {
    //a simple int value that is visible by both threads used for messaging
    public int message = -1;
    //a command that is passed between threads either executing on the client or server side
    public int command = -1;
    //all the possible commands
    public static final int DO_INPUT = 1;
    public static final int DO_OUTPUT = 2;
    public static final int DO_QUIT = 3;
    public static final int DO_STORAGE = 4;
    public static final int DO_PROCESS = 5;
    //commands with an int value greater or equal to SERVER_SIDE executes on the server side
    public static final int SERVER_SIDE = 3;
    //a lock used to wait() the procedural thread
    public final Object procLock = new Object();
    //a lock used to wait() the main thread
    public final Object mainLock = new Object();
    //a lock used to sync message value between threads
    public final Object msgLock = new Object();
    //a lock used to sync command value between threads
    public final Object cmdLock = new Object();
    //========================================================================== Procedural Thread
    public class ProcThread extends Thread {
    //some third party code that will be executed by this thread
    private AlgorithmI aProc;
    //some functions that will be used to execute the third party code
    private final SysFunctions sysFunctions;
    public ProcThread(AlgorithmI aProc, SysFunctions sf) {
    this.aProc = aProc;
    this.sysFunctions = sf;
    @Override
    public void run() {
    int cmd = 0;
    for (int i = 0; i < aProc.getStack().length; i++) {
    cmd = aProc.getStack();
    if (cmd >= SERVER_SIDE) {
    switch (cmd) {
    case DO_STORAGE:
    sysFunctions.storage();
    break;
    case DO_PROCESS:
    aProc.calculate();
    break;
    default:
    break;
    } else {
    setCommand(cmd);
    //TODO: RESUME MAIN THREAD SO THAT IT CAN COMMUNICATE WITH CLIENT
    synchronized (mainLock) {
    mainLock.notify();
    //TODO: PAUSE THIS PROCEDURAL THREAD UNTIL MAIN THREAD HAS COMPLETED THE COMMAND
    synchronized (procLock) {
    try {
    procLock.wait();
    } catch (InterruptedException ex) {
    //interrupted
    switch (cmd) {
    case DO_INPUT:
    aProc.setValue(getMessage());
    break;
    case DO_OUTPUT:
    break;
    default:
    break;
    * An interface that has to be implemented by third party procedures
    public interface AlgorithmI {
    public void calculate();
    public int[] getStack();
    public void setValue(int message);
    //written by someone else which I do not have control over
    public class ThirdPartyProcedure implements AlgorithmI {
    //just two values that will be added together
    private int value1 = 0;
    private int value2 = 0;
    // an array of commands that will be executed by ProcThread
    private int[] stack = {
    SyncExample.DO_STORAGE,
    SyncExample.DO_INPUT,
    SyncExample.DO_STORAGE,
    SyncExample.DO_INPUT,
    SyncExample.DO_STORAGE,
    SyncExample.DO_PROCESS,
    SyncExample.DO_STORAGE,
    SyncExample.DO_OUTPUT,
    SyncExample.DO_QUIT};
    public synchronized void setValue(int value) {
    if (value1 == 0) {
    value1 = value;
    } else {
    value2 = value;
    public void calculate() {
    setMessage(value1 + value2);
    public int[] getStack() {
    return stack;
    // continued below...
    Edited by: datahpile on Aug 20, 2010 6:27 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Thread Count Queue Length in Negative and Too many standby Thread

    We are using Weblogic server 9.2.2 with 1 admin server and 4 managed server . Currently in one of the servers I could observe that there are around 77 standby threads.
    Home > Summary of Servers > server1 > Monitoring > Threads > Self-Tuning Thread Pool
    I could see that the "queue length" is negative (-138) and self tuning standby thread count is 77. Large number of threads STANDBY thread persists during the busy time of the business hours where as other servers are fully utilized.
    Is it normal to have negative queue length and so many STANDBY threads? As for JMS queue negative oracle had already acknowledged that it is a bug. Thanks.
    Edited by: 855849 on May 1, 2011 7:19 AM
    Edited by: SilverHawk on May 12, 2011 8:12 AM

    Yesterday an Oracle Consultant acknowlegded that it is a bug. There was a patch issued for Negative count in the JMS queue count and now this. Thanks for the reply by the way.

  • Synchronized method in Thread

    Hi All,
    Can u show how to use synchronized method in thread.So that only one thread can access the resource at a time so that other needs to wait.Can u give me a sample example regarding this.So that it will be much more useful.
    Thanx,
    m.ananthu

    synchronized public void method1(){
    // code for the method....
    }Hope it helps.

  • How many Ipods can you use with one Itunes account?

    How many iPods can you use/sync with one iTunes account?

    PT wrote:
    Macistotle wrote:
    Unless you have DRM still haunting your tunes ... Then you can only use those songs on 5 devices. Otherwise, connect as many as you like (as stated above).
    No, you can sync your DRM tracks to an unlimited number of iPods (but only authorized to play on 5 different computers/user accounts)
    Patrick
    So I can sync two iPods to my iTunes account and sync the same digital copy movies that come with some o' my DVDs to both ipods? Do movies make a difference really, DRM-Wise? Thanks in advance.

  • On how many pc's may I install Lightroom with one license?

    I'm planning to purchase Lightroom 5, but I need to know on how many pc's I can install the software when having a single license. Note that I will be the only user, but I do need it to work on both my desktop pc, as well as on my laptop.
    How many pc's is the limit?

    Yes the license is cross platform PC or Mac. Limit to two instalations with one in use at any point in time. No activate/deactivate Like other Photoshop applications you just monitor your own use you can uninstall from one computer and install on another as many times you need.

  • How many PCs can I use with one Creative Cloud subscription?

    How many PCs can I use with one Creative Cloud subscription? For example I currently use Lightroom on a home PC with 2 large screens, but use a laptop or iPad when travelling. Does one monthly subscription cover all 3 or do I need 3 separate subscriptions ?

    You are welcome!
    P.S. when using the adobe forums, please mark helpful/correct responses of Staff or helper, if there are any. 

  • How many computers can be upgraded with one 1 purchase mountain lion?

    How many computers can be upgraded with one 1 purchase mountain lion?

    What if I have a Mac with a different apple ID. Can I sign out of that ID and sign in with my other ID and still download it with one purchase?

  • How many downloads do you receive with one purchase of the Illustrator cs6?

    How many different computers can you download the program with one purchase?

    Ok, what illustrator should I purchase ( not monthly fee) to work on my imac osx 10.9.2 and my macbook pro osx 10.9.2
    Thanks. Julian
    Sent from my BlackBerry 10 smartphone on the Verizon Wireless 4G LTE network.

  • I'm buying a new MAC.  How many machines can you associate with one CS Cloud account?

    I'm buying a new MAC.  How many machines can you associate with one CS Cloud account?

    You can install the software on as many computers as you like.
    However you can only activate the software and use it on a maximum of two computers at any one time.

  • How do I rename many photos all at one time with one click?

    I have got many photos of a sery and want to rename it all with one click only (instead of clicking through it all in single actions and wasting time).
    How can I rename many pictures/photos all together with one click only? -
    1) I have OS X Yosemite
    2) Aperture
    3) Automator App
    to use for this purpose, but I do not see through with any of it.
    Detailed Support for 1) and 2) and 3)  please!
    jona li

    Here is an article on how to batch rename files in Yosemite using just the Finder. This is a new feature in Yosemite. See if this article helps you get your files renamed.

  • Possible?Multi-Entity View Object with one Entity Object that is Read-only.

    I know this sounds crazy, but I would like to create a multi-entity view object, where one entity object is based on a table in my application (we'll call it "Users", which basically stores the primary key for the person from the institutional people database), and the other table is a entity object based on a view of the institutional people database table (read only access), which we can call "People".
    I know that since no updates will be done to the People table, it really should be a read-only View Object, but I would lose the ability to sort on attributes like Last Name, Hire date, etc, since those would be transient attributes in my ViewObject for the Users. By having People as an entity object, I can then create a multi entity view object and have the ability to join Users to People and be able to sort on the above mentioned fields (like Last Name).
    The problem is that when I use the JDev (I'm currently using 10.1.2.1) AppModule BC4J tester, when I click on the multi-entity view object that I added to the AppModule it gives me an error:
    oracle.jbo.RowCreateException) JBO-25017: Error while creating a new entity row for People.
    ----- LEVEL 1: DETAIL 0 -----
    (java.lang.InstantiationException) null
    I have tried to change all the attributes to updateable in my entity object, but no create method, and I have tried to make them all read-only, but no effect, I get the same error (probably because the People view is read-only in my schema).
    Is there a way to change the entity object so that it will not try to create a new row when it runs the Tester? So that the multi entity view object behaves more like a view link, but gives me the added bonus of being able to sort on the Last Name column from the People table?
    Thanks for any help on this subject...at worst, I will have to use the view link method to get the job accomplished, but it would be "cooler" if this would work!
    Jeremy.

    Steve, thanks for your quick response to my question.
    To answer your questions, I was trying to create the Multi-entity View Object to give me more flexibility when working with my User table, and my People view. The flexibility I desired was that I would be able to sort my Users based on attributes in the People view. This is not possible when the there is only one Entity in my VO, and the People view data are all transient attributes, because they are not in the SQL statement.
    Ultimately, after working with one of my colleagues, we decided to use the approach that you mentioned by creating a read-only VO with the SQL query we want to display to the user (contains both User and People data fields), and then use a different ViewObject when performing other actions on the User Table (such as inserts/updates/deletes). By using the setWhereClauseParam() method in the handleLifeCycle() for the JSP page, we should be able to navigate between the different View Objects, so that the user does not see any difference.
    Thanks! Oh, and by the way, I have read your article you included before, and I have used it many times before to tune my View Objects! Thanks!

Maybe you are looking for