Trying to develop a blocking method

This seems like it should be simple, but I've been trying to figure it out all morning. Basically, I want to develop a way to lock object across all instances to make it writeable. Creating a static boolean class variable will get me most of the way there, but I'm going for extra credit :) I want to have a method called "lock" that will ultimately guarantee an instance has exclusive write permission. If no instances currently hold the lock, it should simply set the boolean (I assume) and return. If another instance already has the lock, I want the lock method to block until it can get access to the lock. Ideally, this is queued so calls to lock are honored in the order they are received.
For example, I have two threads A and B. I have to ask you to use your imagination a little (since it is hard to demonstrate) and assume these blocks are overlapping on the respective threads.
//executing on thread A
LockableInstance a = new LockableInstance();
a.lock();
a.doSomething();
a.unlock();
//executing on thread B
LockableInstance b = new LockableInstance();
b.lock();  //thread A already holds a lock. this call waits until lock can be acquired.
b.doSomething();
b.unlock();The concept of blocking has really got me stumped. The one way I know this will work is to make lock() an infinite loop calling Thread.sleep until the class variable is unlocked. This seems inefficient for two reasons. For one, the sleep interval needs to be short, so it's just banging on the CPU (especially with many threads running). Another reason is that there is no guarantee locks will be obtained in the order they are requested.
Any ideas on how I could approach this?
Edited by: kgdoom on Nov 11, 2007 1:20 PM
Edited by: kgdoom on Nov 11, 2007 2:11 PM

I think I found what I needed :) For anyone interested, I can use an instance of java.util.concurrent.Semaphore. Specifically, I'm using a "binary" semaphore, which just an instance with 1allocated permit. Does exactly what I was trying to do!
New question... are semaphore objects hefty? If I have many classes using semaphores (one static instance per class), is it a drain on resources somehow? Is there something more efficient in binary cases?

