Java.nio.FileChannel  tryLock() method does not lock!!!

Hello,
I have the following:
           RandomAccessFile raf = new RandomAccessFile(file, "rw");
           try {
                 lock = raf.getChannel().tryLock();
          } catch (OverlappingFileLockException e) {
                  System.out.println("File is locked"); // this never gets printed
           if (lock != null) {
                  // successfully acquired a lock
                  System.out.println("acquired lock!!!"); // this gets printed alright
                  // check if lock is valid
                  System.out.println("is this lock valid?  "+lock.isValid()); // it always is when I run my app
                  // do stuff with the file
          ....Note that I do NOT close the channel, which would make the lock invalid.
Well, as far as I know, the code above tries to acquire an EXCLUSIVE lock (no read or write) on a file. It means that no other java application should be able to access that file, right?
My problem is that I can still open that file with a second instance of my app, regardless of the lock.
What am I missing?
PS: don't know if it's relevant, but I do this right AFTER acquiring the lock:
     InputStream stream = Channels.newInputStream(raf.getChannel());
     XMLDecoder d = new XMLDecoder(new BufferedInputStream(stream));                       

Thanks for the answer, mlk.
Well, I went through MSDN to find no answer. Anyway, now I noticed tryLock() blocks, and it shouldn't. I ran two instances of my app and the second one keeps waiting till I release the lock created on the first one!!! Here's some code:
            try
                lock = channel.tryLock();
                System.out.println("File not locked");
            catch (OverlappingFileLockException e)
                // File is already locked in this thread or virtual machine
                System.out.println("File locked");
             try
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        System.in));
                String str = "";
                while (str != null)
                    System.out.print("> prompt ");
                    str = in.readLine();
                    if (str.equalsIgnoreCase("status")) {
                        System.out.println("lock = "+lock);
                    } else if (str.equalsIgnoreCase("exit")) break;
...As stated in the API docs, tryLock() should return immediately. Therefore, the 'lock = channel.tryLock();' should either return cleanly or throw an exception. Then, no matter what, 'prompt >' should appear in the console. Except it doesn't for the second instance. Exiting the first instance makes the second one print out 'prompt'. I believe this shows tryLock() was blocking the execution. Am I missing something?
Not being able to use file lock functionality has been annoying me for quite some time now. Urgh!!!!
Has someone used it on Windows with success? Is there another way of doing it (I know one could use native code, but I could not find example) ?
Thanks

