Question about using threads and synchronizing objects

Hi all,
I am not that familiar and I have 2 questions.
QUESTION 1
I have a server which just sits and accepts incomming connections, then I spawn off a new thread which implements Runnable, and then call the run method. But the loop would not iterate, it would just sit inside the run method (which has rather long loop in it). I changed the class to extend Thread and called the start() method, rather than run(), and everything worked out fine.
Anyone know why this is?
QUESTION 2
So I am building a client server chat application where a user can be in multiple chat rooms. I have this personObject which has output/input streams. In the personObject, I create writeObject/ readObject method, which simply does as it implies.
I figured that I should make these methods synchronized, to ensure things run smoothly. however, when I made a call to readObject, which sat there and waited, and then made a call to writeObject, I would not enter the writeObject method. I took out the synchronized on the writeObject, and everything worked out fine.
I was under the assumption that synchronizing a method only synchronized on that method, not on the whole class. How come then was I not able to enter the writeObject method?
The more I think about it, I don't think I need to have these methods synchronized, but I thought it wouldn't hurt.
Thanks for the help.

Hi all,
I am not that familiar and I have 2 questions.
QUESTION 1
I have a server which just sits and accepts incomming
connections, then I spawn off a new thread which
implements Runnable, and then call the run method.
But the loop would not iterate, it would just sit
inside the run method (which has rather long loop in
it). I changed the class to extend Thread and called
the start() method, rather than run(), and everything
worked out fine.
Anyone know why this is?
You should still implement Runnable, rather than extending Thread. Like this: Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start(); run() is just another method. Nothing special about it as far as multithreading or anything else goes.
start() is the method that actually spawns a new thread of execution.
I was under the assumption that synchronizing a
method only synchronized on that method, not on the
whole class. How come then was I not able to enter
the writeObject method?When you synchronize, you obtain a lock. As long as you hold that lock--until you exit the sync block or call wait()--no other thread can enter that block or any other block that obtains the same lock.
Two synchronized methods on the same object rely on obtaining the same lock--there's one lock for each object.

