KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > runtime > internal > adaptor > Locker_JavaNio


1 /*******************************************************************************
2  * Copyright (c) 2004, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Danail Nachev (Prosyst) - bug 185654
11  *******************************************************************************/

12 package org.eclipse.core.runtime.internal.adaptor;
13
14 import java.io.*;
15 import java.nio.channels.FileLock JavaDoc;
16 import java.nio.channels.OverlappingFileLockException JavaDoc;
17 import org.eclipse.osgi.util.NLS;
18
19 /**
20  * Internal class.
21  */

22 public class Locker_JavaNio implements Locker {
23     private File lockFile;
24     private FileLock JavaDoc fileLock;
25     private RandomAccessFile raFile;
26
27     public Locker_JavaNio(File lockFile) {
28         this.lockFile = lockFile;
29     }
30
31     public synchronized boolean lock() throws IOException {
32         raFile = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
33
try {
34             fileLock = raFile.getChannel().tryLock();
35         } catch (IOException ioe) {
36             // print exception if debugging
37
if (BasicLocation.DEBUG)
38                 System.out.println(NLS.bind(EclipseAdaptorMsg.location_cannotLock, lockFile));
39             // produce a more specific message for clients
40
String JavaDoc specificMessage = NLS.bind(EclipseAdaptorMsg.location_cannotLockNIO, new Object JavaDoc[] {lockFile, ioe.getMessage(), "\"-D" + BasicLocation.PROP_OSGI_LOCKING + "=none\""}); //$NON-NLS-1$ //$NON-NLS-2$
41
throw new IOException(specificMessage);
42         } catch (OverlappingFileLockException JavaDoc e) {
43             // handle it as null result
44
fileLock = null;
45         } finally {
46             if (fileLock != null)
47                 return true;
48             raFile.close();
49             raFile = null;
50         }
51         return false;
52     }
53
54     public synchronized void release() {
55         if (fileLock != null) {
56             try {
57                 fileLock.release();
58             } catch (IOException e) {
59                 //don't complain, we're making a best effort to clean up
60
}
61             fileLock = null;
62         }
63         if (raFile != null) {
64             try {
65                 raFile.close();
66             } catch (IOException e) {
67                 //don't complain, we're making a best effort to clean up
68
}
69             raFile = null;
70         }
71     }
72 }
73
Popular Tags