Similar Messages

  • Hashmap containsKey() method does not appear to work

    Hashmap containsKey() method does not appear to work
    I have an amazingly simple custom class called CalculationKey, with my own amazingly simple custom equals() method. For some reason when I call my containsKey() method on my HashMap it does not use my defined equals method in my defined key class. Do hashmaps have their own tricky way for establishing whether two keys are equal or not?
    THIS IS MY AMAZINGLY SIMPLE CUSTOM KEY CLASS
    private class CalculationKey
    private LongIdentifier repID;
    private LongIdentifier calcID;
    public CalculationKey(LongIdentifier repID, LongIdentifier calcID)
    this.repID = repID;
    this.calcID = calcID;
    public boolean equals(Object o)
    CalculationKey key = (CalculationKey)o;
    if (key.getCalcID().equals(calcID) &&
    key.getRepID().equals(repID))
    return true;
    else
    return false;
    public LongIdentifier getCalcID()
    return calcID;
    public LongIdentifier getRepID()
    return repID;
    THIS IS MY AMAZINGLY SIMPLE CALLS TO MY HASHMAP WHICH ADDS, CHECKS, AND GETS FROM THE HASHMAP.
    private Hashmap calculationResults = new Hashmap();
    public boolean containsCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    if (calculationResults.containsKey(new CalculationKey(repID, calcID)))
    return true;
    else
    return false;
    public Double getCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    return (Double)calculationResults.get(new CalculationKey(repID, calcID));
    public void addCalculationResult(LongIdentifier repID, LongIdentifier calcID, Double value)
    calculationResults.put(new CalculationKey(repID, calcID), value);
    }....cheers

    You can make a trivial implementation to return a
    constant (not recommended)What do you mean by that? Hmm.. I guess you mean that
    you shouldn't use the same constant for all objects?
    But don't see the int value of an (immutable) Integer
    as constant?
    /Kaj
    You can write hashCode to just always return, say, 42. It will be correct because all objects that are equal will have equal hashcodes. Objects that are not equal will also have equal hashcodes, but that's legal--it just causes a performance hit.
    The value is that it's really really simple to implement: public int hashCode() {
        return 42;
    } So you can use it temporarily while you're concentrating on learning other stuff, or during debugging as a way to confirm that the hashCode is not the problem. (Returning a constant from hashcode(), rather than computing a value, is always legal and correct, so if something's behaving wrong, and you replace your hashCode method with the one above, and it still breaks, you know hashCode isn't the problem.)
    The downside is that you're defeating the purpose of hashing, and any non-trival sized map or set is going to have lousy performance.
    For a decent hashCode recipe, look here:
    http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

  • Why is the giving me this error (method does not return a value) PLEASE !!

    I have this code and it is giving me this error and I don't know how to fix it
    can anyone out there tell me why
    I have included the next line of code as I have had problems in the curly brackets in the past.
    The error is
    "Client.java": Error #: 466 : method does not return a value at line 941, column 3
    Please help
    THX TO ALL
    private Date DOBFormat()
        try
          if
            (MonthjComboBox.getSelectedItem().equals("") || 
             DayjComboBox.getSelectedItem().equals("") ||
             YearjComboBox.getSelectedItem().equals("")){
          else
            String dateString = StringFromDateFields();
            SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
            Date d = df.parse(StringFromDateFields());
            System.out.println("date="+d);
            return d;
        catch (ParseException pe)
          String d= System.getProperty("line.separator");
          JOptionPane.showMessageDialog( this,
           "Date format needs to be DD/MM/YYYY,"+ d +
           "You have enterd: "+ StringFromDateFields()   + d +
           "Please change the Date", "Date Format Error",
           JOptionPane.WARNING_MESSAGE);
          return  null;
      //File | Exit action performed
    public void jMenuFileExit_actionPerformed(ActionEvent e) {
      System.exit(0);
      }

    Fixed it needed to have a return null;
    this is the code
    if
            (MonthjComboBox.getSelectedItem().equals("") ||
             DayjComboBox.getSelectedItem().equals("") ||
             YearjComboBox.getSelectedItem().equals("")){
            return null;

  • Java.lang.IllegalArgumentException: Session: null does not exist

    These days I am getting an exception (java.lang.IllegalArgumentException: Session: null does not exist) when I restart the weblogic managed server. I have a work around to get away with this error. I completely delete the dataspace from ALDSP console and redeploy the artifacts jar file. This is a tedious process. Can anyone suggest a permanent fix to resolve this issue.
    ALDSP version: 3.01
    Weblogic Server: 9.2.2
    Thanks.

    Hey ,Can you please help me?can you tell me how you resolved this issue.Our production is down due to
    java.lang.IllegalArgumentException: Session: null does not exist.
         at com.bea.dsp.management.persistence.primitives.ServerPersistencePrimitives.getDataspaceRoot(ServerPersistencePrimitives.java:118)
         at com.bea.dsp.management.persistence.primitives.ServerPersistencePrimitives.getDataspaceRoot(ServerPersistencePrimitives.java:73)
         at com.bea.dsp.management.activation.ActivationService.dataSpaceAlreadyExists(ActivationService.java:342)
         at com.bea.dsp.management.activation.ActivationService.setRequestHandlerClassLoader(ActivationService.java:206)
         at com.bea.ld.server.bootstrap.RequestHandlerListener.postStart(RequestHandlerListener.java:46)
         Truncated. see log file for complete stacktrace.
    Its urgent plz

  • Keytool error: java.lang.Exception: Keystore file does not exist:

    Hi All,
    While listing the keystore using the command keytool -list, I got the error message that
    keytool error: java.lang.Exception: Keystore file does not exist: C:\Documents and Settings\subramanian.arivalag\.keystore
    I noticed there is no file .keystore in the above mentioned directory. What's this .keystore file? Will it be created automatically or should we create manually?
    Already I created a keystore using -genkey command and received CA authority also.
    Kindly provide me more details about .keystore file and how to handle this error.

    If you specified a keystore filename when you created the keystore
    i.e. keytool -genkey -alias jboss-ssl -keyalg RSA -keystore my_name.keystore -validity 3650
    then you need to specify the same keystore when you export the cert
    i.e. keytool -export -alias jboss-ssl -keystore my_name.keystore –file my_name.cer

  • IOS 6 showFeedbackCaptionAndDoAction() javascript method does not draw consistently

    Hi!
    The issue describe below seem to only appear in iOS 6
    CPlayerLib.js judge() -> showFeedbackCaptionAndDoAction() javascript method does not draw the Feedback Caption consistently
    sometime the feedback does not appear, I see it in the dom tree but the canvas is not drawn, the Div capturing the click is always present. Strangely when I scroll the page a bit it shows up.
    Thanks

    Ok I found a way to fix it.
    In CPlayerLib.js cp.show method in the for loop within the if (htmlItem) I added a setTimeout(function() { htmlItem.style.webkitTransform = "scale3d(1,1,1)"},100) and it now force the canvas to repaint.
    Related issue:
    http://stackoverflow.com/questions/11002195/chrome-does-not-redraw-div-after-it-is-hidden

  • ATMTag.java:5: package javax.servlet does not exist

    My j2ee jdk1.4.2 is not supporting javx package.
    i already set all pathh and class path.
    anybody can help me.
    details are given below ::
    C:\AVA\J2EE Programs\JSP\JSPCustomTag>javac ATMTag.java
    ATMTag.java:5: package javax.servlet does not exist
    import javax.servlet.*;
    ^<br>
    ATMTag.java:6: package javax.servlet.http does not exist
    <br>
    import javax.servlet.http.*;
    <br>
    ATMTag.java:18: cannot resolve symbol
    symbol : class TagSupport
    location: class ATMTag
    public class ATMTag extends TagSupport{
    <br> ^
    ATMTag.java:29: cannot resolve symbol
    symbol : class JspTagException
    location: class ATMTag
    public int doStartTag() throws JspTagException{
    <br> ^
    ATMTag.java:31: cannot resolve symbol
    symbol : class JspWriter
    location: class ATMTag
    <br> JspWriter out =pageContext.getOut();
    ^
    ATMTag.java:31: cannot resolve symbol
    symbol : variable pageContext
    location: class ATMTag
    <br> JspWriter out =pageContext.getOut();
    ^
    ATMTag.java:56: cannot resolve symbol
    symbol : variable pageContext
    location: class ATMTag
    pageContext.getOut().write(str);
    <br> ^
    ATMTag.java:60: cannot resolve symbol
    symbol : variable EVAL_PAGE
    location: class ATMTag
    return EVAL_PAGE;
    ^
    8 errors

    When compiling servlets etc, you need to include in your classpath a jar file with all the javax.* classes defined in it.
    For Tomcat this is called servlet.jar and is in (I think) [TOMCAT_HOME]/shared/lib or /common/lib
    For J2EE 1.4 Server, the jar is [J2EE_HOME]/lib/j2ee.jar
    Where the _HOME directory is the directory where you installed J2EE.
    Include this jar file in your classpath when compiling.
    Good luck,
    evnafets

  • Cannot optimize volume - Receive error "The specified extrinsic Method does not exist"

    When I try to optimize a volume on a server running Windows Server 2012 (R1). I receive the below error. This volume is an ISCSI target to our Compellent SAN. Other Servers don't have an issue with volumes created on the same SAN and I have already ran ChkDsk
    and it returned no errors. Oddly enough I can run a "Defrag T: /D" but a "Defrag T: /O" returns
    "Incorrect Function. (0x80070001)" (Incidentally an "Optimze-Volume T -Defrag" also works) 
    Any Ideas? I'm stumped!
    Command:
    Optimize-Volume -DriveLetter T -Verbose
    Error:
    VERBOSE: Invoking slab consolidation on iSCSI_SAN01_ExchLogFiles (T:)...
    VERBOSE: Slab Analysis:  100% complete.
    optimize-volume : The specified extrinsic Method does not exist.
    At line:1 char:1
    + optimize-volume -DriveLetter T -Verbose
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : MetadataError: (MSFT_Volume (Ob...2-a802-ba7e...):ROOT/Microsoft/...age/MSFT_Volume) [Optimize-Volume], CimException
        + FullyQualifiedErrorId : MI RESULT 17,Optimize-Volume

    I did stumble upon that article as well and working through it didn't help. This is an Exchange 2013 server but I wouldn't think that that would exclusively cause a problem like this (unless there is something under the hood that Exchange 2013 is secretly
    doing). The C drive is for the OS, the M drive is for the Exchange DB, and the
    T drive is for the Logs.  The C drive is "directly" connected and the M and T drives are on the same SAN (different LUNs) via iSCSI. This is running as a virtual guest on VMWare ESXi v5.5.  I have other servers setup the
    same way (not Exchange servers though) with drives on the iSCSI SAN and there are no issues when I run those Optimize-Volume commands. Here is some more output from the console:
    PS C:\Users\administrator> Optimize-Volume -DriveLetter T -Analyze -Verbose
    VERBOSE: Invoking slab consolidation on iSCSI_SAN01_ExchLogFiles (T:)...
    VERBOSE: Slab Analysis: 0% complete...
    Optimize-Volume : The specified extrinsic Method does not exist.
    At line:1 char:1
    + Optimize-Volume -DriveLetter T -Analyze -Verbose
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : MetadataError: (MSFT_Volume (Ob...2-a802-ba7e...):ROOT/Microsoft/...age/MSFT_Volume) [Optimize-Volume], CimException
    + FullyQualifiedErrorId : MI RESULT 17,Optimize-Volume
    PS C:\Users\administrator> Optimize-Volume -DriveLetter M -Analyze -Verbose
    VERBOSE: Invoking slab consolidation on iSCSI_SAN01_ExchMailStoreDB (M:)...
    VERBOSE: Slab Analysis: 0% complete...
    Optimize-Volume : The specified extrinsic Method does not exist.
    At line:1 char:1
    + Optimize-Volume -DriveLetter M -Analyze -Verbose
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : MetadataError: (MSFT_Volume (Ob...2-93f1-0050...):ROOT/Microsoft/...age/MSFT_Volume) [Optimize-Volume], CimException
    + FullyQualifiedErrorId : MI RESULT 17,Optimize-Volume
    PS C:\Users\administrator> Optimize-Volume -DriveLetter C -Analyze -Verbose
    VERBOSE: Invoking analysis on (C:)...
    VERBOSE: Analysis: 0% complete...
    VERBOSE: Analysis: 22% complete...
    # ... Repeated ...
    VERBOSE: Analysis: 94% complete...
    VERBOSE: Analysis: 99% complete...
    VERBOSE: Analysis: 100% complete...
    VERBOSE: Analysis: 100% complete.
    VERBOSE:
    Post Defragmentation Report:
    VERBOSE:
    Volume Information:
    VERBOSE: Volume size = 84.48 GB
    VERBOSE: Cluster size = 4 KB
    VERBOSE: Used space = 63.18 GB
    VERBOSE: Free space = 21.29 GB
    VERBOSE:
    Fragmentation:
    VERBOSE: Total fragmented space = 4%
    VERBOSE: Average fragments per file = 1.23
    VERBOSE: Movable files and folders = 153593
    VERBOSE: Unmovable files and folders = 6
    VERBOSE:
    Files:
    VERBOSE: Fragmented files = 2745
    VERBOSE: Total file fragments = 35394
    VERBOSE:
    Folders:
    VERBOSE: Total folders = 4819
    VERBOSE: Fragmented folders = 2
    VERBOSE: Total folder fragments = 2
    VERBOSE:
    Free space:
    VERBOSE: Free space count = 74005
    VERBOSE: Average free space size = 296.00 KB
    VERBOSE: Largest free space size = 409.42 MB
    VERBOSE:
    Master File Table (MFT):
    VERBOSE: MFT size = 308.00 MB
    VERBOSE: MFT record count = 315391
    VERBOSE: MFT usage = 100%
    VERBOSE: Total MFT fragments = 4
    VERBOSE: Note: File fragments larger than 64MB are not included in the fragmentation statistics.
    VERBOSE:
    You do not need to defragment this volume.

  • Pay Method does not exist.

    Hi,
    I 'm trying to load bank details like Bank name, Account No and etc., through HR_PERSONAL_PAY_METHOD_API. Before that i loaded data thru Assignment
    API.
    But i'm getting error 'Pay method does not exits'
    Any one help this issue.
    Thanks in advance.
    DK

    Please provide us exact error, so that we can take a look into and provide you the solution.
    Below is sample api parameters we need to provide...
    hr_personal_pay_method_api.create_us_personal_pay_method
    (p_validate => false
    ,p_effective_date => effective_date
    ,p_assignment_id => assignment_id
    ,p_org_payment_method_id => 123
    ,p_account_type => acct_type
    ,p_account_name => 'XYZ'
    ,p_account_number => acct_num
    ,p_transit_code => routing_num
    ,p_bank_name => 'PQR'
    ,p_bank_branch => 'ABC'
    ,p_percentage => ln_percentage
    ,p_amount => ln_amount
    ,p_priority => priority
    ,p_personal_payment_method_id => l_personal_payment_method_id
    ,p_object_version_number => l_object_version_number
    ,p_external_account_id => l_external_account_id
    ,p_effective_start_date => l_effective_start_date
    ,p_effective_end_date => l_effective_end_date
    ,p_comment_id => l_comment_id
    Please take a look and try once again. Let us know exact error.

  • SetActionListener method does not print anything in the html file...

    Hi
    I want to add the actionlistener from my Javacode, but the setActionListener method does not have any effect on the Html. I can not figure out why. Can someone tell me what I'm doing wrong?
    tnx
    Andras
    public class Links {
    private HtmlPanelGrid topLinks;
    public HtmlPanelGrid getTopLinks() {
    TopLinks links = new TopLinks();
    Class args[] = {ActionEvent.class};
    if (topLinks == null) {
    topLinks = new HtmlPanelGrid();
    }else {
    topLinks.getChildren().clear();
    MethodBinding mb =
    FacesContext.getCurrentInstance().
    getApplication().
    createMethodBinding("#{event.actionevent}", args);
    HtmlCommandLink command = new HtmlCommandLink();
    command.setValue("Link 1");
    command.setActionListener(mb);
    topLinks.getChildren().add(command);
    return topLinks;
    public void setTopLinks(HtmlPanelGrid topLinks) {
    this.topLinks = topLinks;
    generates this html:
    <body>
    <form id="_id0" method="post" action="/Test/event.faces" enctype="application/x-www-form-urlencoded">
    <table>
    <tbody>
    <tr>
    <td><a href="# onclick="document.forms['_id0'['_id0:_idcl'].value='_id0:_id2'; document.forms['_id0'].submit(); return false;">Link 1</a></td>
    </tr>
    </tbody>
    </table>
    <input type="hidden" name="_id0" value="_id0" />
    <input type="hidden" name="_id0:_idcl" /></form>
    </body>
    As you can see there is no sign of the actionListener... :(

    You may completely misunderstand something.
    Don't worry even if you can't see the actionListener in the html.
    There is one in the server side.

  • 30-Pin Adapter does not lock in to iPad Air

    30-Pin Adapter does not lock in to iPad Air?

    This adaptor lets you connect devices with a Lightning connector to many of your 30-pin accessories. Supports analogue audio output, USB audio, as well as syncing and charging. Video output not supported. 
    http://store.apple.com/sg/product/MD823ZM/A/lightning-to-30-pin-adapter

  • The MoveTo method does not accurately preserve version history

    I know this is a tired story ;-) but
    this link says that one cannot update metadata (e.g. ModifiedBy) of previous versions of an SPListItem.
    Using the MoveTo() method of the API does move both the current list item and all previous versions of course, that much is clear.
    But, that method does not 100% preserve the Version History in that if, after it has moved a file, you were to look at the History via the UI, previous versions will have Modified set to the account under which the (in my case) console application has run
    to kick of the MoveTo process etc.
    This differs from moving using the Content & Structure approach where everything is maintained 100%.
    So I deduce that there must be some underlying code using the Content & Structure approach that differs from that using the MoveTo() method.? Is that the case?
    And is the link at the start of this question correct? We cannot then programmatically change the metadata on old versions?
    Thanks,
    Maz

    1. There must be, but not sure if its publicly accessible. You probably have to disassemle (i.e. using ILSpy) and find out.
    2. That's correct, you can't change the metadata of old versions
    Kind regards,
    Margriet Bruggeman
    Lois & Clark IT Services
    web site: http://www.loisandclark.eu
    blog: http://www.sharepointdragons.com

  • My iphone4s does not lock the screen automatically when playing music and charging

    My iphone4s (iso5.1) does not lock the screen automatically with the condition in charging and playing music.
    System has been set to lock the screen in 1 mins.
    Everything goes fine when not in charging, the system can lock well even playing music.
    System can lock as well when all the music playing apps are closed, even when charging.
    I don't think that's my apps' problem, all my music playing apps have the same problem.
    My ipod has the exact same problem described above, I believe that's an iso system bug.

    It's not something i'm familar with but i will forward it internally for investigation. Could you please send me a PM with the IMEI of your phone and the build number? You can find these under Settings -> About phone and Settings -> About phone -> Status.
     - Official Sony Xperia Support Staff
    If you're new to our forums make sure that you have read our Discussion guidelines.
    If you want to get in touch with the local support team for your country please visit our contact page.

  • The control chart in the sampling method does not match the insp. char. Mes

    The control chart in the sampling method does not match the insp. char.
    Message no. QD240
    how solve?????

    You need to compare 'requirement for control chart' and 'control indicator of insp. characteristic'.
    1. Requirement for control chart
    QCC0 > Quality Planning > Basic Data > Sample, SPC > Statistical Process Control > Define Control Chart Type
    See detail for your control chart and check 'requirement' in characteristic type screen area.
    2. Control indicator of insp. characteristic
    QS24
    Check 'control indicator' is suitable for requirement.
    Regards, Do Wook KIM

  • Apple account none payment methode does not appear

    when i creat my apple id the none option in payment methode does not appear . please tell me what I do ?????

    Unless the instructions on this page are followed when creating an account : Create an iTunes Store, App Store, or iBooks Store account without a credit card or other payment method - Apple Support…
    then credit card details will need to be entered before the account can be used to download any item from the store.
    If you are being prompted to review the account then you could see if this post by mountaingoatgirl lets you do so without needing to enter credit card details : https://discussions.apple.com/message/24303054#24303054
    If not then you will either need to enter your credit card details (you should be able to remove it after entering it), or create a new account (and use the instructions on the above link when creating it).

Maybe you are looking for