Similar Messages

  • Trouble writing a blocking method when asking GUI for input

    Hi,
    I think this is more of a thread question than a GUI question, so that is why i posted it here...
    My problem is I have a client/server application, and the client also has a GUI, which I get an input string from.
    My problem is, that I don't know how to write a blocking method, which will wait for the GUI's input.
    The example I provided below is very simple, and the obvious solution would be to use a JOptionPane, but that is not a viable solution. The way I am getting around this now is using a Thread.sleep call in my GUI, but I feel that this is incorrect, and there should be another way around it.
    Here is my server class (w/ main method)
    import java.net.*;
    import java.io.*;
    public class Server {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(4444);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                System.exit(1);
            Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String  outputLine;
            outputLine = "Temp String";
            out.println(outputLine);
             System.err.println("Client: " + in.readLine());
            outputLine = "Bye";
            out.println(outputLine);
            out.close();
            in.close();
            clientSocket.close();
            serverSocket.close();
    }Here is my client class (w/ main method)
    import java.io.*;
    import java.net.*;
    public class Client {
        public static void main(String[] args) throws IOException {
            Socket kkSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                kkSocket = new Socket("localhost", 4444);
                out = new PrintWriter(kkSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: localhost.");
                System.exit(1);
            ClientGUI cg = new ClientGUI();
            String fromServer;
            String fromUser;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye."))
                    break;
                fromUser = cg.getInput();
             if (fromUser != null) {
                    System.out.println("Client: " + fromUser);
                    out.println(fromUser);
            out.close();
            in.close();
            kkSocket.close();
             System.exit(0);
    }and here is the ClientGUI class (note: you need to resize it in order to see the textbox....
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class ClientGUI extends JFrame {
         private JTextField textBox = new JTextField();
         private JButton input = new JButton("Submit");
         private boolean recievedInput = false;
         private String inputText = "";
         public ClientGUI() {
              this.setupGUI();
         private ActionListener buttonAction = new ActionListener() {
              public void actionPerformed(ActionEvent e)  {
                   inputText = textBox.getText();
                   recievedInput = true;
         public String getInput() {
              while(recievedInput == false) {
                   try {
                        Thread.sleep(2000);  //I  DONT want to do this!!
                   catch(InterruptedException e) {
                        e.printStackTrace();
              recievedInput = false;
              return inputText;
         private void setupGUI() {
              textBox.setMinimumSize(new Dimension(100, 20));
              input.addActionListener(buttonAction);
              this.getContentPane().setLayout(new BorderLayout());
              this.getContentPane().add(textBox, BorderLayout.WEST);
              this.getContentPane().add(input, BorderLayout.EAST);
              this.pack();
              this.setSize(100,300);
              this.setVisible(true);
    }If you have any ideas, I would greatly appreciate it

    warnerja,
    I tried the following, but I got an exception.
    in the while loop inside Client.java, I put the following:
                 synchronized(cg) {
                      try {
                          cg.wait();
                        fromUser = cg.getInput();
                      catch(InterruptedException e) {
                           e.printStackTrace();
                 }and inside my ClientGUI class, I put the following:
    private ActionListener buttonAction = new ActionListener() {
              public void actionPerformed(ActionEvent e)  {
                   inputText = textBox.getText();
                   ClientGUI.this.notify();
         public String getInput() {
              return inputText;
         }But I got this exception:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.notify(Native Method)
         at ClientGUI$1.actionPerformed(ClientGUI.java:21)
    any idea what I am doing wrong?

  • My ipod cclassic 80gb is hang after trying dat press and hold method then also its not working please tell me solution

    My ipod cclassic 80gb is hang after trying dat press and hold method then also its not working please tell me solution

    Thanks for your response and good luck wishes, I suspect I will need them!
    In principle, I agree re: the manufacturer's warranty. However, I am pretty upset that this is now my second iPod to develop a critical fault within weeks of the warranty expiring, and frankly, it is not unreasonable to expect a state-of-the-art $500 electronic device to last well beyond one year of life.
    I agree talking to Apple is not likely to do me any good (the clue is in how impossible they make it to talk to them in the first place) - but that is not necessarily OK. I expect I will have to pay money to get the battery replaced - again, not OK (full stop - but especially given the cost of the device and the money I have spent with Apple). Yes, the batteries have a limited lifespan, but it should last longer than this (and surely, I should notice a gradual decline in its functionality, not an instant stop).
    I will try Deggie's suggestion (see my reply post), but probably won't hold my breath (think I have already done this). I probably will have to get the new battery - and probably under my own steam. It is a principle at stake and I feel I should be able to let Apple know how I'm feeling - and am frustrated that they make this virtually impossible. It sends the very clear message that they are not interested in listening to their customers.

  • I plug my iPhone 3gs into my laptop and it no longer syncs with my iTunes.  Ive tried all the trouble shooting methods and nothing works.  My iPhone doesnt appear on iTunes or under "my computer." Does anyone know how to fix this?

    I plug my iphone 3gs into my laptop and it no longer syncs with my iTunes.  I've tried all the trouble shooting methods and nothing works.  My iPhone doesn't appear on iTunes or under "My Computer." Does anyone know how to fix this?

    If AMDS is running, you are using a USB port directly on the computer and not a hub, you have disconnected other USB devices except keyboard and mouse, you have completely uninstalled and reinstalled iTunes as described in http://support.apple.com/kb/HT1925, You have tried cleaning the connector on the bottom of the phone, you have tried a different cable, you have installed the latest USB drivers for your computer, you have disabled your antivirus and firewall, you are running as an Administrator account and you have tried creating a new user on your computer and connected when logged in as that user then you have exhausted my knowledge. The only other thing to try is a different computer. If it isn't recognized on a different computer you have a hardware problem. Good luck!

  • HT5271 Where on my mac do I find library?  I am trying to fix a blocked plug in and the directions to do so say I need to go to the /library/internet plug ins (disabled) folder.  no where to be found??

    Where on my mac do I find library?  I am trying to fix a blocked plug in and the directions to do so say I need to go to the /library/internet plug ins (disabled) folder.  no where to be found??

    Thank you, found it!  However, my real issue is a blocked plug in.  Another person was having the same issue and they where told to do this:
    Additional Information
    If you need to re-enable an out-of-date version of Flash Player, you can do the following:
    Navigate to the /Library/Internet Plug-Ins (Disabled) folder.
    Drag "Flash Player.plugin" into /Library/Internet Plug-Ins.
    If the browser is running, quit and restart it.
    Which I do not have a Internet Plug-Ins (disabled) folder?  Can I just drag the Flash Player Plug In to the trash and start over?  Help!!

  • I have been trying to develop digital pictures from my ipad2. I don't have iPhoto. When I develop them from Walgreens or snapfish they turn out very fuzzy/blurry. They are crystal clear on my iPad. I know it's not the camera because I developed them befor

    I have been trying to develop digital pictures from my ipad2 photo library. I don't have iPhoto. When I develop them with snapfish or Walgreens they are fuzzy and blurry (low res/pixels). I know it's not the camera because I have printed these same photos before. They are crystal clear on my iPad. I don't know what to try next .

    Contact Snapfish and Walgreens customer/technical support in regards to their digital photo developing service.

  • While trying to fix a blocked plug-in problem, I uninstalled Adobe Flash Player and now cannot reinstall.  Help!! Please.

    I am trying to fix a blocked plug-in.  I unstalled Adobe Flash Player and now cannot re install.  Any help would be appreciated.

    More info. Why can't you reinstall? Something is preventing reinstalling? If so what? What occurs when you try?
    Or you don't know how to reinstall?

  • I keep trying to install ad blocker (FF4) - and it does not work!

    keep trying to install ad blocker - shows it installing, but cannot find it on my add on/extensions list after and does not work!

    ADOBE FLASH PLAYER 10.3.183.5 INSTALLATION/ AND OPERATIG FAILURE WITH INT. EXP.9
    Hello, I have spent four days and half of those nights trying to get this accursed thing to properly install and run. The damned thing indicates that it was successfully installed, but would not work and all programes that needed it, kept telling me I needed to instal it. Also, it appeared in my installed program list, but had no file size against it.
    I had an hour on line with my Norton Tecnician, having suggested to him that Norton may be blocking it. He allegedly diconnected Norton and tried it, then told me the problem was not Norton.
    WRONG!
    I uninstalled it again for the millionth time, opened my Norton 360 and temporarily turned my Anti-virus off for 15 minutes, I then installed flash again and immediately re-set my Norton. In my case:
    PROBLEM SOLVED!!
    ps; I was signed in ( my username showing at top of page), but this forum would not display any button to add a reply or start a thread.
    SOLUTION: Signed in again. Crazy or what?
    Have a nice day.

  • HT204266 'm trying to change my payment method to none but I can not. Can someone help me, please?

    I tried to go into my account as well in setting to tried to change my payment method to none but I can not change it. I do not want my payment method on my account any more. I can not even download free apps because it states that my payment information is wrong, but I know that it's not. What can I do to delete my payment information? Please if anyone can help, please send me any suggests.

    Turn off FaceTime and iMessage.
    Wait a few hours then turn them back on.

  • I'm trying to develop a PKI enabled plugin for firefox using add-on builder. how do you call a java applet using add-on javascript on add-on builder ?

    i have a signed applet which encrypts and digitally signs text information. i need to call this applet from the add-on javascript on firefox's add-on builder . how do i do it ?
    i've tried using contentScript and contentScriptFile to load the html file which calls the applet vis applet tag , it doesnt work.
    this is the error which croped up:
    Java Plug-in 1.6.0_26
    Using JRE version 1.6.0_26-b03-383-11A511 Java HotSpot(TM) 64-Bit Server VM
    User home directory = /Users/sreer1990
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    java.lang.NullPointerException
    at sun.net.www.ParseUtil.toURI(ParseUtil.java:261)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:861)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at sun.plugin.PluginURLJarFileCallBack.downloadJAR(PluginURLJarFileCallBack.java:81)
    at sun.plugin.PluginURLJarFileCallBack.access$000(PluginURLJarFileCallBack.java:48)
    at sun.plugin.PluginURLJarFileCallBack$2.run(PluginURLJarFileCallBack.java:150)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin.PluginURLJarFileCallBack.retrieve(PluginURLJarFileCallBack.java:127)
    at sun.net.www.protocol.jar.URLJarFile.retrieve(URLJarFile.java:186)
    at sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:50)
    at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:70)
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:104)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.connect(CachedJarURLConnection.java:201)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFileInternal(CachedJarURLConnection.java:145)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFile(CachedJarURLConnection.java:91)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(DeployURLClassPath.java:752)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$800(DeployURLClassPath.java:631)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(DeployURLClassPath.java:698)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(DeployURLClassPath.java:690)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.<init>(DeployURLClassPath.java:652)
    at com.sun.deploy.security.DeployURLClassPath$3.run(DeployURLClassPath.java:400)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(DeployURLClassPath.java:389)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(DeployURLClassPath.java:366)
    at com.sun.deploy.security.DeployURLClassPath.getResource(DeployURLClassPath.java:230)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Plugin2ClassLoader.java:966)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Plugin2ClassLoader.java:955)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:134)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:250)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:180)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:240)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:180)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:161)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:675)
    at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3046)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1498)
    at java.lang.Thread.run(Thread.java:680)
    Exception: java.lang.NullPointerException

    Try posting at the Web Development / Standards Evangelism forum at MozillaZine. The helpers over there are more knowledgeable about web page development issues with Firefox. <br />
    http://forums.mozillazine.org/viewforum.php?f=25 <br />
    You'll need to register and login to be able to post in that forum.

  • Trying to understand the various methods of the Office Web API

    Looking at the Office Web API, I don't see explanations, details of what a specific Office Web API method does. Is one suppose to experiment to discovered what they do, or is there some place I need to look for details?
    Thanks
    Jim

    ​Hi JimBassett,
    What do you mean by "Office Web API"? Do you mean javascript api for office? If so, I think you could turn to the link below for explanations, details of the methods.
    #JavaScript API for Office
    https://msdn.microsoft.com/en-us/library/office/fp142185.aspx
    If you mean the Office 365 API, here is a article for your reference:
    #Overview of developing on the Office 365 platform​
    https://msdn.microsoft.com/en-us/office/office365/howto/platform-development-overview
    Best Regards,
    Edward
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • Firefox stops responding immediately after startup. I've tried all the recommended troubleshooting methods and cannot figure out why.

    I have tried all of the recommended troubleshooting methods but none of them seem to work. This issue began despite no change being made to Firefox, or my computer; it just spontaneously stopped responding after launch.
    Not only does Firefox stop responding, but it also prevents any other programs from being launched, and make already launched programs extremely slow. Furthermore, once it stops responding, it becomes impossible to get rid of; the only way is to log off, or restart the computer entirely.

    Do a malware check with several malware scanning programs on the Windows computer.
    Please scan with all programs because each program detects different malware.
    All these programs have free versions.
    Make sure that you update each program to get the latest version of their databases before doing a scan.
    *Malwarebytes' Anti-Malware:<br>http://www.malwarebytes.org/mbam.php
    *AdwCleaner:<br>http://www.bleepingcomputer.com/download/adwcleaner/<br>http://www.softpedia.com/get/Antivirus/Removal-Tools/AdwCleaner.shtml
    *SuperAntispyware:<br>http://www.superantispyware.com/
    *Microsoft Safety Scanner:<br>http://www.microsoft.com/security/scanner/en-us/default.aspx
    *Windows Defender:<br>http://windows.microsoft.com/en-us/windows/using-defender
    *Spybot Search & Destroy:<br>http://www.safer-networking.org/en/index.html
    *Kasperky Free Security Scan:<br>http://www.kaspersky.com/security-scan
    You can also do a check for a rootkit infection with TDSSKiller.
    *Anti-rootkit utility TDSSKiller:<br>http://support.kaspersky.com/5350?el=88446
    See also:
    *"Spyware on Windows": http://kb.mozillazine.org/Popups_not_blocked
    *https://support.mozilla.org/kb/troubleshoot-firefox-issues-caused-malware

  • Trying to understand the getResource method

    Hi!
    I'm writing a simple game and I'm using a game framework for java. The framework uses the getResource("path") method on creating every texture. The constructor only accepts the relative path. My problem is I don't want image files to be placed in the build folder. I would like to create textures from an absolute path. I don't want to modify the framework code.
    In the Class Loader javadoc I've found that getResorce method executes the findResorce method if it fails on finding the resource. The findResource method should be overriden in a Class Loader implementation. How can I do it?
    Thanks.

    morgalr wrote:
    tom_ex wrote:
    Hi!
    I'm writing a simple game and I'm using a game framework for java. The framework uses the getResource("path") method on creating every texture. The constructor only accepts the relative path. My problem is I don't want image files to be placed in the build folder. I would like to create textures from an absolute path. I don't want to modify the framework code.
    In the Class Loader javadoc I've found that getResorce method executes the findResorce method if it fails on finding the resource. The findResource method should be overriden in a Class Loader implementation. How can I do it?
    Thanks.It does this so you can JAR your application, which gives you the ability to distribute an executable with all of your resources included. So your buds will not have to worry about if they have the support files installed to run your application or not.I understand the intention, but it's rather an opposite of what I'm trying to do. In my idea the game on it's first running aks the user for a path. The path points a place where the sounds and images should by downloaded i.e. from an ftp server. On the later runnings the game already know where the images, etc have been downloaded and uses them.

  • HT2729 i have been trying to copy videos from my pc to ipad but it is not working .. i have tried the "drag and drop method and even add files to library but to no avail please help

    please help me regarding moving videos from pc to ipad .. i have ipad 2 wih ios5 and windows xp.. ihave tried add files to library and drag and drop method but they are not working.. what should i do

    Are you trying to add videos to itunes or to your ipad from itunes.
    Your question is very confusing.

  • Can't get login script to work - tried both prefs and tty methods ...

    Calling all you script gurus ...
    I'm trying to auto-mount a sparse image on login (why? I got my 17" stolen along with the data - i'm using an encrypted image as my document repository now).
    I can't get this simple script to run using either method (modifying the LoginWindow plist OR the apple suggested method of adding the section into the /etc/ttys file.
    I've tested the script file from the terminal and all works fine.
    Any ideas?
    Thanks
    Paul
    MBP 2.1GHz, iBook 12" 1GHz, G3 PowerMac   Mac OS X (10.4.6)   Stolen Powerbook 17" S# W8505160RJ3 - reward offered

    I personally haven't had much success with the '/etc/ttys' method for specifying login hooks either...
    On the other hand, the ".plist" method has worked well for me in the past. Just in case you weren't aware, note that the the file for specifying a "login hook" via ".plist" file has changed in "Tiger" compared to "Panther". It was never the "loginwindow.plist", which is used for specifying "Login Items", but rather the "com.apple.loginwindow.plist" file, but unlike "Panther" which used "/Library/Preferences/com.apple.loginwindow.plist" (a security issue for which Apple was rightly criticized), in "Tiger" Apple wisely changed the location to a more secure directory, ie. "/private/var/root/Library/Preferences/com.apple.loginwindow.plist". The current procedures for specifying "login hooks" via ".plist" file can be found in this document:
    http://docs.info.apple.com/article.html?artnum=301446
    But as far as mounting a disk image is concerned, adding the mounted volume (rather than a script to mount the disk image) to "Login Items" should be sufficient to initiate the mounting process...

