KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > configurator > 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  *******************************************************************************/

11 package org.eclipse.update.internal.configurator;
12
13 import java.io.*;
14 import java.nio.channels.FileLock JavaDoc;
15 import java.nio.channels.OverlappingFileLockException JavaDoc;
16
17 /**
18  * Internal class.
19  */

20 public class Locker_JavaNio implements Locker {
21     private File lockFile;
22     private RandomAccessFile raf;
23     private FileLock JavaDoc fileLock;
24
25     public Locker_JavaNio(File lockFile) {
26         this.lockFile = lockFile;
27     }
28
29     public synchronized boolean lock() throws IOException {
30         raf = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
31
try{
32             fileLock = raf.getChannel().tryLock();
33         } catch(OverlappingFileLockException JavaDoc e) {
34             fileLock = null;
35         } finally {
36             if (fileLock != null)
37                 return true;
38             raf.close();
39             raf = null;
40         }
41         return false;
42     }
43
44     public synchronized void release() {
45         if (fileLock != null) {
46             try {
47                 fileLock.release();
48             } catch (IOException e) {
49                 //don't complain, we're making a best effort to clean up
50
}
51             fileLock = null;
52         }
53         if (raf != null) {
54             try {
55                 raf.close();
56             } catch (IOException e) {
57                 //don't complain, we're making a best effort to clean up
58
}
59             raf = null;
60         }
61         if (lockFile != null) {
62             lockFile.delete();
63             lockFile = null;
64         }
65     }
66 }
67
Popular Tags