KickJava   Java API By Example, From Geeks To Geeks.

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


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

11 package org.eclipse.core.runtime.adaptor;
12
13 import java.io.*;
14 import java.nio.channels.FileLock JavaDoc;
15 import org.eclipse.osgi.framework.log.FrameworkLogEntry;
16
17 /**
18  * Internal class.
19  */

20 public class Locker_JavaNio implements Locker {
21     private File lockFile;
22     private FileLock JavaDoc fileLock;
23     private FileOutputStream fileStream;
24
25     public Locker_JavaNio(File lockFile) {
26         this.lockFile = lockFile;
27     }
28
29     public synchronized boolean lock() throws IOException {
30         fileStream = new FileOutputStream(lockFile, true);
31         try {
32             fileLock = fileStream.getChannel().tryLock();
33         } catch (IOException ioe) {
34             // log the original exception if debugging
35
if (BasicLocation.DEBUG) {
36                 String JavaDoc basicMessage = EclipseAdaptorMsg.formatter.getString("location.cannotLock", lockFile); //$NON-NLS-1$
37
FrameworkLogEntry basicEntry = new FrameworkLogEntry(EclipseAdaptor.FRAMEWORK_SYMBOLICNAME, basicMessage, 0, ioe, null);
38                 EclipseAdaptor.getDefault().getFrameworkLog().log(basicEntry);
39             }
40             // produce a more specific message for clients
41
String JavaDoc specificMessage = EclipseAdaptorMsg.formatter.getString("location.cannotLockNIO", new Object JavaDoc[] {lockFile, ioe.getMessage(), BasicLocation.PROP_OSGI_LOCKING}); //$NON-NLS-1$
42
throw new IOException(specificMessage);
43         }
44         if (fileLock != null)
45             return true;
46         fileStream.close();
47         fileStream = null;
48         return false;
49     }
50
51     public synchronized void release() {
52         if (fileLock != null) {
53             try {
54                 fileLock.release();
55             } catch (IOException e) {
56                 //don't complain, we're making a best effort to clean up
57
}
58             fileLock = null;
59         }
60         if (fileStream != null) {
61             try {
62                 fileStream.close();
63             } catch (IOException e) {
64                 //don't complain, we're making a best effort to clean up
65
}
66             fileStream = null;
67         }
68     }
69 }
Popular Tags