|
| 1 | +// Copyright 2019 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package com.google.firebase.installations; |
| 16 | + |
| 17 | +import android.content.Context; |
| 18 | +import java.io.File; |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.RandomAccessFile; |
| 21 | +import java.nio.channels.FileChannel; |
| 22 | +import java.nio.channels.FileLock; |
| 23 | + |
| 24 | +/** Use file locking to acquire a lock that will also block other processes. */ |
| 25 | +class CrossProcessLock { |
| 26 | + private final FileChannel channel; |
| 27 | + private final FileLock lock; |
| 28 | + |
| 29 | + private CrossProcessLock(FileChannel channel, FileLock lock) { |
| 30 | + this.channel = channel; |
| 31 | + this.lock = lock; |
| 32 | + } |
| 33 | + |
| 34 | + static CrossProcessLock acquire(Context appContext, String lockName) { |
| 35 | + try { |
| 36 | + File file = new File(appContext.getFilesDir(), lockName); |
| 37 | + FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); |
| 38 | + // Use the file channel to create a lock on the file. |
| 39 | + // This method blocks until it can retrieve the lock. |
| 40 | + FileLock lock = channel.lock(); |
| 41 | + return new CrossProcessLock(channel, lock); |
| 42 | + } catch (IOException e) { |
| 43 | + throw new IllegalStateException("exception while using file locks, should never happen", e); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /** Release a previously acquired lock and free any underlying resources. */ |
| 48 | + void releaseAndClose() { |
| 49 | + try { |
| 50 | + lock.release(); |
| 51 | + channel.close(); |
| 52 | + } catch (IOException e) { |
| 53 | + throw new IllegalStateException("exception while using file locks, should never happen", e); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments