Skip to content

Commit 4ab52d8

Browse files
committed
Optimize the number of audio send factories
1 parent cf09a34 commit 4ab52d8

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

LavalinkServer/src/main/java/lavalink/server/io/SocketContext.java

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ public class SocketContext {
5555
private final Map<String, Player> players = new ConcurrentHashMap<>();
5656
private ScheduledExecutorService statsExecutor;
5757
public final ScheduledExecutorService playerUpdateService;
58+
private static final int audioSendFactoryCount = Runtime.getRuntime().availableProcessors() * 2;
59+
private final ConcurrentHashMap<Integer, IAudioSendFactory> sendFactories = new ConcurrentHashMap<>();
5860

5961
SocketContext(WebSocket socket, String userId, int shardCount) {
6062
this.socket = socket;
@@ -76,7 +78,7 @@ Core getCore(int shardId) {
7678
return cores.computeIfAbsent(shardId,
7779
__ -> {
7880
if (nasSupported)
79-
return new Core(userId, new CoreClientImpl(socket, shardId), createAudioSendFactory());
81+
return new Core(userId, new CoreClientImpl(socket, shardId), getAudioSendFactory(shardId));
8082
else
8183
return new Core(userId, new CoreClientImpl(socket, shardId));
8284
}
@@ -126,16 +128,18 @@ void shutdown() {
126128
players.values().forEach(Player::stop);
127129
}
128130

129-
private IAudioSendFactory createAudioSendFactory() {
130-
Integer customBuffer = Launcher.config.getBufferDurationMs();
131-
NativeAudioSendFactory nativeAudioSendFactory;
132-
if (customBuffer != null) {
133-
nativeAudioSendFactory = new NativeAudioSendFactory(customBuffer);
134-
} else {
135-
nativeAudioSendFactory = new NativeAudioSendFactory();
136-
}
131+
private IAudioSendFactory getAudioSendFactory(int shardId) {
132+
return sendFactories.computeIfAbsent(shardId % audioSendFactoryCount, integer -> {
133+
Integer customBuffer = Launcher.config.getBufferDurationMs();
134+
NativeAudioSendFactory nativeAudioSendFactory;
135+
if (customBuffer != null) {
136+
nativeAudioSendFactory = new NativeAudioSendFactory(customBuffer);
137+
} else {
138+
nativeAudioSendFactory = new NativeAudioSendFactory();
139+
}
137140

138-
return AsyncPacketProviderFactory.adapt(nativeAudioSendFactory);
141+
return AsyncPacketProviderFactory.adapt(nativeAudioSendFactory);
142+
});
139143
}
140144

141145
}

0 commit comments

Comments
 (0)