Need an example of how to use java.nio.channels.FileLock

Hi,
I need to use the Filelock, but can�t find any examples on how to implement it -
is it still used in Java 5.0?

Would this be the correct way to check whether the file is already locked?
public static void main(String[] args) throws Exception {
     FileOutputStream fos = new FileOutputStream("data.txt");
     FileLock fl = fos.getChannel().tryLock();
     if (fl != null) {
     System.out.println("Locked File");
     Thread.sleep(30000);
     fl.release();
     System.out.println("Released Lock");
     else{
          System.out.println("File is already locked!");
     fos.close();
     }

Similar Messages

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • How to use Java NIO to implement disk cache for serialized java objects

    Hi,
    I have a cache (implemented as hahstable etc.) that contains java objects (mostly strings) and swaps objects from runtime memory to the disk and back based on some algorithms. Currently, the reading and writing from the disk is implemented using java.io.* package i.e. fileInputstream and FileOutputStream. Essentially, I serialize the java object and write to the disk and the deserialize and give it back to the Hashtable cache.
    The performance of swapping from disk to memory is kinda slow. I have read that memory mapping would improve the performance.
    My idea is to do the following:
    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBuffer for that but then I have the following questions. I will not store objects in the hashtable anymore.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?
    As you can see, I am beginner in memory mapped io and need help.

    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBufferThis is a good idea, one that I have worked on. It involves quite a bit of manipulation with temporary buffers and a deep working knowledge of object serialization.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?The best way to handle this is do a two-step process, cutting the file into two pieces and gluing it back together where the original one is...
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.It is hard. Wrapping the streams and making the IO work properly is not the challenge however. The hard part comes in hacking the object streams. The object input/output streams use a ClassDescriptor object which only gets written once/ read once. This shouldn't be a problem if you will read/write the entire file at once, but will bring you grief if you want random access to your objects. You will also need an indexing mechanism to support random access.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?I guess it depends on your needs. Do you require random access to objects? NIO provides some performance gains, but mostly for very large amounts of data (>10M in my experience).
    You can always write all your objects into the same file using normal io techniques and you can still generate an index and acheive random access. It might be easier...
    Good luck

  • How to use java.nio on Mac?

    I am getting the error "cannot find symbol" on "Path", "FIles", etc. I am using javac and java 1.8.0_20 on Mac OS X 10.9.2 and the Terminal. Thanks.
    import java.io.*;
    import java.nio.*;
    class a{
         public static void main(String args[]) throws IOException{
              Path directorio = "/Users/Josue/Desktop/";
              try {
                   DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
                   for( Path file: stream ){
                        System.out.println(file.getFileName());
              catch ( DirectoryIteratorException x ){
                   System.err.println(x);

    Before you answer, I got the solution (from somewhere else), it was because I didn't import explicitly the  classes Files, Paths, etc.
    But I don't understand why  .*  didn't work to do it?

  • Detect loss of socket connection using java.nio.channels.Selector

    I'm using the nio package to write a "proxy" type application, so I have a ServerSocketChannel listening for incoming connections from a client and then create a SocketChannel to connect to a server. Both SocketChannels are registered to the same Selector for OP_READ requests.
    All works fine, until either the client or server drops the connection. How can I detect this has happened, so my proxy app can drop the other end of the connection ?
    The Selector.select() method is not triggered by this event. I have tried using Selector.select(timeout) and then checking the status of each channel, but they still show isConnected()=true.
    Thanks,
    Phil Blake

    Please don't cross post.
    http://forum.java.sun.com/thread.jsp?thread=184411&forum=4&message=587874

  • Is java.nio.channels.FileLock thread safe ?

    Hello,
    I want to lock a file in exclusive mode. The 1.4.2 doc says the followings:
    File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
    File-lock objects are safe for use by multiple concurrent threads.
    I'm confused. If They are not suitable for controlling access to a file by multiple threads within the same virtual machine, How can they be safe for use by multiple concurrent threads ?
    thanks in advance...

    I think it means that you still need to synchronize your threads around the code that obtains the lock and writes data to the file.

  • Java.nio.channels.FileChannel jar file

    Hi
    I have used java.nio.channels.FileChannel package in my program.
    where can I get the jar file which has the above package?
    Thanx

    i give here sample code.. use this it will work fine..
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    public class copyImage
    public static void main(String [] args) throws IOException
    try {
    // Create channel on the source
    FileChannel srcChannel = new FileInputStream("dragonfly.jpg").getChannel();
    FileChannel dstChannel =new FileOutputStream("1.jpg").getChannel();
    // Copy file contents from source to destination
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    // Close the channels
    srcChannel.close();
    dstChannel.close();
    } catch (IOException e) {
    }

  • How to use Java Web Start with EJB ?

    hi forum...
    how to use Java WebStart with EJB ?
    examples ?
    thanks...
    mindu

    Mindu,
    WebStart will work with EJB. I use it with WebLogic Server. You have to make sure and deploy the weblogic.jar file - sign it if needed.
    For signing information, look here,
    http://java.sun.com/products/javawebstart/1.2/docs/developersguide.html
    Dan

  • How to use java source in Oracle when select by sqlplus.

    How to use java source in Oracle when select by sqlplus.
    I can create java source in Oracle
    import java.util.*;
    import java.sql.*;
    import java.util.Date;
    public class TimeDate
         public static void main(String[] args)
    public String setDate(int i){
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(new Date((long)i*1000));
    System.out.println("Dateline: "
    + calendar.get(Calendar.HOUR_OF_DAY) + ":"
    + calendar.get(Calendar.MINUTE) + ":"
    + calendar.get(Calendar.SECOND) + "-"
    + calendar.get(Calendar.YEAR) + "/"
    + (calendar.get(Calendar.MONTH) + 1) + "/"
    + calendar.get(Calendar.DATE));
    String n = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE);
         System.out.print(n);
         return n;
    I have table name TEST
    ID DATE_IN
    1 942685200
    2 952448400
    When I write jsp I use method setDate in class TimeDate
    The result is
    ID DATE_IN
    1 1999/11/16
    2 2003/7/25
    Thanks you very much.

    It is unclear where you are having a problem.  Is your issue at runtime (when the form runs in the browser) or when working in the Builder on the form?
    Also be aware that you will need to sign your jar and include some new manifest entries.  Refer to the Java 7u51 documentation and blogs that discuss the changes.
    https://blogs.oracle.com/java-platform-group/entry/new_security_requirements_for_rias
    http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/manifest.html

  • Req any examples of how to use a USB midi controller​/keyboards with Labview TIA

    Req any examples of how to use a USB midi controller/keyboards with Labview TIA

    Hi,
    To access the MIDI ports you will need to call the Windows SDK. To send MIDI commands is relatively easy, here is an example that shows you how to send data to a MIDI controller or keyboard.
    As far as input goes, this is the hard part. There are a series of functions that you need to call to open up the device, set some buffers and and possibly a callback to get notifications on the incoming data.
    Reading MIDI data will not be an easy task, your best bet will be to implement this in a DLL and call that DLL in LabVIEW, there should be some code available o the web.
    = "http://msdn.microsoft.com/library/default.asp?url​=/library/en-us/multimed/htm/_win32_multimedia_... is a link to the Windows multimedia functions that you could use for MIDI input.
    Let me know if you have any further questions.
    Regards,
    Juan Carlos
    N.I.

  • How to use java integrate with ondemand

    Hi All,
    As i'm new to integration, can anyone help me to use java integrate with ondemand that inserts some records in ondemand and deletes some records from ondemand in secheduled interval basis.?
    Thanks in advance..!
    regards
    sowm

    Greetings,
    hi forum...
    how to use Java WebStart with EJB ? examples ?Well, for starters these are complementing, not 'cooperating', technologies. I presume, since EJB's do not - directly, at least - communicate with a web browser, that you intend for "Java WebStart" to somehow invoke an EJB?? Java WebStart is a technology for running client-side (Java) applications from the web browser - perceptively, the application resides on the server, but technically it, like an applet, is downloaded to the client and run there. Unlike an applet, however, it is not constrained by "sandbox" restrictions and does not have to be re-downloaded each time it is invoked - though the process allows for automagically updating the client-side with new versions of the application. ;) So, with this in mind, to "use Java WebStart with EJB" means little more than deploying an EJB client application with Java WebStart as the distribution channel.
    thanks
    minduRegards,
    Tony "Vee Schade" Cook

  • How to use Java Beans In JSTL?

    Hi
    I want to know how to use Java bean in JSTL
    please explain this with giving any one example.
    Thanks-
    Swapneel

    A bean is obtain by <jsp:useBean> tag nd once bean is obtained we can get its property by using getProperty tag.

  • How to use java in Form 9i

    hi
    i want to ask how to use java in form 9i, can any one plz. give me an example
    thanks & best regards!
    SoftDesire

    From an earlier posting:
    "Have a look in the online help for "Java Importer", PJC and "Java Bean".
    There are also some paper on otn.oracle.com/products/forms
    Click to view the papers and you will see a couple which should how to integrate Forms and Java.
    Hope this helps.
    Grant Ronald
    Forms Product Management"
    HOpe this helps.
    Grant

  • How to use Java WebStart with EJB ?

    hi forum...
    how to use Java WebStart with EJB ? examples ?
    thanks
    mindu

    Greetings,
    hi forum...
    how to use Java WebStart with EJB ? examples ?Well, for starters these are complementing, not 'cooperating', technologies. I presume, since EJB's do not - directly, at least - communicate with a web browser, that you intend for "Java WebStart" to somehow invoke an EJB?? Java WebStart is a technology for running client-side (Java) applications from the web browser - perceptively, the application resides on the server, but technically it, like an applet, is downloaded to the client and run there. Unlike an applet, however, it is not constrained by "sandbox" restrictions and does not have to be re-downloaded each time it is invoked - though the process allows for automagically updating the client-side with new versions of the application. ;) So, with this in mind, to "use Java WebStart with EJB" means little more than deploying an EJB client application with Java WebStart as the distribution channel.
    thanks
    minduRegards,
    Tony "Vee Schade" Cook

  • How to use Java as a Front-end app

    how java application can be used as the Front-end interfaces to Forte based
    applications???
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    Rajiv,
    If you have Forte's WebEnterprise product, and Forte version 3.0.G.x or
    later, you have the ability to export an IIOP interface for any Forte
    service object. In fact, you can go one step further and generate a Java
    interface that "hides" the IIOP issues from the developer. The way you do
    this is to do the following:
    1) From the partitioning workshop, double click on the service object you
    wish to expose as an IIOP interface. This will bring up the Service Object
    Properties dialog.
    2) Off the Export tab, set the External Type drop down to IIOP. If IIOP is
    not an available option in the drop down list then you do not have
    WebEnterprise install.
    3) From here you need to set up the necessary IIOP configuration parameters
    (see the documentation for details on the specifics of what the parameters
    control).
    4) If you want to have Forte generate a JavaBean interface and the necessary
    Java classes to be called by your application then make sure you select the
    Java parameter at the bottom of the Configuration dialog. If IDL is
    selected then Forte will generate a generic IDL interface.
    5) When you make your distribution Forte will generate the Java classes for
    you.
    This mechanism works very well for accessing a Forte service object from a
    Java application.
    Good Luck!
    Jeff Wille
    -----Original Message-----
    From: Rajiv Srivastava <[email protected]>
    To: [email protected] <[email protected]>
    Date: Wednesday, December 09, 1998 2:03 PM
    Subject: how to use Java as a Front-end app
    how java application can be used as the Front-end interfaces to Forte based
    applications???
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

Maybe you are looking for

  • EJB 3.0 Web service fail to deploy when ws result is on a diff lib project

    I'm trying to develop a web service using EJB 3.0 with annotations. I'm using Netbeans 5.5 EE. The web service should returns an object declared on another Netbeans project. ( a library.jar). Netbeans compiles everything alright, although when I depl

  • Blob download issue

    Hi , all. Why that code:         select some_csv_blob         from somewhere         where someone = somewhat        v_mime:= 'text/csv';        v_file_name:= 'some_file_with_a_strange_name';        OWA_UTIL.mime_header (NVL (v_mime, 'application/oct

  • Carriage Return

    Hi Friends, Few days back one of clients of my company had a problem with carriage Returns in the data.To make it simple we take column data from the tables and output it to a flat file like notepad onto the server.This process is repeated for a numb

  • Iphone remove multiple photos

    how do you remove large amounts of photos from iPhone?  I see no way of doing this from iPhone itself.. and when I connect iPhone to my MacBook Pro I cannot see it in Finder or anywhere else (********) here http://www.gottabemobile.com/2012/05/28/how

  • I downloaded the ios7 onto my Ipad2 and now I can't get online!

    I am at a loss!  I am not technically knowledgable at all.  I downloaded the ios7 onto my Ipad and now its telling me the ipad isnt connected to the server. Then I looked somewhere within the ipad itself and saw a whole list of things that said it cr