#1487 Updates hot code classes to remove usage of reentrant locks for thread synchronization. (#1488)

Co-authored-by: Dennis Sheirer <dsheirer@github.com>
This commit is contained in:
Denny Sheirer
2023-03-11 16:04:55 -05:00
committed by GitHub
parent 2d6c5c2331
commit f0dc80437c
4 changed files with 164 additions and 179 deletions

View File

@@ -44,7 +44,6 @@ import java.util.Map;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -481,7 +480,6 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
public class NativeBufferReceiver implements Listener<INativeBuffer> public class NativeBufferReceiver implements Listener<INativeBuffer>
{ {
private boolean mOutputProcessorUpdateRequired = false; private boolean mOutputProcessorUpdateRequired = false;
private ReentrantLock mUpdateFlagLock = new ReentrantLock();
/** /**
* Processes tuner center frequency change source events to flag when output processors need updating. * Processes tuner center frequency change source events to flag when output processors need updating.
@@ -492,20 +490,11 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
long frequency = event.getValue().longValue(); long frequency = event.getValue().longValue();
if(mChannelCalculator.getCenterFrequency() != frequency) if(mChannelCalculator.getCenterFrequency() != frequency)
{
mUpdateFlagLock.lock();
try
{ {
//Update the channel calculator frequency so that it's ready when the output processor update occurs //Update the channel calculator frequency so that it's ready when the output processor update occurs
mChannelCalculator.setCenterFrequency(frequency); mChannelCalculator.setCenterFrequency(frequency);
mOutputProcessorUpdateRequired = true; mOutputProcessorUpdateRequired = true;
} }
finally
{
mUpdateFlagLock.unlock();
}
}
} }
/** /**
@@ -515,20 +504,18 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
*/ */
@Override @Override
public void receive(INativeBuffer nativeBuffer) public void receive(INativeBuffer nativeBuffer)
{
mUpdateFlagLock.lock();
try
{ {
if(mOutputProcessorUpdateRequired) if(mOutputProcessorUpdateRequired)
{ {
updateOutputProcessors(); try
mOutputProcessorUpdateRequired = false;
}
}
finally
{ {
mUpdateFlagLock.unlock(); updateOutputProcessors();
}
catch(Exception e)
{
mLog.error("Error updating polyphase channel output processors");
}
mOutputProcessorUpdateRequired = false;
} }
if(mPolyphaseChannelizer != null) if(mPolyphaseChannelizer != null)

View File

@@ -28,12 +28,10 @@ import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.tuner.channel.StreamProcessorWithHeartbeat; import io.github.dsheirer.source.tuner.channel.StreamProcessorWithHeartbeat;
import io.github.dsheirer.source.tuner.channel.TunerChannel; import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource; import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Polyphase Channelizer's Tuner Channel Source implementation. Wraps a ChannelOutputProcessor instance and * Polyphase Channelizer's Tuner Channel Source implementation. Wraps a ChannelOutputProcessor instance and
@@ -47,12 +45,10 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
private StreamProcessorWithHeartbeat<ComplexSamples> mStreamHeartbeatProcessor; private StreamProcessorWithHeartbeat<ComplexSamples> mStreamHeartbeatProcessor;
private double mChannelSampleRate; private double mChannelSampleRate;
private long mIndexCenterFrequency; private long mIndexCenterFrequency;
private ReentrantLock mOutputProcessorLock = new ReentrantLock();
private List<Integer> mOutputProcessorIndexes = new ArrayList<>(); private List<Integer> mOutputProcessorIndexes = new ArrayList<>();
private double mTunerSampleRate; private double mTunerSampleRate;
private double mTunerCenterFrequency; private double mTunerCenterFrequency;
private PendingOutputProcessorUpdate mPendingOutputProcessorUpdate;
/** /**
* Constructs an instance * Constructs an instance
@@ -69,7 +65,7 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
super(producerSourceEventListener, tunerChannel); super(producerSourceEventListener, tunerChannel);
mChannelSampleRate = channelCalculator.getChannelSampleRate(); mChannelSampleRate = channelCalculator.getChannelSampleRate();
mStreamHeartbeatProcessor = new StreamProcessorWithHeartbeat<>(getHeartbeatManager(), HEARTBEAT_INTERVAL_MS); mStreamHeartbeatProcessor = new StreamProcessorWithHeartbeat<>(getHeartbeatManager(), HEARTBEAT_INTERVAL_MS);
updateOutputProcessor(channelCalculator, filterManager); doUpdateOutputProcessor(channelCalculator, filterManager);
} }
/** /**
@@ -150,18 +146,28 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
} }
/** /**
* Updates the output processor whenever the source tuner's center frequency changes. * Queues a request to update the output processor whenever the source tuner's center frequency changes.
* @param channelCalculator providing access to updated tuner center frequency, sample rate, etc. * @param channelCalculator providing access to updated tuner center frequency, sample rate, etc.
* @param filterManager for designing and caching synthesis filters * @param filterManager for designing and caching synthesis filters
*/ */
public void updateOutputProcessor(ChannelCalculator channelCalculator, SynthesisFilterManager filterManager) throws IllegalArgumentException public void updateOutputProcessor(ChannelCalculator channelCalculator, SynthesisFilterManager filterManager)
throws IllegalArgumentException
{
mPendingOutputProcessorUpdate = new PendingOutputProcessorUpdate(channelCalculator, filterManager);
}
/**
* Performs the output processor update. This method must be invoked on the channel results calling thread to
* ensure we don't have thread contention on the output processor.
* @param channelCalculator for updates
* @param filterManager for updates
* @throws IllegalArgumentException if there's an issue.
*/
public void doUpdateOutputProcessor(ChannelCalculator channelCalculator, SynthesisFilterManager filterManager)
throws IllegalArgumentException
{ {
String errorMessage = null; String errorMessage = null;
mOutputProcessorLock.lock();
try
{
//If a change in sample rate or center frequency makes this channel no longer viable, then the channel //If a change in sample rate or center frequency makes this channel no longer viable, then the channel
//calculator will throw an IllegalArgException ... handled below //calculator will throw an IllegalArgException ... handled below
List<Integer> indexes = channelCalculator.getChannelIndexes(getTunerChannel()); List<Integer> indexes = channelCalculator.getChannelIndexes(getTunerChannel());
@@ -191,7 +197,8 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
{ {
mLog.error("Error creating an updated synthesis filter for the channel output processor"); mLog.error("Error creating an updated synthesis filter for the channel output processor");
errorMessage ="Cannot update output processor - unable to design synthesis filter for [" + errorMessage ="Cannot update output processor - unable to design synthesis filter for [" +
indexes.size() + "] channel indices"; indexes.size() + "] channel indices - channel sample rate [" + channelCalculator.getChannelSampleRate() +
"] channel bandwidth [" + channelCalculator.getChannelBandwidth() + "]";
} }
} }
@@ -241,11 +248,6 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
indexes.size(); indexes.size();
} }
} }
}
finally
{
mOutputProcessorLock.unlock();
}
//Unlikely, but if we had an error designing a synthesis filter, throw an exception //Unlikely, but if we had an error designing a synthesis filter, throw an exception
if(errorMessage != null) if(errorMessage != null)
@@ -264,7 +266,13 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
*/ */
public void receiveChannelResults(List<float[]> channelResultsList, long currentSamplesTimestamp) public void receiveChannelResults(List<float[]> channelResultsList, long currentSamplesTimestamp)
{ {
mOutputProcessorLock.lock(); if(mPendingOutputProcessorUpdate != null)
{
ChannelCalculator channelCalculator = mPendingOutputProcessorUpdate.getChannelCalculator();
SynthesisFilterManager filterManager = mPendingOutputProcessorUpdate.getSynthesisFilterManager();
mPendingOutputProcessorUpdate = null;
doUpdateOutputProcessor(channelCalculator, filterManager);
}
try try
{ {
@@ -273,9 +281,9 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
mPolyphaseChannelOutputProcessor.receiveChannelResults(channelResultsList, currentSamplesTimestamp); mPolyphaseChannelOutputProcessor.receiveChannelResults(channelResultsList, currentSamplesTimestamp);
} }
} }
finally catch(Exception e)
{ {
mOutputProcessorLock.unlock(); mLog.error("Error processing channel results", e);
} }
} }
@@ -344,4 +352,40 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
return "POLYPHASE [" + mPolyphaseChannelOutputProcessor.getInputChannelCount() + "] " + return "POLYPHASE [" + mPolyphaseChannelOutputProcessor.getInputChannelCount() + "] " +
getTunerChannel().getFrequency(); getTunerChannel().getFrequency();
} }
/**
* Support classes needed to update the output processor.
*/
public class PendingOutputProcessorUpdate
{
private final ChannelCalculator mChannelCalculator;
private final SynthesisFilterManager mSynthesisFilterManager;
/**
* Constructs an instance
* @param channelCalculator for support
* @param synthesisFilterManager for support
*/
public PendingOutputProcessorUpdate(ChannelCalculator channelCalculator, SynthesisFilterManager synthesisFilterManager)
{
mChannelCalculator = channelCalculator;
mSynthesisFilterManager = synthesisFilterManager;
}
/**
* Channel calculator
*/
public ChannelCalculator getChannelCalculator()
{
return mChannelCalculator;
}
/**
* Channel calculator
*/
public SynthesisFilterManager getSynthesisFilterManager()
{
return mSynthesisFilterManager;
}
}
} }

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer * Copyright (C) 2014-2023 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -18,13 +18,11 @@
*/ */
package io.github.dsheirer.sample; package io.github.dsheirer.sample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Broadcasts an item to multiple listeners * Broadcasts an item to multiple listeners
@@ -32,8 +30,7 @@ import java.util.concurrent.locks.ReentrantLock;
public class Broadcaster<T> implements Listener<T> public class Broadcaster<T> implements Listener<T>
{ {
private final static Logger mLog = LoggerFactory.getLogger(Broadcaster.class); private final static Logger mLog = LoggerFactory.getLogger(Broadcaster.class);
private ReentrantLock mLock = new ReentrantLock(); private List<Listener<T>> mListeners = new CopyOnWriteArrayList<>();
private List<Listener<T>> mListeners = new ArrayList<>();
public Broadcaster() public Broadcaster()
{ {
@@ -90,27 +87,11 @@ public class Broadcaster<T> implements Listener<T>
*/ */
public void addListener(Listener<T> listener) public void addListener(Listener<T> listener)
{ {
if(listener != null) if(listener != null && !mListeners.contains(listener))
{
mLock.lock();
try
{
if(!mListeners.contains(listener))
{ {
mListeners.add(listener); mListeners.add(listener);
} }
} }
catch(Exception e)
{
mLog.error("Unexpected error while adding listener", e);
}
finally
{
mLock.unlock();
}
}
}
/** /**
* Deregisters the listener from receiving elements from this broadcaster * Deregisters the listener from receiving elements from this broadcaster
@@ -118,22 +99,9 @@ public class Broadcaster<T> implements Listener<T>
public void removeListener(Listener<T> listener) public void removeListener(Listener<T> listener)
{ {
if(listener != null) if(listener != null)
{
mLock.lock();
try
{ {
mListeners.remove(listener); mListeners.remove(listener);
} }
catch(Exception e)
{
mLog.error("Unexpected error while removing listener", e);
}
finally
{
mLock.unlock();
}
}
} }
/** /**
@@ -149,24 +117,16 @@ public class Broadcaster<T> implements Listener<T>
*/ */
public void broadcast(T t) public void broadcast(T t)
{ {
mLock.lock();
try try
{ {
List<Listener<T>> listeners = new ArrayList<>(mListeners); for(Listener<T> listener: mListeners)
for(Listener listener: listeners)
{ {
listener.receive(t); listener.receive(t);
} }
} }
catch(Exception e) catch(Exception e)
{ {
mLog.error("Unexpected error while broadcasting to listeners", e); mLog.error("Error while broadcasting [" + t.getClass() + "] to listeners");
}
finally
{
mLock.unlock();
} }
} }
} }

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer * Copyright (C) 2014-2023 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -22,10 +22,10 @@ package io.github.dsheirer.source.tuner.channel;
import io.github.dsheirer.sample.Listener; import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import io.github.dsheirer.util.ThreadPool; import io.github.dsheirer.util.ThreadPool;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Thread-safe implementation that coordinates the flow of data/buffer stream processing with a parallel, periodic * Thread-safe implementation that coordinates the flow of data/buffer stream processing with a parallel, periodic
@@ -42,7 +42,7 @@ import java.util.concurrent.locks.ReentrantLock;
*/ */
public class StreamProcessorWithHeartbeat<T> implements Listener<T> public class StreamProcessorWithHeartbeat<T> implements Listener<T>
{ {
private ReentrantLock mLock = new ReentrantLock(); private static final Logger mLog = LoggerFactory.getLogger(StreamProcessorWithHeartbeat.class);
private HeartbeatManager mHeartbeatManager; private HeartbeatManager mHeartbeatManager;
private long mHeartbeatInterval; private long mHeartbeatInterval;
private Listener<T> mListener; private Listener<T> mListener;
@@ -87,26 +87,20 @@ public class StreamProcessorWithHeartbeat<T> implements Listener<T>
* Optionally fires a heartbeat if we're not currently processing a native buffer * Optionally fires a heartbeat if we're not currently processing a native buffer
*/ */
private void fireOptionalHeartbeat() private void fireOptionalHeartbeat()
{
//Acquire lock only if it's not already locked, otherwise ignore heartbeat for this timer interval.
if(mLock.tryLock())
{ {
try try
{ {
mHeartbeatManager.broadcast(); mHeartbeatManager.broadcast();
} }
finally catch(Exception e)
{ {
mLock.unlock(); mLog.error("Error firing optional heartbeat", e);
}
} }
} }
@Override @Override
public void receive(T data) public void receive(T data)
{ {
mLock.lock();
try try
{ {
mHeartbeatManager.broadcast(); mHeartbeatManager.broadcast();
@@ -118,9 +112,9 @@ public class StreamProcessorWithHeartbeat<T> implements Listener<T>
listener.receive(data); listener.receive(data);
} }
} }
finally catch(Exception e)
{ {
mLock.unlock(); mLog.error("Error distributing data to listeners following heartbeat", e);
} }
} }