Maybe you are looking for

  • Inter-Org Mailbox moves from Exchange 2007 to Exchange 2013

    G'Day All, Is it possible to move Exchange 2007 mailboxes to Exchange 2013 in a different forest? Both environment has all the required patches and service packs. There is a two way trust, and I don't want to introduce Exchange 2010 CAS in the source

  • Suppressing decimal places in the screen fields

    Hello All, I need to display a quantity fields which is referring to the domain MENGE(10+3) While displaying, it appears as 1234567890.000 here how to suppresss the zero's. Screen field is got from program(not dictionary) can you help me out. Regrds,

  • Slideshow blank image

    When I try to preview or play Slideshow on LR 1.1 (Windows XP)the software does not display the image (blank black screen), although in preview it apparently scrolls through the film strip. Am I doing something wrong? Thanks Nick

  • Choppy movie play back-everything working slow!!!

    I have an external hard drive, lots of space, but with only about 35 min of video in my I-movie 4 program I am getting a choppy playback that skips along without smooth play! I have the playback set to the standard setting (Smooth Playback) and still

  • JCA 1.0 ConnectionManager

    Hi Binod, I have bounced into a problem regarding jca. 1. I have a implementation of ConnectionRequestInfo that has the properties "type" and "method" (with getters and setters). I have implemented equals and hashCode methods so i can differ to Conne