Helpful hint while multi-threading

Hi all
This had me stupmed for a little while. A multi-threaded program I'd been working didn't appear to be working correctly. I noticed this was because it looked like the thread never made it to its run() method. The cause of this was the fact id overridden the start() method of the thread without including this.run() at the end. The symptoms of this happening aren't obvious though, and it can be quite puzzling. I hope this gets added to any FAQs etc, or solves someones problem.

And if, for whatever reason, you do need to override start(), you should not call this.run() at the end, you should call super.start() !!!
If you call this.run() at the end, you are having the current thread go and do the run method.

Similar Messages

  • Help with understanding multi-threaded code

    Hi Everyone,
    I am currently reading a book on multi-threading and up until recently I have been able to understand what is going on. The thing is the complexity of the code has just jumped up about two gears without warning. The code is now using inner classes which I am trying to develop an understanding of but I am not finding it easy going, and the book has been lite on explanations. If anybody can help with the following code it will be really appreciated.
    public class SetPriority extends Object
         private static Runnable makeRunnable()
              Runnable r = new Runnable()
                   public void run()
                        for(int i=0; i<5; i++)
                             Thread t = Thread.currentThread();
                             System.out.println("in run() - priority=" + t.getPriority() +
                                          ", name=" + t.getName());
                             try{
                                  Thread.sleep(2000);
                             }catch(InterruptedException x){
                                  //ignore
              return r;
         public static void main(String[] args)
              Thread threadA = new Thread(makeRunnable(), "threadA");
              threadA.setPriority(8);
              threadA.start();
              Thread threadB = new Thread(makeRunnable(), "threadB");
              threadB.setPriority(2);
              threadB.start();
              Runnable r = new Runnable()
                   public void run()
                        Thread threadC = new Thread(makeRunnable(), "threadC");
                        threadC.start();
              Thread threadD = new Thread(r, "threadD");
              threadD.setPriority(7);
              threadD.start();
              try{
                   Thread.sleep(3000);
              }catch(InterruptedException x){
                   //ignore
              threadA.setPriority(3);
              System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority());
    }My greatest challenge is understanding how the makeRunnable() method works. I don't understand how this inner class can be declared static and then multiple "instances" created from it. I know that I have no idea what is going on, please help!!!
    Thanks for your time.
    Regards
    Davo
    P.S.: If you know of any really good references on inner classes, particularly URL resources, please let me know. Thanks again.

    Yikes!! The good news is that you're unlikely to see such convoluted code in real life. But here we go.
    "private static Runnable makeRunnable()" declares a method that returns objects of type Runnable. The fact that the method is declared "static" is pretty irrelevant - I'll describe what that means later.
    The body of the method creates and returns an object of type Runnable. Not much special about it, except that you can give such an object to the constructor of class Thread and as a result the run() method of this Runnable object will be called on a new thread of execution (think - in parallel).
    Now the way it creates this Runnable object is by using the "anonymous inner class" syntax. In effect the method is doing the same as
    public class MyNewClass implements Runnable {
        public void run() {
            // All the same code inside run()
    public class SetPriority {
        private static Runnable makeRunnable() {
            Runnable r = new MyNewClass();
            return r;
        // The rest of the original code
    }Except you don't bother declaring MyNewClass. You're not interested in defining any new method signatures. You just want to create an object that implements Runnable and has certain instructions that you want inside the run() method. Think of the whole approach as shorthand.
    Think about this for a while. In the mean time I'll write up the "static".

  • Refreshing Screen while Multi-Threading

    I am trying to refresh a GUI while calling a class that extends the Thread class.My code looks similiar to this:
    myThreadingClass mtc=new myThreadingClass();
    mtc.start();
    while(mtc.isAlive()){
    repaint();
    invalidate():
    The isAlive() is never returning false! ? ! I somehow need to do the repaint while waiting for the thread to finish. I had a mtc.join() before that worked and went on in the program, but I did not have any way to refresh the GUI with the mtc.join().
    Any one have any good ideas?

    I need to keep refreshing the screen, and from what I understand invokeLater(Runnable r) will invoke the run() after other processes have finished, by not while the run() is in progress. You can tell me if I am correct, or if the GUI thread will automatically repaint while the run() is in progress? I would greatly appriciate this. I can't find helpful information on this topic!

  • Program Crashes while multi-threading

    Hi Gurus:
    I am working on a program where I am running multiple JInternalFrames inside a JFrame. Each JInternalFrame starts a new thread (when the OK button is pressed). The thread calls a native (C++) method, which interfaces with another API (CAD).
    Problem is that when I run two frames together, my program crashes. If I wait for one frame to complete the process and then start the second one, everything works fine. I am not sharing any data between the threads. I even put a synchronized access modifier in front of the method that is causing the crash, to no avail. Don't know what else to try. I also ran the program in two different processes with only invoking one frame in each process, and it worked fine.
    The program either crashes with no error message, or sometimes it gives this error:
    -------------- Start of error --------------------------
    Another exception has been detected while we were handling last error.
    Dumping information about last error:
    ERROR REPORT FILE = (N/A)
    PC = 0x22ABDFFD
    SIGNAL = -1073741819
    FUNCTION NAME = (N/A)
    LIBRARY NAME = (N/A)
    Please check ERROR REPORT FILE for further information, if there is any.
    Good bye.
    ----------- End of error -------------------------------
    Any help would be appreciated.
    Regards,
    Kamran

    I also got that error - sometimes.
    Now I get something like this :
    An unexpected exception has been detected in native code outside the VM.
    Unexpected Signal : 11 occurred at PC=0x403bce8e
    Function name=__libc_free
    Library=/lib/libc.so.6
    Dynamic libraries:
    08048000-0804c000 r-xp 00000000 08:01 17180 /usr/java/jdk1.3.1_01/bin/i386/native_threads/java
    0804c000-0804d000 rw-p 00003000 08:01 17180 /usr/java/jdk1.3.1_01/bin/i386/native_threads/java
    40000000-40016000 r-xp 00000000 08:01 446282 /lib/ld-2.2.2.so
    40016000-40017000 rw-p 00015000 08:01 446282 /lib/ld-2.2.2.so
    and so on.
    I got an application which starts 50 threads (sometimes I start 60 or 30, just testing right now).
    Do you've got RedHat? And Kernel 2.4.2-2smp?
    I don't know how I got rid of your error, but now I got that one...
    Anybody who has experiences with that?
    THX,
    Peter

  • Need help to do multi-threading

    Can some one help me in creating an application that constantly polls the specified local directory for any new XML files. When an XML file is detected, it will create a new thread to handle the processing of the file, it will then assign the XML file to the new thread, and move the XML to temp directory.

    despite the few information about your program, the usage of timers seems be the best choice:
    import java.util.*;
    public class MainAppClass
         MainAppClass()
              Timer dirCheck = new Timer();
              long CHECKING_INTERVAL = 20000; // milliseconds
              // you may also include parameters in the TimerTask extended class
              // like the list of directories, etc.
              DirListener dirListener = new DirListener();
              // Now you schedule the TimerTask execution
              dirCheck.schedule(dirListener, 0, CHECKING_INTERVAL);
    class DirListener extends TimerTask
         public void run()
              // here you verify the list of directories
              // and launch one thread for each XML file
              // founded in these directories
    }take a look in the java.util.Timer and java.util.TimerTask classes

  • LabVIEW built DLL's in a multi-threaded C++ app, Help Needed!

    I'm working on a software application that is being developed
    primarily in C++. There is a component of this larger application,
    however, that is being developed in LabVIEW (for several reasons that
    I won't dive into here). This LabVIEW code is therefore executed
    within a C++ wrapper class that calls a LabVIEW built DLL.
    All this was fine and dandy, untill we decided to multi-thread our C++
    application. As a result, the LabVIEW DLL now gets called from
    multiple threads simultaneously. From all of my testing, it appears
    that resource locking is occuring such that only one thread has access
    to the .dll at a time. If I make the .vi used to define the dll
    function prototype as non-reentrant then this is what we see. As an
    example, say we have 3 threads all calling the same .dll method call.
    Thread 1, 2, and 3 all call the .dll within a few milliseconds of each
    other. Thread 1 completes the .dll call after X milliseconds. Thread 2
    completes the .dll call after 2X milliseconds, and thread 3 completes
    after 3x milliseconds.
    Now, changing the vi to reentrant, and running the same test, we see
    Thread 1, 2, and 3 all complete the .dll call in 3x milliseconds.
    While the fact that they now take the same amount of time to complete
    would lead you to believe they are happening in parallel, the fact
    that it takes 3x milliseconds as opposed to X milliseconds means they
    are not.
    Has anyone ever dealt with these issues before? Is it possible that
    messing with the "execution system" for the vi will have an affect?
    What if different .dll methods but still attached to the same .dll are
    called from different threads? Same behavior? Is it a lost cause? Is
    there no way to make code within a single LabVIEW built .dll run in
    two different threads at the same? From what I understand this is
    easily doable with a normal (non-LV built) .dll.
    Please, if anyone has any advice in this area, let me know!!!
    Much appreciated,
    Jesse Hurdus

    Duplicate post.

  • HELP!....GUI crashes when i call a multi-threaded program from it

    Hi..I have encountered a problem in my end of year project, which i cant see to solve. The problem is i am starting a multi-threaded program for a JButton on a GUI. All though this starts the other program it crashes the GUI completely how do i stop this.
    this is the code i use to call the threaded program.
    public void actionPerformed(ActionEvent e)
    Object target=e.getSource();
    String line = new String();
    if( target==b1 )
         try
    cl = new client();
         cl.startup();
         catch(Exception ex){ex.printStackTrace();}
    thanks Mike

    No there is no exceptions being given. this is one of the reasons why i dont no what to do. i thought myself that the threaded was taking all the resources and not going back to the GUI. if this is the case is there anyway that i can call back the GUI and keep the threaded program running?
    thanks
    mike.

  • Helpful hints for new Creative Zen MP3 2/4/8/16/32 GB (flash) Users On

    Summary of helpful hints (from this forum and me) for new Creative Zen MP3 2/4/8/6/32 GB (flash) Users Only!
    Rev..
    Date: 4/28/2008
    Author: ZenAndy
    Creative terminology:
    MP3 Player Recovery Tool - A program that resolves the majority of player problems quickly.
    One click is all it takes to update your player to the latest available firmware, and to give your player a clean bill of health.
    Link: http://www.creative.com/products/mp3...me.asp region=
    Note: You can also go to "Creative" "Support" "downloads" choose your MP3 Player type to obtain the latest firmware and software releases.
    Note: On your Zen you can look under "System" & "Information" and then compare the firmware download
    releases OR you can have the "MP3 Player Recovery Tool" (above) do it for you automatically.
    Note: Creative Zen 4/8/6 GB "MP3 Recovery Tool" DOES NOT stop on a firmware comparison match.
    Note: All firmware releases/revisons for the 4/8/6 GB Zen also works (is the same as) for the 2 GB & 32 GB Zen.
    Recovery Mode - If you experience one or more of the following symptoms, it is recommended that you boot the player into its unique Recovery Mode, and then clean up, format or reload the firmware.
    . The player is not detected in Creative MediaSource or Windows Media Player
    2. The battery does not last as expected
    3. Your computer stops responding during file transfers
    4. There is a power outage during file transfers
    5. There is an error about firmware
    6. LCD displays a "Firmware Problem" message
    7. Your player is not responding.
    8. The player is performing erratically.
    Getting Started
    . Load your Creative Zen software from CD FIRST and BEFORE plugging the Zen MP3 player, using the short cable, into the PC USB port to charge it.
    2. Try charging the Zen MP3 player directly from the USB port on the PC. If not, make sure the USB Hub you are using is adequately powered to provide full charging current to the Zen player. Also, try to have the Zen MP3 player as the only USB device, if possible, on the USB hub.
    Some/most Creative Zen flash MP3 Music players come "fully discharged" so, in the mean time, just read the manuals.
    FULLY charge the Zen MP3 player for several hours (~4.0 hrs max) until the battery symbol is NOT flashing AND the battery symbol/icon has a small plug/key symbol in the middle.
    After the first full charge - additional charging is much quicker about 2 /4 hours. (From 0% empty to full)
    3. Go to Creative/Support/Downloads and check for the latest software releases for the Creative Zen. Then check on your Zen MP3 player under System/Information for your firmware revision. Make sure you have the latest software downloaded on your PC and firmware on your Zen MP3 player. < Latest revision [.2.0] 28Feb08>
    OR
    You can run MP3 Player Recovery Tool - see above.
    4. In some cases you might have to do the Recovery Mode "paper clip reset" to get the Zen MP3 flash player started.
    See the Zen User's Guide FAQ. The paper clip reset hole is on the bottom edge below the music pause/run switch.
    (Not the slotted mic hole on the top edge of the player near the earphone jack and SD card slot!!!)
    5. My preference is to have the player shutdown/off before inserting and removing the earphone/headphone plug.
    Recovery Mode Using The Paper Clip OR
    Alternati've Method For Recovery Mode Without The Paper Clip.
    Why use it's
    If you experience one or more of the following symptoms:
    . The player is not detected in Creative MediaSource or Windows Media Player
    2. The battery does not last as expected
    3. Your computer stops responding during file transfers
    4. There is a power outage during file transfers
    5. There is an error about firmware
    6. LCD displays a "Firmware Problem" message
    7. Your player is not responding.
    8. The player is performing erratically.
    Save a copy of your player's content, if possible, before cleaning up the memory!
    Recovery Mode Using The Paper Clip Reset Method
    #. Turn off player if not already turned off
    #2. Press/hold play/pause button. If you accidentally release
    the button, start this reset procedure over again.
    #3. Gently push the end of a metal paper clip into the reset hole on
    the botton edge below the play/pause switch.
    (Do not use the slotted mic hole at the top edge near the earphone jack)
    #4. Slide the on/off/lock switch towards the on position - slide it to the botton hold
    until the display lights up and then release.
    #5. The recovery mode screen appears and four menu items are shown - see below
    <Alternati've Method For Recovery Mode Without The Paper Clip>
    #. Turn off player if not already turned off
    #2. Press/hold play/pause button. If you accidentally release
    the button, start this reset procedure over again.
    #3. Slide the on/off/lock switch towards the on position - slide it to the botton hold
    until the display lights up and then release. Be patient and wait!
    #4. The recovery mode screen appears and four menu items are shown:
    < Clean Up> - cleans, rebuilds and reorganizes your player's memory and restores it to optimal efficiency.
    When the cleanup is complete, select Reboot. Your player restarts and starts rebuilding its music library.
    Note: Your player's firmware is reset to default settings after your player's memory is cleaned up.
    Note: This procedure the hide/show password is reset.
    <2 Format All>- Warning - Formatting your player erases all content on your player's memory and resets your player's firmware to default settings. If possible, back up all data on your player before proceeding.
    Also, you can do this from the PC see Zen User's Guide. FAQ
    <3 Reload Firmware> - Caution !!!! Selecting Reload Firmware erases your player's firmware.
    DO NOT select Reload Firmware unless you have downloaded a newer firmware version for your player, or have been advised to do so by Creative Customer Support.
    Note: My advice when loading/replacing firmware is to connect directly
    to the PC USB port without using a USB hub.
    <4 Reboot> Restarts the player just like the "on/off/lock switch" when switched ON.
    Note: Having NO battery energy/charge/juice this procedure will not work.
    Lithium-Ion Polymer Battery Hints
    Ref:
    http://www.omnica.com/omniview_electronics2.htm
    http://en.wikipedia.org/wiki/Lithium_ion_battery
    . Allow the battery to completely discharge from time-to-time then recharge it fully.
    2. Lithium-Ion batteries loses about 5%- 0% capacity per month.
    3. Lithium-Ion polymer batteries have about 300-500 discharge/charge cycles.
    4. A half full battery indication (50% @ /2 the battery color) used up about 24 hrs worth of battery. Below 50% the indication goes fairly fast to the max of 30 hrs. Note: The battery level indication seems non-linear through out its range.
    5. Battery is Empty~0% - warning screen will appear on LCD and player might shutdown.
    6. Battery is Full- 00% with battery symbol NOT flashing AND plug/key symbol in the center of the battery.
    7. It takes about 2 /4 hours to charge the battery from empty to full.
    8. It takes about 4 hours max to charge a "New" Zen player shipped from the factory.
    9. There is a battery manufactuer's failure rate, which is normal ~ % or less, in which the Lithium-Ion Polymer battery refuses to charge. Creative, ships the Zen MP3 players with some or no charge so there is very small probability that you could have one. I call it the "Deep Six Discharge Battery" Contact/call Creative for replacement.
    Documentation
    There are several pieces of documentation you might need to read to fully understand and use your Creative Zen MP3 flash player to its fullest capabilities.
    #. Zen Users Guide "English" - For Zen MP3 Player - download from Creative/Support/Product documentation
    #2. Zen Quick Users Guide /Front/Back - download from Creative/Support/Product documentation
    #3. Sync Manager (Creative Zen) Click on sync symbol on PC task bar then help
    #4. Creative Zen Media Explorer - Just look under the main help menu
    #5. Windows Media Player <if used>(Microsoft)Use the help files with this program.
    General Tips to increase/decrease the playing time on your Creative Zen flash player.
    <Creative Battery Spec: 5 Hrs. Video & "UP TO" 30 Hrs. Audio/Songs>
    Please do the following:
    . Volume control lower/higher - higher volume settings will decrease playing times. This is logical. More output "volume power" decreases the battery juice.
    2. Audio Settings: EQ, Smart Vol, & Bass Boost will effect your playing time but I believe they are not critical as the Volume & Bit Rates(28 kbsp and others) / File Format (MP3,WMA) & Lock Switch.
    3. Bit Rates & File Formats Do Matter. Bit Rates and File formats will increase/decrease your playing time.
    Per Catherina-CL
    "WMA files will use up more power than MP3 files, and higher bitrates more so than standard ones (like 28kbps MP3). Best thing to do is rip an album in 28kbps MP3 and leave it playing in a loop on a normal volume level. See how long the battery lasts then."
    Please Note: The main difference between MP3 and WMA is the compression. According to Microsoft a 64KBPS WMA file is the same quality 28KBPS MP3. This is of course up to a person's preference but you may find you can get better compression out of WMA.
    4. FULLY CHARGE your Zen. This means the battery symbol is NOT flashing AND there is a plug/key symbol embedded within the battery symbol. The battery is 00% FULL under BOTH conditions. Having just the battery symbol all green will not do it.
    From the link:
    http://www.omnica.com/omniview_electronics2.htm
    Regarding lithium-ion shelf life, one of our engineers recently met with a battery-house representati've. It has come to their attention that repeated charging and re-charging of a less than fully discharged Li-ion cell affects the battery "gas gauge" included with many devices. Over a number of cycles there is a resultant loss in accuracy. Frequently, the indicated remaining charge has little relationship to the actual amount of life left in the cell! Fortunately, according to the battery expert, the gauge will reset itself if the battery is allowed to completely discharge from time-to-time.
    5. Having different types of earphones/headphones will increase or decrease the playing time by how much "electronic load" the earphones/headphones create on the Zen player. There are some power hungry earphones/headphones out there.
    The 6 ohm earbuds conserves battery power more than the 32 ohm earbuds supplied by Creative. (About 0% more)
    6. Always, always lock your Zen player while playing music. This cuts off the power drain from the color 2.5" LCD and blank the LCD screen. After all, you can't read the LCD screen if it is in your shirt pocket and playing music!
    7. Make sure you have the latest firmware upgrades in order to get the best of your Creative Zen Flash MP3 Player.
    Troubleshooting
    Your Creative Zen is extremely complex.
    Check this link to peek inside player http://www.anythingbutipod.com/archi...isassembly.php
    Also, this link:
    http://arstechnica.com/journals/hard...ssor-behind-it
    There could be a million things that could go wrong with your player so you will not be the FIRST or LAST to have a problem. Keep in mind, there are many, many others that have the Zen with no problems whatsoever. Things happen, but Creative is there to help.
    Dropping a Zen or any other player might/will/possibly ruin the player for good!!!
    Since this player is solid-state (no moving parts e.g. mini-disk dri've) then the only thing that will keep it from running for years is the non-user replaceable Lithium-Ion battery. I will concentrate on some troubleshooting tips which are battery related but I hope you have already the latest firmware downloaded and installed on your player
    Battery - Lithium-Ion Polymer
    #. Battery won't charge "out of the box" new player.
    A. First, read above "Getting Started"
    B. Next, try a different USB mini cable.
    C. Next, there is a battery manufactuer's failure rate < %, in which the Lithium-Ion Polymer battery refuses to charge.
    Creative, ships the Zen MP3 players with no charge so there is very small probability thatyou could have one.
    I call it the "Deep Six Discharge Battery" Call / Contact Creative.
    #2. Battery won't charge properly after using the player for some time.
    A. When you plug in your player into the USB port via mini USB patch cable, the connection resets the player to the "docked screen" with the battery level gas guage , in the right hand corner.
    Sometimes this action does not reset the player properly but there is no indication to you that the player is charging.
    Just disconnect/connect the USB cable again.
    B. Sometimes, the Zen player gets confused and you have to do a Recovery Mode "paper clip reset" which forces the player into a "special menu screen" to clean-up the player and to reset the player which allows showing the "docked screen" while charging the unit. See Zen User's Guide for explicit instruction und FAQ.
    C. Since the Zens came out late in 2007, the maximum of 300-500 charge/discharge should not apply YETbut users beware, as with any other Lithium-Ion Polymer battery it will not charge fully "like new"because of a " fixed shelf life" (2-3 yrs) OR too many charge/discharge cycles. A battery replacement is in order.
    Methods of charging the Creative Zen MP3
    . The short mini-standard USB cable provided by Creative from the factory. Plugs into a PC USB port.
    2. Uni'versal Power Adapter (Creative) plugs into the wall. Works "anywhere in the world"
    Note: Different countries have different wall AC voltages and hertz requirements. This has adapters for different countries/locations wall outlets and a uni'versal power supply for all voltage and hertz requirements.
    Note: This is a heavy duty high/fast charging wall outlet charging adapter. (2400 ma)
    3. Auto/Vehicle 2 VDC charger (Creative) or other compatible vehicle 2 VDC to USB charger.
    4. EARHUGGER IPOD POWER POD - MP3-8370 (White compact module)
    http://www.earhugger.com/powerPod.html
    http://www.amazon.com/Earhugger-MP3-.../dp/B000QTTKSS
    This compact module will solve all the following travel modes and conditions:
    . Camping, hiking or outdoor travel - no PC or noAC or maybe no auto/car.
    2. Airplane travel - no PC or no AC or no auto/car.
    3. Train/subway travel - no PC or no auto/car
    4. Car travel - no PC or no AC
    5. Foot travel - no PC or no AC or no auto/car
    It uses 4 ways to charge the Zen:
    . Retractable mini-standard USB cord for PC charging. <--- does not communicate with PC! - only for charging
    2. Retractable mini USB cord for auto/vehicle charging (Fused)
    3. Retractable mini USB cord for wall 0-20 VAC 50/60Hz charging. (non-international use plug style)
    4. 9 VDC battery terminal for using standard alkaline 9 VDC or high ma Lithium 9 VDC to charge the Zen via
    mini USB cable. Note:You might need several alkaline batteries to charge the internal 550 ma hr Zen battery!
    Great for remote destinations.
    5. Rechargeable portable battery packs.
    Black & Decker has several "Power To Go"models CPI0B-C & CPI20XB (not for international use because of 20 AC 60Hz only charging wall wart)
    Note: There are other brands that also do this method of charging.
    http://www.blackanddecker.com/Produc...Path=4033.4040
    You charge this portable NiMH battery pack from the AC wall outlet so you can carry with you on trips to charge the Zen.
    6. Mobile phone chargers. Some have a mini-USB plug for charging the phone but it could be used to charge the Zen BUT BEWARE IT COULD RUIN THE ZEN IF IT IS NOT COMPATIBLE! The output should have a voltage of 5 VDC +- 5% (4.75-5.25 VDC) ON THE PROPER MINI-USB PINS and a charging current at least 200 ma to 2400 ma. See this forum for the recommend phone phone chargers to use with the Zen.
    Note: You are charging an internal Lithium-ion polymer 550 mahr battery in the Zen so the lower the charging current the longer it takes to charge.
    Note: You will find that charging the Zen from the wall charger is much faster than the "current limited" charging on the standard PC USB port.
    Note: For diagnostic purposes and emergency charging of the Zen it is wise to have an external (non-PC) charging device for your Zen.
    Note: Only the battery charging symbol shows up on the Zen when using an external charger.
    Scratches
    All plastic screens will scratch, doesn't matter which type you have.
    For minor scratches you could use the Novus three part cleaner, polish and scratch remover system. Do not use the #3 coarse abrasi've in this system! Be extremely careful in using this product !!!! Please check the web.
    OR
    Low abrasi've toothpase <--- some say this works
    OR
    CD scratch remover/repair kit <---- have not tried this.
    The Zen (Flash) MP3 glass LCD screen is covered by the overlay plastic you see on the front. Worst case, you can have only the outer shell repaired and replaced by Creative.
    To prevent scratches in the first place:
    Use the Zen cloth bag which comes with the unit (sometimes ) to prevent scratches.
    OR
    Buy the Zen clear plastic case (Clear Case #70AB2600002). Sold by Creative.< I use this>
    OR
    Buy an clear plastic overlay. (Screen protector #70AB2600003) which goes over the LCD protector screen for protection. Sold by Creative.
    OR
    Also, you can cut up a "generic" PDA screen protector to fit the Zen.
    OR
    Obtain a "digital camera lcd screen protector" from a camera store or internet
    OR
    "Invisible shield" -The best protection money can buy
    http://www.zagg.com/invisibleshield/...ns-shields.php
    How to destroy your Zen - WHAT NOT TO DO
    . Leave it in the auto/car/vehicle - the vehicle inside heats up 20-35 F higher than the outside temperature.
    2. Leave it outside in freezing temperature 0C 32F. The LCD will freeze/discolor/absorb water.
    Note: It is remotely possible it could recover when warm-up at room temperature.
    Note: Just keep the Zen near your body heat when outside in freezing temperatures.
    3. Dropping it might cause the LCD screen to crack or loosen up the internal connections to the electronics or short out the internal electronics.
    Note: Use a protecti've case to cushion the blow from dropping the Zen.
    4. Dropping or submerging or getting the Zen wet in water might short out the electronics and battery.
    You could prevent destruction by immediately shaking the Zen vigorously in open air to dry it out.
    5. Sitting on it could flex the electronics and short or open circuits which would cause a defecti've/faulty Zen.
    <A bit of humor ... There is No Santa Claus, Easter Bunny or Tooth fairy and Creative does NOT give away money. If you destroy or damage your Zen you will pay not Creative>
    How can you tell if your Zen is defecti've/faulty
    . A "white screen" or a "totally blank black screen" shows up on the Zen LCD.
    2. You cannot force the Zen into the special "Recovery Mode" menu screen.
    3. The Zen refuses to "take a charge"(To charge up the internal Lithium-Ion Polymer battery)
    4. The Zen LCD is cracked or distorted due to dropping or handling abuse.
    5. The Zen clock does not keep accurate time (within 2 mins max per month)
    Contact Creative if any of the above faults occur - the Zen is bad and nothing you can do will fix it!
    WSOD "White Screen of Death"
    The "White Screen of Death" is really caused by a hardware problem. You see, the internal Freescale/SigmaTel STMP3700 MP3 processor has to write to the LCD. If this operation is prevented by internal electronic opens or shorts, bad STMP3700, locked-up firmware, bad LCD or any other electronic component failure then the CPU might/will halt and refuse to write to the LCD which will be reflected in a "white screen of death" I cannot cover all the causes of the "white screen of death" but rest assured Creative should pick these problems up in their quality control manufacturing process with a 99% success rate. Problems do show up after the manufacturing process but Creative has warranty protection for this other % fault rate. (Which is normal in electronics manufacturing)
    Media Content
    Listening to the built-in music on the Zen is OK but after a while your question now becomes "What else can I do with my Zen "
    Note: The "How to" instructions for adding Media content can be found in the Zen documentation.
    Terminology:
    Album: Collection of tracks or songs under one "album" title.
    Artist: Track or song artist
    DRM: Digital rights management - copy protection scheme - Zen cannot use music with this music protection scheme. (itunes) (But "itunes plus" will work)
    Genres: Type or kind of music
    <The following genres are defined in ID3v>
    Blues,Classic Rock,Country,Dance,Disco,Funk,Grunge,Hip-Hop,Jazz,Metal,New Age,Oldies,Other,Pop,
    R&B,Rap,Reggae,Rock,Techno,Industrial,Alternati've ,Ska,Death Metal,Pranks,Soundtrack,Euro-Techno,
    Ambient,Trip-Hop,Vocal,Jazz+Funk,Fusion,Trance,Classical,Instru mental,Acid,House,Game,Sound Clip,
    Gospel,Noise,AlternRock,Bass,Soul,Punk,Space,Medit ati've,Instrumental Pop,Instrumental Rock,
    Ethnic,Gothic,Darkwave,Techno-Industrial,Electronic,Pop-Folk,Eurodance,Dream,Southern Rock,
    Comedy,Cult,Gangsta,Top 40,Christian Rap,Pop/Funk,Jungle,Nati've American,Cabaret,New Wave,
    Psychadelic,Rave,Showtunes,Trailer,Lo-Fi,Tribal,Acid Punk,Acid Jazz,Polka,Retro,Musical,Rock & Roll,
    Hard Rock
    <The following genres are Winamp extensions>
    Folk,Folk-Rock,National Folk,Swing,Fast Fusion,Bebob,Latin,Revival,Celtic,Bluegrass,Avantg arde,
    Gothic Rock,Progressi've Rock,Psychedelic Rock,Symphonic Rock,Slow Rock,Big Band,Chorus,
    Easy Listening,Acoustic,Humour,Speech,Chanson,Opera,Cha mber Music,Sonata,Symphony,
    Booty Bass,Primus,Porn Groove,Satire,Slow Jam,Club,Tango,Samba,Folklore,Ballad,Power Ballad,
    Rhythmic Soul,Freestyle,Duet,Punk Rock,Drum Solo,A capella,Euro-House,Dance Hall
    <A bit of humor: I think the above Genres lists are missing two - "elevator music" & Crying and Whining e.g. Country Western>
    ID3 Tags: Internal file information associated with an Mp3 or wav audio file. This format contains
    Track number, Album name/title, Genre, Artist and Song Title which can be sorted and indexed by
    the Zen device.
    IPTV: Is a system where a digital television service is deli'vered using Internet Protocol over a network infrastructure, which may include deli'very by a broadband connection. http://zencast.com/
    JPEG: Is a commonly used method of compression for photographic images.
    This is the only photo format used by the Zen.
    MP3 and WMA music tracks: Music format used by the Zen.
    Note: Having the wrong bit rates will drain the Zen battery faster. (See above)
    MP3: Is a digital audio encoding format using a form of lossy data compression.
    Non-protected AAC: Files are regular AAC files without any DRM: they can be converted to other formats (like MP3) and can be played on an unlimited amount of devices and burned an unlimitd amount of times. They have no restrictions.
    Podcast: Is a series of digital-media files which are distributed over the Internet using syndication feeds for playback on portable media players and computers. http://zencast.com/
    Protected AAC: Files are AAC audio files that contain DRM (Digital Rights Management), most often music purchased from the iTunes store. The Creative Zen cannot use these files.
    Note: "Itunes Plus Store" have songs without DRM which the Zen can use.
    Ripping CDs: Copying tracks from an audio CD on a PC and downloading tracks to the Zen.
    Note: Use the Creative Zen Media Explorer for ripping audio CD is one method.
    Song Title: Name of song or track
    Track Number: Numerical number of track of CD album.
    Track: General name for song or song title.
    Unprotected AAC format: Music format used by the Zen
    WMA:Is an audio data compression technology developed by Microsoft. The name can be used to refer to its audio file format or its audio codecs.
    WAV: (or WAVE), short for Waveform audio format, is a Microsoft and IBM audio file format standard for storing an audio bitstream on PCs.
    Note: The Zen's built-in microphone produces this audio file format.
    Zen Audio Format:MP3, WMA, WAV, non-protected AAC (.m4a), Audible (2, 3, 4)
    Zen Media Content: Video, Music, Audio, Photos/Images transferred/dowloaded into the Zen
    Zen Photo Format:JPEG
    Note: You can copy/drag/paste JPEG photos from your PC to your Zen for viewing.
    Note: You can import photos & view photos from the SD card.
    Zencast Organizer: Seamlessly integrates ZENcast media files with Creative portable media players and/or your computer
    Zen Video Format:MJPEG, WMV9 and (with transcoding - MPED4-SP, DivX 4/5 and XviD)
    Warning - In some countries (including the US) its illegal to do:
    Copying audio DVD & DVDs
    Defeating DRM MP3 Music (Digital Rights Management)
    Intercepting/copying (non purchased) music.
    Downloading music/songs from an illegal or "free" rouge website.
    General Media Content links:
    http://pro-music.org/Content/GetMusi...lineStores.php
    Note: Check to see if your music files/tracks contains ID3 tags.
    Note: ZEN also supports iTunes Plus tracks from the iTunes store,
    Note: The following media content is only a small fraction of means and ways
    of collecting/dowloading media content to the Zen.
    Media Content from Creative Website(s)
    Note: The Media Content can be found under "Fill your Zen" on the bottom of the Creative Zen product page.
    http://zencast.com/
    ZENcast is the ultimate source for free IPTV channels, video blogs and podcasts on the Internet. It provides quick and easy access to a wide range of interesting and entertaining video and audio content online.
    http://www.audible.com/adbl/site/cre...seBVCookie=Yes
    Audible.com - Audible.comis the Internet s leading audio provider of bestselling audio books, comedy programs and today s most relevant magazines and newspapers
    http://creative.vongo.com/
    VONGO is the video download service that gives you instant access to over 2500 hit movie and video selections from Starz .
    Watch movies whenever, wherever on your ZEN. A great entertainment venue for watching movies while on the road or on the go.
    http://www.napster.com/creative/
    Transfer unlimited music to your ZEN without paying per song.
    With Napster To Go you can:
    Choose from over 5 million songs, plus new releases every week
    Play music instantly from any internet-connected computer
    Find old favorites and discover new music by exploring playlists, radio, Billboard charts and more
    Create a library of your favorite music and build custom playlists.
    http://www.emusic.com/ZEN
    Choose from over ,500,000 songs
    Burn unlimited CDs
    Compatible with every MP3 player
    No confusing restrictions-Own your music!
    http://www.lala.com/frontend/action/...=user:2672@223
    Why pay 99per song when you can get the whole album for $At lala.com, you can trade your used CDs for new music.
    .8 million titles available for trade. CD quality guaranteed.
    Every CD you receive is yours to keep - no restrictions.
    Pay only $ per CD received. No monthly fees or commitments. Sign up is FREE.
    http://www.amazon.com/b/ &node=62663
    Buy or Rent Movies Online
    Watch DVD-quality video downloads on your PC or ZEN
    Conveniently download from your PC at work to your PC at home
    Discover thousands of TV shows & movies available for download
    I started this thread in April 08 to help other new Creative Zen MP3 (Flash) users. If there are common threads that are posted from new users then I try to make a section to inform other new users in solving their similar problems. I cannot believe that this thread was viewed over 0,000 times! Thank you for your "viewing" support.
    Please note: This thread is constantly changing so check back for any new helpful hints, problem solving, troubleshooting and practical solutions for the Creative Zen.
    "The Creative ZenR O C K S"
    Zenandy
    Message Edited by Zenandy on 08--2008 08:26 AM

    Hi,
    I'm from germany so no 'best buy' but I think I will lock around sleeve/bag for a different product with same measures. Any tip?
    The clear plastic case is not what I want. I would like to use the player without such protections. I just want a sleeve to protect the player while its in my jacket/pants.
    Btw, i have bought this version: Creative Zen (maybe european version?). I also doesn't seem to have your mentioned sleeve. I also couldn't find it on the website.
    Anyway, thank you,
    Chris

  • Multi-thread failure - Error in assignment

    Hello
    I have a c++ program processor running under Windows XP with Oracle 9i. My program access to oracle by an ODBC driver version 9.2.0.4.0. It could be launched in multi-thread to increase performance. When I launch it with one thread everything is fine. When I use several threads I have problems. ODBC driver returns to me a "error in assignment ... General error" message and my updates queries failed. Under SQl server it works without problems. It seems to be a kind of deadlock. When I disable check box in my odbc driver of "enable query timeout" my program encounter a problem and freezes...
    Could someone help me ?

    user13335017 wrote:
    I have thought of the above solutions as workable, however, it is not. Some exhibited errors are:
    A. "Attempt to use database while environment is closed." This error applies to 2, 3 and 4 all the way;
    B. "Attempt to read / write database while database is closed." This error applies to 3 in particular;
    C. "Attempt to close environment while some database is still open." This error applies to 5.
    Please help me with designing a better strategy to solve the concurrent issue. Many thanks in advance.All these are expected errors. You should design the application so that you do not close an environment handle while database handles are still open, keep database handles open for as long as operations need to be performed on the underlying databases, open the database handles after opening the database handles, and close database handles before closing the environment handle.
    In short, in pseudo-code, you should have something like this:
    - open environment handle,
    - open database handles,
    - perform whatever operations are needed on the databases,
    - close database handles,
    - close environment handle.
    You can refer to the Getting Started with Data Storage and the Getting Started with Transaction Processing guides appropriate for the API you are using, from the Berkeley DB documentation page.
    Regards,
    Andrei

  • The problem about multi-thread in java application

    i have problem with the multi-thread in java application, i don't know how to stop and restart a thread safely, because the function thread.stop(),thread.suspend() are both deprecated.
    now what i can only do is making the thread check a flag(true or false) to determine whether to start or to stop, but i think this thread will always be in the memory and maybe it will lower the performance of the system, as the program i am developping is working under realtime enviorement.
    please help me about it. thanks !

    hi,
    you can stop a thread by exiting it's run()-method which in terms can be done by checking the interrupted-flag:
    public void run(){
    while(interrupted()){ //if the thread consists of a loop
    or
    public void run(){
    if(interrupted())return;
    if(interrupted())return;
    or by the use of the return-statement anywhere withing the run-method. Afterwards, that is when the thread is no longer needed, you clear all the references to the specific thread object by setting them to null:
    Thread t;
    ... //working
    t.interrupt(); //interrupting
    while(t.isAlive()){
    Thread.yield(); //wait till thread t has stopped
    t=null;
    best regards, Michael

  • Aggregate Storage And Multi-Threading/Multi-Core Systems

    Please pardon if this question has been asked before, but the Forum search is not returning any relevant results.
    We are in the process of purchasing hardware for an 11.1.2 Essbase environment. We are going 64-bit, on Windows 2008, with either 32 GB or 64 GB of system RAM. The debate we are having is the number of CPUs and cores per CPU. We have not built any ASO databases as of yet, but we plan to launch a major BSO to ASO conversion project once 11.1.2 is off the ground here.
    Historically, with BSO, we did not see performance improvements significant enough to justify the cost of additional CPUs when we ran calcs on multi-CPU systems vs. single or dual CPU systems, even when the settings and design should have taken the most advantage of BSO's multi-threading capabilities. However, it would seem that ASO's design may be able to make better use of multi-core systems.
    I know that there are a lot of factors behind any system's performance, but in general, is ASO in 11.1.2 written well enough to make it worthwhile to consider, say, a four CPU, total 16 core system vs. a 2 CPU, total four core system?

    Grand central dispatch - infancy, not really doing its job, and I don't think apps have to be specifically written for HT, but they do have to not do things that they use to - prevent threads from going to sleep! or be parked.
    high usage is not necessarily high efficiency. often the opposite.
    Windows 7 seems to be optimized for multi-core thanks to a lot of reworking. Intel wants and knows it isn't possible to hand code, that the hardware has to be smarter, too. But the OS has a job, and right now I don't think it does it properly. Or handle memory.
    Gulftown's 12MB cache will help, and over all should be 20% more efficient doing its work.
    With dual processors, and it doesn't look like there are two quick path bridges, data shuffling has led to memory thrashing. Use to be page thrashing with not enough memory. Then core thrashing but having the cores, but not integrated (2008 is often touted as being greatest design so far, but it was FOUR dual-cores, 2009 was the first with a processor that really was new design and (native) 4-core.
    One core should be owned by the OS so it is always available for its own work and housekeeping.
    The iTunes audio bug last year showed how damaging and not to implement code and how a thread could usurp processing and add a high cpu temperature while basically doing nothing, sort of a denial of service attack on the processor - those 80*C temps people had.
    All those new technology features under development and not like OpenCL, GCD and even OpenGL are tested, mature but rather 1.0 foundation for the future. A year ahead of readiness.

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

  • Trouble rationalizing use of multi-threading in run of the mill servlets

    Hey everybody,
    While spending time writing an internal wiki article on servlets for work, I asked myself a very basic question: What does multi-threading buy average servlets where the business logic requires procedural handling of the request?
    Don't get me wrong: I appreciate the fact that servlet containers spawning a new thread being less expensive than spawning an entirely new process is helpful and efficient. Coming from a background in PHP, it is great how servlets maintain persistence. However, as more of my coworkers are required to gain proficiency in Java and designing servlets, it is a question that many will ask and aside from having real-time processing of data files and other arduous tasks, I cannot think of any instances of where multi-threading benefits the application.
    What are some of the ways that you are using multi-threading with web applications?
    How would you explain why and where you would want to use multi-threading to someone?
    Thank you in advance for your insight,
    Andy

    how can we pass arguments to the run ()method?Create classes which implement Runnable that take your runtime parameters as constructor arguments and store them.
    eg: if your single thread method is   static void foo (int quantity, String name) {
        for (int i=0; i<quantity; i++) {
          System.out.println(name);
    // caller code
      foo(7, "wombats");Then you can make a runnable implementation thus:public class Foo implements Runnable {
      final int quantity_;
      final String name_;
      public Foo (int quantity, String name) {
        quantity_ = quantity;
        name_ = name;
      public void run () {
        for (int i=0; i<quantity_; i++) {
          System.out.println(name_);
    // caller code
      new Thread(new Foo(7, "wombats")).start();
    You could overload this method to take parameters in
    your class that implements the Runnable interface,
    and then call the base run() method.I don't get what you mean by this; Runnable is an interface so there is no base class run() method, and a run() overloaded with extra parameters method wouldn't get called by the thread.
    Pete

  • Proble with multi-threaded app using the same connection

    have a multi-threaded app. The threads all share the
    same connection. They all do some selects / updates.
    The OS is NT 4.0 and the application server is weblogic
    Some times I am getting the error "java.sql.SQLException: Io exception: not in streaming mode"
    and some times I am getting "java.sql.SQLException: Io exception: Protocal violation
    Any Ideas?
    Regards
    Suresh

    Don't create threads.... Your threads should if they are necessary be reusable, your threads should call the connections it needs from the cache service with let's say a max number of N pools (each pool a max number of M connections), if the connection domain asked exists on cache a connection is asked for corresponding pool, if the connection domain is not on cache the less used domain is thrown away (all inner connections closed first) and substituted by the new one requested. While the pool is not full keep creating connections as the request came (and all existing connections are being held and not released), when M connections exists, a request should wait till a connection is released.
    If you can have 20 threads asking for the same connection and the max number of connections on pool is M=10, then yopur threads will wait for a connection being released. All this must be synchronized. You should set M the closest as possible to the normal number of requests you can imagine to happen the same time. You should get connection use it and release it right away if you can have a lot of requests.
    I hope this helps you.

  • The CPU utilization is 0% for the other remaining processes when multi threading is used

    I am new to AE ,so I am trying to render a project enabling multi threading process the additional processes are present but their utilization is 0% .
    I want to juice out every single CPU utiliaztion .
    ANy help is greatly appriciated,.
    My system specs:
    AMD 9690 4.7 Ghz 8 core
    32 GB DDR3
    C:\256 GB Solid Satte Raid 0
    GeForce 780 Ti DDR5 3GB

    It is very tempting to try and use all of your system resources and multiprocessing for all your projects, but this is not the way After Effects works. Many third-party plug-ins, many codecs, and many operations do not respond well to multiprocessing. All it takes is one process in your entire thread that is not MP aware to foul the whole thing and give you longer render times.
    You are also leaving zero processors for the rest of your computer. Not a wise idea.
    After effects renders one frame at a time. One HD frame even with multiple layers of pixel processing just isn't that much data. It does take a while to do the calculations, but expecting to have every one of your CPUs jacked up at 100% to render a single frame of video is expecting an awful lot.
    I would suggest that you read up on optimizing After Effects for your computer. Do not expect to be able to utilize 100% of your system resources at all times. That's just not the way processing video on a pixel by pixel basis works.
    Just a little FYI,  for 99% of my projects in After Effects I have render multiple frames simultaneously turned off. It just doesn't work with most of the things I do. Sorry for the disappointment.

Maybe you are looking for