Similar Messages

  • Question About Java Threads and Blocking

    I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
    // Test ProcessBuilder
    public class CommandProcessor {
    public static void Run(String[] cmd) throws Exception {
    System.out.println("inside CommandProcessor.Run function...");
    Process p = new ProcessBuilder(cmd).start();
    StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
    StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
    s1.start();
    s2.start();
    //p.waitFor();
    System.out.println("Process Returned");
    Here's the "StreamGobbler" class:
    import java.lang.*;
    import java.io.*;
    // Attempt to make the output of the process go to the message window
    // as it is produced rather that waiting for the process to finish
    public class StreamGobbler implements Runnable {
    String name;
    InputStream is;
    Thread thread;
    public StreamGobbler (String name, InputStream is){
    this.name = name;
    this.is = is;
    public void start(){
    thread = new Thread (this);
    thread.start();
    public void run(){
    try{
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    while (true){
    String s = br.readLine();
    if (s == null) break;
    System.out.println(s);
    //messageWindow.writeToMessageArea("[" + name + "]" + s);
    is.close();
    catch(Exception ex){
    System.out.println("Problem reading stream" + name + "...:" + ex);
    ex.printStackTrace();
    The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
    We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
    while (s1.thread.isAlive() || s2.thread.isAlive())
    // We really don't do anything here
    I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
    Thank you in advance for your help!

    You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
    This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
    I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

  • Short question about networking, Threads and  web services..

    Lets say I got 2 classes, Midlet A and Thread B.
    I created Thread B because web services (jsr-172) uses networking and It has to be done in a separate thread other then the Midlet A.
    So, in Thread B, I have the run(), where I do all my stuff, and some getSomething() methods.
    I need to have run() complete before calling getSomething(), so I used something like this in Midlet A:
    while(true){
        if(b.isAlive())
            getSomething();
    }Problem is, Thread B only runs to completion when I don't call b.isAlive(). (I know from System.out.println I placed in it) When I do use any methods like wait() or join() or isAlive(), Thread B stops at the web service call.
    I really don't understand what's the problem. I've tried various ways to only call getSomething() when the thread finishes running, but all of them made my WTK emulator hang at the part where it asks for permission to access the network.
    If I don't use getSomething(), which is the purpose of starting the thread in the first place, it runs fine in the emulator and doesn't hang anywhere. Oh the irony.

    Bump!
    Anyone got even half a clue what's wrong? =O
    Hmm. I think that having the midlet wait for the thread causes the midlet to hang because the thread will then wait for the midlet for permission to access the network, but the midlet is waiting for the thread to finish it's code. Damn.
    Message was edited by:
    lonereaction

  • Questions about Using Lightroom and Print Studio Pro

    I want to use Print Studio pro via the lightroom plugin since as I understand it, that is the only way to ensure a 16-bit file is being passed to the printer (on Windows).  However, I am a little confused about how the image is being rendered.  Is lightroom applying a default output sharpening to the file before handing it off to Print Studio Pro or Does Print Studio Pro manage resolution and Output sharpening based on the media and print size you choose?  
    So basically I am wondering if there is any output sharpening being applied, and when is it applied.  The possibilities I think would be:
    Lightroom is applying a default output sharpening when rendering the file to TIF for Print Studio Pro (If this is the case, what setting is being applied and is it possible to change it?)
    Print Studio Pro is applying output sharpening based on media type and print size, or applying a generiz amount of sharpening that does not take into account media or size.
    No Sharpening is being applied.  In this case, I should probably be exporting this file manually with output sharpening applied and then opening in Print Studio Pro
    The other question I have is if when using the plugin is the TIF file that is being generated in 16-bit pro-photo to ensure the maximum amount of color data?
    Because if Print Studio Pro is not applying sharpening I think it may just be better to print through the lightroom tool even though it renders down to 8-bit because the amount of control I have via the lightroom print module would be far more advantageous than any color data I am losing by printing in 8-bit.
    Anyone know the answer to all this?

    I had similar questions when I first got my Pro-100.
    1. You can call up PSP from any module, so I assume it is ignoring print module settings.
    2. If I select a Saved Print, which adjusts the print module settings specific to that print, and the open PSP the paper settings in PSP are not what is in LR, supporting the "ignore" conclusion.
    3. I ran some test prints using LR to print at three different output sharpening settings (Off, Standard, High) to ensure I could see a difference (I did).
    4. I ran four test prints: LR-Standard, XPS driver, LR-Standard regular driver, PSP using standard driver and PSP using XPS driver. I couldn't see any difference between the four prints.
    Since LR is such an easy printing process I haven't seen a reason to use PSP.
    John Hoffman
    Conway, NH
    1D Mark IV, Rebel T5i, Pixma PRO-100, MX472

  • New to Apple, questions about using Windows, and other things

    Hello all,
    Today is my first day as an Apple owner. It's funny because I'm also a MCSE, MCSA, and MCP.
    I purchased a 24" iMac, 2.8GHz, 4GB RAM, and 1TB Hard Drive.
    I want to use Windows on my Mac so that I don't have to keep switching over to my PC. My main reason for using Windows is so that I can continue to enjoy my PC Games... mostly racing and D&D games.
    So my question is... how does Windows run on bootcamp? Can I still use all of my USB controllers (like my steering wheels, joysticks, etc?)
    I really havent even turned on my iMac... been too amazed at just looking at it for the first day (and also rearranging my home office).
    I really just want to know from those of you who have PCs AND Macs, if you still find yourself having to go back to your PC because of incompatibilities or performance issues on the iMac?

    Using BootCamp, your Windows experience is no different than if running it on a similarly configured PC. If you went with a VM running under Mac OS X (like VMWare or Parallels), there are a number of differences. However, using BootCamp you have a Mac-branded PC.
    I'd point out that people have been dual-booting operating systems in this fashion for decades. Windows has no obvious in-built support for doing so, but other operating systems (like Linux, FreeBSD, etc.) have always very clearly and explicitly supported dual-booting (on Macs and regular PCs) from the get go.

  • Questions about using Rescue and Recovery backup / Alternatives

    I have used R&R, created DVD backup set, restored to a new HD.  All worked great.  Now a few months later I'd like to create another DVD BU set.  Apparently we can only create ONE R&R dvd?  It tells me I can continue to create the BU dvd set or cancel.  My son has an identical X61 tablet and he could not create R&R the first time on DVD.  I burned him a copy of mine and he was able to restore to his new HD.  So, why restrict to a single copy of a dvd which is easily duplicated?
    Question:  Is the old R&R dvd compatable with new version of R&R (4.2x)?  Can I continue to use it with new dvd BU sets?
    Second: has anyone found a good backup utility like Casper which allows complete HD BU to an external drive?  This is something I always did before the Lenovo, kept a spare HD to simply plug in in case the operating one failed, great BU.  Casper will NOT work with Vista and the X61.  Worked with them for several weeks, no progress.  Created some hard to remove problems as well.
    Thanks!
    I do weekly BU to an external TBHD using the Thinkvantage utility but my confidence is not complete.
    Moderator Note; Message Subject edited
    Message Edited by andyP on 10-08-2008 07:24 PM

    hi
    you can try acronis true image solution it will even back up the entire service partition for you!goodluck!
    Cheers and regards,
    • » νιנαソѕαяα∂нι ѕαмανє∂αм ™ « •
    ●๋•کáŕádhí'ک díáŕý ツ
    I am a volunteer here. I don't work for Lenovo

  • General questions about using webservices and xml as opposed to an oracle driver

    Dear Experts; I have a general question which I have yet to test. Is it faster to use an ODBC driver to connect and retrieve data from an Oracle database than creating a .net webservices and using an XML to get the data for your web application. THank you

    At some point in the architecture stack some component will need to access the database in order to get the information from the database. That component will need to use an Oracle client driver.

  • Newbie question about using vectors and arrays

    I'm fairly new to JME development and java in general. I need some help in regards to Vectors and 1 dimensional arrays. I'm developing a blackberry midlet and am saving the queried info i pull back from my server side application with each record saved into the array and subsequently each array saved as an element in the vector, thereby creating a 2D "array".
    However I'm having a problem accessing the elements in the array. Here is a sample of what I mean and where I get stuck:
    Vector _dataTable = new Vector(1, 1);
    String[] r1 = {"a", "b", "c", "d"};
    String[] r2 = {"1", "2", "3", "4"};
    _dataTable.addElement(r1);
    _dataTable.addElement(r2);
    Object temp = _dataTable.elementAt(0); //Save the element as an new object for useNow how do I access the particular indexes of the element of the temp object? Do i need to caste it to an array? Is there another more efficient/easier way I should be storing my data? Any help would be great!
    Edited by: Sotnem2k1 on Apr 1, 2008 7:50 AM
    Edited by: Sotnem2k1 on Apr 1, 2008 7:51 AM

    Thanks for the feedback newark. I have this scenario below:
    // Class for my 1D array
    public class OneRecord {
        private String[] elementData = new String[4];
        public OneRecord() {   
            elementData[0] = null;
            elementData[1] = null;
            elementData[2] = null;
            elementData[3] = null;
        public OneRecord(String v1, String v2, String v3, String v4) {   
            elementData[0] = v1;
            elementData[1] = v2;
            elementData[2] = v3;
            elementData[3] = v4;
        public void setElement(int index, String Data) {
            elementData[index] = Data;
        public String getElement(int index) {
            return elementData[index];
    } Then in my main app I have:
    Vector _dataTable = new Vector(1, 1);
    OneRecord currRecord = new OneRecord("a", "b", "c", "d");
    _dataTable.addElement(currRecord);
    OneRecord temp = (OneRecord)_dataTable.elementAt(1);
    System.out.println(temp.getElement(0)); Are there more efficient data structures out there to save queried data from a server side app? Like I said, i'm still trying to learn the most efficient techniques of coding...esp for the Blackberry. Any suggestions would be great!

  • I have a question about using multiple ipads in our school.  Each of our teachers have a iPad and AppleTV in their classroom.  The issue is, with our classrooms so close in proximity to one another, is there a way to pair teacher

    I have a question about using multiple ipads in our school.  Each of our teachers have a iPad and AppleTV in their classroom.  The issue is, with our classrooms so close in proximity to one another, is there a way to pair teacher #1 iPad to its AppleTV without effecting/projecting onto the adjacent teachers #2 classroom AppleTV?

    Not as such.
    Give the AppleTV units unique names and also enable Airplay password in settings with unique passwords for each teacher.
    AC

  • Question about using 10g/11g and APEX ...

    Hi,
    I just recently learned of Oracle's APEX and have a few questions about using it.
    Can I use APEX with express, standard, and enterprise editions of 10g and 11g?
    Are all of these free to use?

    You might want to read about APEX rather than jumping into questions that are reasonably well documented. Info at http://www.oracle.com/technology/products/database/application_express/index.html
    Your specific questions:
    1) Apex is a package that can be installed into any properly licensed database.
    2) The price for the production license of the database varies by edition.
    The price for Express Edition is $0 for use in production. Part of the cost for that edition is 'no Oracle Support based support, no patches, data volume limitation, etc.'

  • The question about portlet customization and synchronization

    I have a question about portlet customization and synchronization.
    When I call
    NameValuePersonalizationObject data = (NameValuePersonalizationObject) PortletRendererUtil.getEditData(portletRenderRequest);
    portletRenderRequest.setPortletTitle(str);
    portletRenderRequest.putString(aKey, aValue);
    PortletRendererUtil.submitEditData(portletRenderRequest, data);
    Should I make any synchronization myself (use "synchronized" blocks or something else) or this procedure is made thread-safe on the level of the Portal API?

    HI Dimitry,
    I dont think you have to synchronize the block. i guess the code is synchronized internally.
    regards,
    Harsha

  • Question About Color's and Gradients

    Hi all,
    I have a question about color swatches and gradients.
    I am curious to know, if I have 2 color swatches that I make into a gradient color, is it posible to change the tint of each indivdual color in that gradient and have that applied to the gradient without having to adjust the gradients opacity.
    The reason that I'm asking this is because in creating a project I found that the colors that I chose for to make my gradient from my swatches were to dark, and while I can adjust each one's tint to my liking (if the object they were applied to was going to be a solid color) but that doesn't seem to apply to the overall gradient.
    I hope that makes sense, I know that this was something that was able to be accomplished in quark and was wondering if I can do something similar.

    If you double click your gradient swatch (after adding it to the swatches)
    Then click a colour stop in the gradient, and then change the drop down menu to CMYK (or rgb)
    And you can alter the percentages there. It's not much use for spot colours but it's a start.
    But making tint swatches would be a good start anyway.
    At least then when you double click the gradient (in the swatches) to edit it you can choose from CMYK, RGB, LAB, or Swatches and adjust each colour stop to your liking.

  • Question about using Runtime.getRuntime();

    hi all
    i have a question about using Runtime.getRuntime(). if i use this to get a runtime reference to run an external program, is it considered as starting a new thread inside the thread that starts it?
    is it safe to do it in the Session EJB? if not, what can you recommand to do it? thanks

    hi all
    i have a question about using Runtime.getRuntime().
    if i use this to get a runtime reference to run an
    external program, is it considered as starting a new
    thread inside the thread that starts it? No. Starting a process, starts a process. Threads have nothing to do with it.
    is it safe to do it in the Session EJB? if not, what
    can you recommand to do it? thanksSo what? Run another process? If you want to run another process in java then your choices are to use Runtime.exec() or use JNI. And using JNI will probably end up doing exactly the same thing as Runtime.exec().
    "Safe" is harder. Typically to correctly use Runtime.exec() you must use threads. And as noted threads ideally should not be used. You can use them but if you do you had better understand why they didn't want you using them in the first place. You had also better be sure that you really want to wait for it to complete.
    Other than that Runtime.exec() is safe because it can't crash the VM like other interfaces can (like JNI.)

  • Hi, I have quick question about use of USEBEAN tag in SP2. When I specify a scope of SESSION for the java bean, it does not keep the values that I set for variable in the bean persistent.Thanks,Sonny

     

    Make sure that your bean is implementing the serializable interface and that
    you are accessing the bean from the session with the same name.
    Bryan
    "Sandeep Suri" <[email protected]> wrote in message
    news:[email protected]..
    Hi, I have quick question about use of USEBEAN tag in SP2. When I
    specify a scope of SESSION for the java bean, it does not keep the
    values that I set for variable in the bean persistent.Thanks,Sonny
    Try our New Web Based Forum at http://softwareforum.sun.com
    Includes Access to our Product Knowledge Base!

  • Question about using new battery in old Powerbook

    I have a pre-intel Powerbook G4, and the battery is pretty much toast (lasts about 15 minutes now). I have ordered a new battery for it, and I have this question about using it:
    Am I smarter to keep the new strong battery out of the PB most days (as I usually work with it plugged in at home) and just pop it in when I know I will be out surfing on batteries? Or is it just as good living in my laptop 24/7 and only occasionally being called upon to do its job?
    Current bad Battery Information below:
    Battery Installed: Yes
    First low level warning: No
    Full Charge Capacity (mAh): 1144
    Remaining Capacity (mAh): 1115
    Amperage (mA): 0
    Voltage (mV): 12387
    Cycle Count: 281
    thanks folks, Shereen

    Hi, Shereen. Every Powerbook battery wants to be used — drained and then recharged — at least every couple of weeks. If you've always used your Powerbook on AC power nearly all the time, and not followed that pattern of discharging and recharging the battery every week or two, it's possible that your use habits have shortened the lifespan and prematurely diminished the capacity of your old battery. Of course it's also possible that your battery is merely old, as a battery's capacity also diminishes with age regardless of how it's used. You didn't say how old the battery is in years, so this may or may not be an issue. I mention it only because it can be an issue.
    For general information on handling a battery for the longest possible lifespan, see this article. My advice on the basis of that article and long experience reading these forums is that it would be OK to do as you propose, but I doubt that you'd derive any significant benefit from it. You would still want to be sure of putting the new battery through a charge/discharge cycle every week or two, even if you didn't have a reason to use the Powerbook away from home or your desk, because sitting unused outside the computer is just as bad for a battery as sitting unused inside it. And you should never remove the battery from your computer when it's completely or almost completely discharged and let it sit that way any longer than a day or two.
    Message was edited by: eww

Maybe you are looking for

  • Report for viewing credit limit block released documents

    Hello All, Our client's requirement- credit limit check to be carried out and authorised persons can release the blocked orders. But is there any report at month end to see how many documents were released and who released them  Is there any standard

  • Windows XP, installation failed

    I have 2 motherboards MS-6380E installed in two different computers with different additional hardware. The installation of Windows XP failed onn both computers. The error message is: "Bios time wrong" (but the time is correct. And  "can not install

  • Configuring httpd-ssl.conf on Leopard and Apache 2.2.6

    Hi everybody, I recently migrated to Leopard from Tiger 10.4.10. On my Tiger client I had installed my own web server using mod_ssl with Apache 1.3 server. On Leopard, apache 2.2.6 and OpenSSL 0.9.7 are now installed and configurations files have cha

  • Customer Statement and DI API Invoices

    Hi, We are running SAP Business One 2007A PL5. We have a number of invoices that have been created by the DI API used by the Radio Beacon/SAP interface.  These invoices are not appearing on the customer statement. The only noticable difference in the

  • Moving and renaming files after PSE has uploaded them

    I use PSE 7 I have many folders  (50+) and perhsps file names  ( few thousdand)  that after uplaoding all of them into PSE and tagging about half I am consdering remaning some of them and also combine some folders or just renaming some folders any  w